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)
}
1) Return View doesn’t make a new requests, it renders the view without changing URLs in the browser’s address bar. (ie., simple like Server.Transfer () ) 2) Return RedirectToAction makes a new requests and URL in the browser’s address bar is changed (ie., simple like Response.Redirect () )
The redirect () method of the Response interface returns a Response resulting in a redirect to the specified URL. Note: This is mainly relevant to the ServiceWorker API. A controlling service worker could intercept a page's request and redirect it as desired.
2) Return RedirectToAction makes a new requests and URL in the browser’s address bar is changed (ie., simple like Response.Redirect () ) In this above,it will generate the URL for you based on your route table.CustomerID will pass to the customerDetail action method under the CustomerFolder
Redirect With the RedirectView Let's start with this simple approach – and go straight to an example: Behind the scenes, RedirectView will trigger a HttpServletResponse.sendRedirect () – which will perform the actual redirect.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With