Get auth on constructor controller?

Hi guys!

I need get auth on constructor of class. Is possible?

example

class UserController {
  constructor({ auth }) {
    console.log(auth);
  }

this route will be in the middleware auth

1 Like

Hey @henriqueweiand! :wave:

You cannot receive the context in the constuctor of your controller.
If you need to inject it inside other classes/services you will need to do it directly in your route handler.

1 Like

@henriqueweiand

An example in the routes:

Route.post('/your_url', async ({response, request, auth }) => {
  return response.ok({status: true})
}).middleware(['your_middleware_if_needed'])

And example in your controller:

class UserController {

  async login ({ auth, request }) {
    const { email, password } = request.all()
    await auth.attempt(email, password)

    return 'Logged in successfully'
  }
}

For more info please read this link: https://adonisjs.com/docs/4.1/authentication#_basic_example

Basically don’t add it to the constructor add it to the actual url-action that match the route

Regards

2 Likes