-
Notifications
You must be signed in to change notification settings - Fork 2
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
f7a12f2
commit 3dab7b0
Showing
1 changed file
with
56 additions
and
0 deletions.
There are no files selected for viewing
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,56 @@ | ||
// | ||
// ModelAuthenticatable.swift | ||
// | ||
// | ||
// Created by Mihael Isaev on 12.02.2022. | ||
// | ||
|
||
import Vapor | ||
import Bridges | ||
|
||
public protocol ModelAuthenticatable: Table, Authenticatable { | ||
static var usernameKey: KeyPath<Self, Column<String>> { get } | ||
static var passwordHashKey: KeyPath<Self, Column<String>> { get } | ||
func verify(password: String) throws -> Bool | ||
} | ||
|
||
extension ModelAuthenticatable { | ||
public static func authenticator( | ||
database: DatabaseIdentifier | ||
) -> Authenticator { | ||
ModelAuthenticator<Self>(database: database) | ||
} | ||
|
||
var _$username: Column<String> { | ||
self[keyPath: Self.usernameKey] | ||
} | ||
|
||
var _$passwordHash: Column<String> { | ||
self[keyPath: Self.passwordHashKey] | ||
} | ||
} | ||
|
||
private struct ModelAuthenticator<User>: BasicAuthenticator | ||
where User: ModelAuthenticatable | ||
{ | ||
public let database: DatabaseIdentifier | ||
|
||
public func authenticate( | ||
basic: BasicAuthorization, | ||
for request: Request | ||
) -> EventLoopFuture<Void> { | ||
User.query(on: database, on: request) | ||
.where(\User._$username == basic.username) | ||
.first() | ||
.flatMapThrowing | ||
{ | ||
guard let user = $0 else { | ||
return | ||
} | ||
guard try user.verify(password: basic.password) else { | ||
return | ||
} | ||
request.auth.login(user) | ||
} | ||
} | ||
} |