You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
I just ported another useful Laravel Redirector feature called "intended URL" to the Redirect class in Adonis.js Router.
An example scenario for this is when a user tries to visit an authenticated page, maybe from a deeplink or email notification, and they are redirected to the login route because they are not logged in. What will happen is that they will be redirected to whatever route the login controller method decides, which obviously means the user needs to start the whole process of opening their intended URL all over again.
Make sure you have enabled useAsyncLocalStorage in the config/app.ts file, and you have set up the Adonis Session package and then add the extension below to the app provider:
importtype{ApplicationService}from'@adonisjs/core/types'import{HttpContext,Redirect}from'@adonisjs/core/http'declare module '@adonisjs/core/http'{exportinterfaceRedirect{/** * Create a new redirect response while putting the current URL in the session. */guest(path: string,statusCode?: number,headers?: Record<string,string>): void/** * Create a new redirect response to the previously intended location. */intended(path?: string,statusCode?: number,headers?: Record<string,string>): void/** * Get the "intended" URL from the session. */getIntendedUrl(): string|null/** * Set the "intended" URL in the session. */setIntendedUrl(intendedUrl: string|null): this
}}exportdefaultclassAppProvider{constructor(protectedapp: ApplicationService){}/** * Register bindings to the container */register(){//}/** * The container bindings have booted */asyncboot(){Redirect.prototype.guest=function(this: Redirect,path: string,statusCode: number=302,headers={}){constctx=HttpContext.get()constintended=ctx?.request?.url(true)if(intended){this.setIntendedUrl(intended)}Object.entries(headers).forEach(([key,value])=>{ctx?.response?.header(key,value)})returnthis.status(statusCode).toPath(path)}Redirect.prototype.intended=function(this: Redirect,path: string='/',statusCode: number=302,headers={}){constctx=HttpContext.get()constintendedUrl=ctx?.session?.pull('intended.url')??pathObject.entries(headers).forEach(([key,value])=>{ctx?.response?.header(key,value)})returnthis.status(statusCode).toPath(intendedUrl)}Redirect.prototype.setIntendedUrl=function(this: Redirect,url: string){constctx=HttpContext.get()ctx?.session?.put('intended.url',url)returnthis}Redirect.prototype.getIntendedUrl=function(this: Redirect){constctx=HttpContext.get()returnctx?.session?.get('intended.url')??null}}/** * The application has been booted */asyncstart(){//}/** * The process has been started */asyncready(){//}/** * Preparing to shut down the app */asyncshutdown(){//}}
Now, update the app/middleware/auth_middleware.ts contents with everything below:
import{errorsasauthErrors}from'@adonisjs/auth'importtype{Authenticators}from'@adonisjs/auth/types'importtype{HttpContext}from'@adonisjs/core/http'importtype{NextFn}from'@adonisjs/core/types/http'/** * Auth middleware is used to authenticate HTTP requests and deny * access to unauthenticated users. */exportdefaultclassAuthMiddleware{/** * The route to redirect to when authentication fails */redirectTo='/login'asynchandle(ctx: HttpContext,next: NextFn,options: {guards?: (keyofAuthenticators)[]}={}){try{awaitctx.auth.authenticateUsing(options.guards)}catch(error){if(errorinstanceofauthErrors.E_UNAUTHORIZED_ACCESS){returnctx.response.redirect().guest(this.redirectTo)}throwerror}returnnext()}}
Then, in your login controller, you can do something like this:
reacted with thumbs up emoji reacted with thumbs down emoji reacted with laugh emoji reacted with hooray emoji reacted with confused emoji reacted with heart emoji reacted with rocket emoji reacted with eyes emoji
Uh oh!
There was an error while loading. Please reload this page.
-
Hello everyone!
I just ported another useful Laravel Redirector feature called "intended URL" to the Redirect class in Adonis.js Router.
An example scenario for this is when a user tries to visit an authenticated page, maybe from a deeplink or email notification, and they are redirected to the login route because they are not logged in. What will happen is that they will be redirected to whatever route the login controller method decides, which obviously means the user needs to start the whole process of opening their intended URL all over again.
Make sure you have enabled
useAsyncLocalStoragein theconfig/app.tsfile, and you have set up the Adonis Session package and then add the extension below to the app provider:Now, update the
app/middleware/auth_middleware.tscontents with everything below:Then, in your login controller, you can do something like this:
And you are good to go!
Beta Was this translation helpful? Give feedback.
All reactions