How to use Vapor Middleware
saroar opened this issue · 3 comments
saroar commented
saroar commented
import Vapor
import JWT
import MongoKitten
public final class JWTMiddleware: Middleware {
public init() {}
public func respond(to request: Request, chainingTo next: Responder) -> EventLoopFuture<Response> {
guard let token = request.headers.bearerAuthorization?.token.utf8 else {
return request.eventLoop.makeFailedFuture(
Abort(.unauthorized, reason: "Missing authorization bearer header")
)
}
do {
request.payload = try request.jwt.verify(Array(token), as: Payload.self)
} catch let JWTError.claimVerificationFailure(name: name, reason: reason) {
request.logger.error("JWT Verification Failure: \(name) \(reason)")
return request.eventLoop.makeFailedFuture(JWTError.claimVerificationFailure(name: name, reason: reason))
} catch let error {
return request.eventLoop.makeFailedFuture(
Abort(.unauthorized, reason: "You are not authorized this token \(error)")
)
}
return next.respond(to: request)
}
}
extension AnyHashable {
static let payload: String = "jwt_payload"
}
extension Request {
var loggedIn: Bool {
return self.storage[PayloadKey.self] != nil ? true : false
}
var payload: Payload {
get { self.storage[PayloadKey.self]! } // should not use it
set { self.storage[PayloadKey.self] = newValue }
}
}
saroar commented
my routes
try app.group("v1") { api in
let events = api.grouped("events")
let eventsAuth = events.grouped(JWTMiddleware())
try eventsAuth.register(collection: EventController() )
}
// inside controller i use like this
if request.loggedIn == false { throw Abort(.unauthorized) }
but for vapor-router no option
stephencelis commented
Hi @saroar! Since this is a question and not a bug report, I'm going to convert this to a discussion where more eyes might see it. If there is a deficiency in the library we'd definitely take a PR to correct it, though!