Skip to content

Instantly share code, notes, and snippets.

@calebkleveter
Last active December 21, 2016 15:13
Show Gist options
  • Save calebkleveter/b2b34023d7707e33a194f6b9b2d05393 to your computer and use it in GitHub Desktop.
Save calebkleveter/b2b34023d7707e33a194f6b9b2d05393 to your computer and use it in GitHub Desktop.
static func authenticate(credentials: Credentials) throws -> Auth.User {
switch credentials {
case let id as Identifier:
guard let user = try User.find(id.id) else {
throw Abort.custom(status: .forbidden, message: "Invalid user identifier.")
}
return user
case let usernamePassword as UsernamePassword:
let fetchedUser = try User.query().filter("username", usernamePassword.username).first()
guard let user = fetchedUser else {
throw Abort.custom(status: .networkAuthenticationRequired, message: "User does not exist")
}
if try BCrypt.verify(password: usernamePassword.password, matchesHash: fetchedUser!.password) {
return user
} else {
throw Abort.custom(status: .networkAuthenticationRequired, message: "Invalid user name or password.")
}
default:
let type = type(of: credentials)
throw Abort.custom(status: .forbidden, message: "Unsupported credential type: \(type).")
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment