Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import Async
- import Bits
- import Fluent
- import Authentication
- import MongoKitten
- /// Authenticatable by `Basic username:password` auth.
- public protocol MongoBasicAuthenticatable: Authenticatable {
- /// Key path to the username
- typealias UsernameKey = WritableKeyPath<Self, String>
- /// The key under which the user's username,
- /// email, or other identifing value is stored.
- static var usernameKey: UsernameKey { get }
- /// Key path to the password
- typealias PasswordKey = WritableKeyPath<Self, String>
- /// The key under which the user's password
- /// is stored.
- static var passwordKey: PasswordKey { get }
- /// Authenticates using the supplied credentials, connection, and verifier.
- static func authenticate(using basic: BasicAuthorization, verifier: PasswordVerifier, on collection: MongoKitten.Collection) -> Future<Self?>
- }
- extension MongoBasicAuthenticatable where Self: Model {
- /// See `BasicAuthenticatable`.
- public static func authenticate(using basic: BasicAuthorization, verifier: PasswordVerifier, on collection: MongoKitten.Collection) -> Future<Self?> {
- return collection.findOne("username" == basic.username).map({ (document) -> (Self?) in
- guard let document = document else {
- return nil
- }
- let user = try document.user()
- guard try verifier.verify(basic.password, created: user.basicPassword) else {
- return nil
- }
- return user as? Self
- })
- }
- }
- extension MongoBasicAuthenticatable {
- /// Accesses the model's password
- public var basicPassword: String {
- get { return self[keyPath: Self.passwordKey] }
- set { self[keyPath: Self.passwordKey] = newValue }
- }
- /// Accesses the model's username
- public var basicUsername: String {
- get { return self[keyPath: Self.usernameKey] }
- set { self[keyPath: Self.usernameKey] = newValue }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement