Advertisement
Guest User

Untitled

a guest
Jun 24th, 2019
86
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.85 KB | None | 0 0
  1. import Async
  2. import Bits
  3. import Fluent
  4. import Authentication
  5. import MongoKitten
  6.  
  7. /// Authenticatable by `Basic username:password` auth.
  8. public protocol MongoBasicAuthenticatable: Authenticatable {
  9. /// Key path to the username
  10. typealias UsernameKey = WritableKeyPath<Self, String>
  11.  
  12. /// The key under which the user's username,
  13. /// email, or other identifing value is stored.
  14. static var usernameKey: UsernameKey { get }
  15.  
  16. /// Key path to the password
  17. typealias PasswordKey = WritableKeyPath<Self, String>
  18.  
  19. /// The key under which the user's password
  20. /// is stored.
  21. static var passwordKey: PasswordKey { get }
  22.  
  23. /// Authenticates using the supplied credentials, connection, and verifier.
  24. static func authenticate(using basic: BasicAuthorization, verifier: PasswordVerifier, on collection: MongoKitten.Collection) -> Future<Self?>
  25. }
  26.  
  27. extension MongoBasicAuthenticatable where Self: Model {
  28. /// See `BasicAuthenticatable`.
  29. public static func authenticate(using basic: BasicAuthorization, verifier: PasswordVerifier, on collection: MongoKitten.Collection) -> Future<Self?> {
  30.  
  31. return collection.findOne("username" == basic.username).map({ (document) -> (Self?) in
  32.  
  33. guard let document = document else {
  34. return nil
  35. }
  36.  
  37. let user = try document.user()
  38.  
  39. guard try verifier.verify(basic.password, created: user.basicPassword) else {
  40. return nil
  41. }
  42.  
  43. return user as? Self
  44. })
  45. }
  46. }
  47.  
  48. extension MongoBasicAuthenticatable {
  49. /// Accesses the model's password
  50. public var basicPassword: String {
  51. get { return self[keyPath: Self.passwordKey] }
  52. set { self[keyPath: Self.passwordKey] = newValue }
  53. }
  54.  
  55. /// Accesses the model's username
  56. public var basicUsername: String {
  57. get { return self[keyPath: Self.usernameKey] }
  58. set { self[keyPath: Self.usernameKey] = newValue }
  59. }
  60. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement