Created
July 29, 2017 00:01
-
-
Save JoeyBodnar/1451673fa0eee3678f89deae0874c42d 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
import Foundation | |
import Vapor | |
import HTTP | |
import AuthProvider | |
import JWT | |
final class ExampleUsersController { | |
private let droplet: Droplet | |
init(droplet: Droplet) { | |
self.droplet = droplet | |
} | |
func addRoutes() { | |
let user = droplet.grouped(["user"]) | |
user.get("all", handler: index) | |
user.post("create", handler: create) | |
user.post("login", handler: login) | |
} | |
func index(req: Request) throws -> ResponseRepresentable { | |
return try ExampleUser.all().makeJSON() | |
} | |
func login(request: Request) throws -> ResponseRepresentable { | |
if let username = request.data[ExampleUser.nameKey]?.string, let password = request.data[ExampleUser.passwordKey]?.string { | |
let credentials = Password(username: username, password: password) | |
do { | |
let user = try ExampleUser.authenticate(credentials) | |
let token = try Token.createJwt(from: user) | |
return try JSON(node: ["username": user.username, "token": token]) | |
} catch let error { | |
return try JSON(node: ["error": error.localizedDescription]) | |
} | |
} | |
else { return try JSON(node: ["error": LoginSignupError.missingField.description])} | |
} | |
func create(request: Request) throws -> ResponseRepresentable { | |
if let username = request.data[ExampleUser.nameKey]?.string, let confirmPassword = request.data[ExampleUser.confirmPasswordKey]?.string, let password = request.data[ExampleUser.passwordKey]?.string { | |
if confirmPassword != password { | |
return try JSON(node: ["error": LoginSignupError.passwordMismatch.description]) | |
} | |
do { | |
let passwordHashed = try ExampleUser.hasher.make(password) | |
let user = try ExampleUser(username: username, password: passwordHashed) | |
try user.save() | |
return user | |
} catch let error { return try JSON(node: ["error": error])} | |
} | |
else { return try JSON(node: ["error": LoginSignupError.missingField.description]) } | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment