Single route with Guest and Auth middleware

Is this possible in Adonis Js to make a single route sometimes Guest and sometimes Auth on condition.

like when register has value role_id = 1 in request this does not require Auth middleware, however when role_id =2 it check Authentication

 Route.post('register', 'AuthController.register')
 Route.post('register', 'AuthController.register')..middleware(['auth'])
1 Like

I advise you to create a custom middleware with auth object. Like:

...
async handle({ response, auth, request }, next) {
  // call next to advance the request
  const role = request.input('role_id')
  if(role == 2){
    try {
	await auth.check();
    } catch (error) { ... }
  }
  await next();
}
3 Likes

Do we always call .middleware[‘auth’] on routes even when we have a customAuth?

Basically, if we make a custom auth as below, do we still use middleware[‘auth’,‘customAuth’] or is middleware[‘customAuth’] on that route fine.

Custom Auth

try {
	await auth.check();
	return view.render('/home')
    } catch (error) { 
return view.render('auth/login') 
}
2 Likes

If you create your own authentication middleware you don’t need to use the default one. But of course, we mustn’t forget: await auth.check(); :wink:

For your example, you don’t need to use middleware auth

You might be interested in this: auth middleware source code

2 Likes