I have a route handler which returns a Future for my login page, defined as follows :
func boot(router: Router) throws {
let authSessionRoutes = router.grouped(User.authSessionsMiddleware())
authSessionRoutes.get("/login", use: loginHandler)
}
func loginHandler(_ req: Request) throws -> Future<View> {
return try req.view().render("loginPage")
}
This works well when the user is not connected, but I'd like to add logic so that any authenticated user trying to access this page would be redirected to their homepage instead.
Here's what I tried :
func loginHandler(_ req: Request) throws -> Future<View> {
if let _ = try req.authenticated(User.self) {
return req.redirect(to: "/") <<< Cannot convert return expression of type 'Response' to return type 'EventLoopFuture<View>'
}
return try req.view().render("loginPage")
}
This tells me that since my loginHandler is expected to return a Future<View>
, returning a Response
does not conform to the method's definition.
What would be the best way to handle this case?
EDIT :
Thanks for the answer ! My final code looks like so :
func loginHandler(_ req: Request) throws -> Future<Response> {
if let _ = try req.authenticated(User.self) {
return req.future().map() {
return req.redirect(to: "/")
}
}
return try req.view().render("loginPage").encode(for: req)
}
You have two options - you can either use the Abort.redirect(to:)
error and throw that instead of calling the redirect.
Otherwise you can change the return type to Future<Response>
and convert the rendered view to a response.