Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.