Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Authentication framework #21

Closed
wants to merge 5 commits into from
Closed
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Next Next commit
Authenticator middleware and request cache
  • Loading branch information
adam-fowler committed Jan 29, 2021
commit 57872e49b33c78ee0fd9cc7aff192d5ea880045a
13 changes: 13 additions & 0 deletions Sources/Hummingbird/Authentication/Authenticator.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
import NIO

public protocol HBAuthenticator: HBMiddleware {
func authenticate(request: HBRequest) -> EventLoopFuture<Void>
}

extension HBAuthenticator {
public func apply(to request: HBRequest, next: HBResponder) -> EventLoopFuture<HBResponse> {
authenticate(request: request).flatMap {
next.respond(to: request)
}
}
}
39 changes: 39 additions & 0 deletions Sources/Hummingbird/Authentication/Request+Auth.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
extension HBRequest {
public struct Auth {
/// Login with type
/// - Parameter auth: authentication details
public func login<Auth>(_ auth: Auth) {
var logins = self.loginCache ?? [:]
logins[ObjectIdentifier(Auth.self)] = auth
request.extensions.set(\.auth.loginCache, value: logins)
}

/// Logout type
/// - Parameter auth: authentication type
public func logout<Auth>(_ auth: Auth.Type) {
if var logins = self.loginCache {
logins[ObjectIdentifier(Auth.self)] = nil
request.extensions.set(\.auth.loginCache, value: logins)
}
}

/// Return authenticated type
/// - Parameter auth: Type required
public func get<Auth>(_ auth: Auth.Type) -> Auth? {
return loginCache?[ObjectIdentifier(Auth.self)] as? Auth
}

/// Return if request is authenticated with type
/// - Parameter auth: Authentication type
public func has<Auth>(_ auth: Auth.Type) -> Bool {
return loginCache?[ObjectIdentifier(Auth.self)] != nil
}

var loginCache: [ObjectIdentifier: Any]? { request.extensions.get(\.auth.loginCache) }

let request: HBRequest
}

/// Authentication object
public var auth: Auth { return .init(request: self) }
}