Help for Identify - Auth Admin and Normal User

Hi there,

In my app, I have two different roles for user: i) admin; and ii) driver. For some routes, I want to verify if an user is an admin, before run the controller. I don’t want put a ‘if’ to check the role every single method inside controller.

How can I do that?

Thank you,

Hi :wave:,

You can use middleware.
I have a similar case in one of my projects:

Full gitlab project

Adonis doc - Auth

Have a nice day!

1 Like

Hi @CrBast,

Thanks for answer me,

Just to understand more about adonis, in your code, you don’t return a response with status 200. Why?

Have a nice day!

Hi :smiley:,

The answer is not 200 because the authentication failed or the account is not an administrator : throw new Error('Need admin privileges') -> go to catch()

If the account is an admin : await next() is called

Adonis documentation - next()

HI @CrBast,

Thanks for information,

I simplified the handle method, and it works fine.

  async handle({ response, auth }, next) {
    // call next to advance the request
    await auth.check()

    if (auth.user.type != 'adm')
      return response.status(401).json()

    await next()

I think throw an Error, makes more sense when you handle the Exception, outside the class.

Best regards,

1 Like

Hi @CrBast,

Thanks for information about try-catch.

Have a nice a weekend,

1 Like