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

Combining with manual auth middleware #85

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Changes from all commits
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
20 changes: 14 additions & 6 deletions Sources/ImperialCore/Middleware/ImperialMiddleware.swift
Original file line number Diff line number Diff line change
Expand Up @@ -5,26 +5,34 @@ public class ImperialMiddleware: Middleware {

/// The path to redirect the user to if they are not authenticated.
let redirectPath: String?
/// The Middleware for responding after error
let onErrorMiddleware: Middleware?

/// Creates an instance of `ImperialMiddleware` with the option of a redirect path.
///
/// - Parameter redirect: The path to redirect a user to if they do not have an access token.
public init(redirect: String? = nil) {
/// - Parameter onErrorMiddleware: The middleware for responding on oAuth error (might be used for e.g. for manual Authenticable)
public init(redirect: String? = nil, onErrorMiddleware: Middleware? = nil) {
self.redirectPath = redirect
self.onErrorMiddleware = onErrorMiddleware
}

/// Checks that the request contains an access token. If it does, let the request through. If not, redirect the user to the `redirectPath`.
/// Checks that the request contains an access token. If it does, let the request through.
/// If not, calls respond method from `onErrorMiddleware` if it exists. if not, redirect the user to the `redirectPath`.
/// If the `redirectPath` is `nil`, then throw the error from getting the access token (Abort.unauthorized).
public func respond(to request: Request, chainingTo next: Responder) -> EventLoopFuture<Response> {
do {
_ = try request.accessToken()
return next.respond(to: request)
} catch let error as Abort where error.status == .unauthorized {
guard let redirectPath = redirectPath else {
return request.eventLoop.makeFailedFuture(error)
guard let onErrorMiddleware = onErrorMiddleware else {
guard let redirectPath = redirectPath else {
return request.eventLoop.makeFailedFuture(error)
}
let redirect: Response = request.redirect(to: redirectPath)
return request.eventLoop.makeSucceededFuture(redirect)
}
let redirect: Response = request.redirect(to: redirectPath)
return request.eventLoop.makeSucceededFuture(redirect)
return onErrorMiddleware.respond(to: request, chainingTo: next)
} catch let error {
return request.eventLoop.makeFailedFuture(error)
}
Expand Down