Created
September 3, 2017 23:05
-
-
Save JoeyBodnar/4db508fb67d744f44b3f00f4df2d4c7b to your computer and use it in GitHub Desktop.
Http Auth tutorial, user.swift
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
import AuthProvider | |
import FluentProvider | |
import HTTP | |
import Vapor | |
extension User: ResponseRepresentable {} | |
extension User: Timestampable {} | |
final class User: Model { | |
let storage = Storage() | |
static let idKey = "id" | |
static let emailKey = "email" | |
static let passwordKey = "password" | |
var email: String | |
var password: Bytes | |
init(email: String, password: Bytes) throws { | |
self.email = email | |
self.password = password | |
} | |
init(row: Row) throws { | |
email = try row.get(User.emailKey) | |
let passwordAsString:String = try row.get(User.passwordKey) | |
password = passwordAsString.makeBytes() | |
} | |
func makeRow() throws -> Row { | |
var row = Row() | |
try row.set(User.emailKey, email) | |
try row.set(User.passwordKey, password.makeString()) | |
return row | |
} | |
} | |
extension User: JSONConvertible { | |
convenience init(json: JSON) throws { | |
let passwordAsString: String = try json.get(User.passwordKey) | |
try self.init(email: json.get(User.emailKey), | |
password: User.hasher.make(passwordAsString)) | |
} | |
func makeJSON() throws -> JSON { | |
var json = JSON() | |
try json.set(User.idKey, id) | |
try json.set(User.emailKey, email) | |
return json | |
} | |
} | |
// boilerplate Preparation | |
extension User: Preparation { | |
static func prepare(_ database: Database) throws { | |
try database.create(self) { builder in | |
builder.id() | |
builder.string(User.emailKey) | |
builder.string(User.passwordKey) | |
} | |
} | |
/// Undoes what was done in `prepare` | |
static func revert(_ database: Database) throws { | |
try database.delete(self) | |
} | |
} | |
extension User: NodeRepresentable { } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment