Created
July 28, 2017 23:59
-
-
Save JoeyBodnar/1ea0a16a3c64acb1a23cb5332f239860 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
extension ExampleUser: ResponseRepresentable {} | |
extension ExampleUser: Timestampable {} | |
final class ExampleUser: Model, PasswordAuthenticatable { | |
let storage = Storage() | |
public static let hasher = BCryptHasher(cost: 10) | |
static let nameKey = "email" // Vapor expects this to be set to email, even though it is the username | |
static let passwordKey = "password" | |
static let confirmPasswordKey = "confirmPassword" | |
public static let passwordVerifier: PasswordVerifier? = ExampleUser.hasher | |
var username: String | |
var password: Bytes | |
var hashedPassword: String? { | |
return password.makeString() | |
} | |
init(username: String, password: Bytes) throws { | |
self.username = username | |
self.password = password | |
} | |
init(row: Row) throws { | |
username = try row.get(ExampleUser.nameKey) | |
let passwordAsString:String = try row.get(ExampleUser.passwordKey) | |
password = passwordAsString.makeBytes() | |
} | |
func makeRow() throws -> Row { | |
var row = Row() | |
try row.set(ExampleUser.nameKey, username) | |
try row.set(ExampleUser.passwordKey, hashedPassword) | |
return row | |
} | |
} | |
extension ExampleUser: Preparation { | |
static func prepare(_ database: Database) throws { | |
try database.create(self) { builder in | |
builder.id() | |
builder.string(ExampleUser.nameKey) | |
builder.string(ExampleUser.passwordKey) | |
} | |
} | |
/// Undoes what was done in `prepare` | |
static func revert(_ database: Database) throws { | |
try database.delete(self) | |
} | |
} | |
extension ExampleUser: JSONConvertible { | |
convenience init(json: JSON) throws { | |
let passwordAsString: String = try json.get(ExampleUser.passwordKey) | |
try self.init(username: json.get(ExampleUser.nameKey), password: ExampleUser.hasher.make(passwordAsString)) | |
} | |
func makeJSON() throws -> JSON { | |
var json = JSON() | |
try json.set(ExampleUser.nameKey, username) | |
return json | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment