Auth in views via view.render


#1

I have this error handler (Exceptions/Handler.js):

'use strict'

const BaseExceptionHandler = use('BaseExceptionHandler')
const Env = use('Env')

/**
 * Error class handler.
 * 
 * @class ExceptionHandler
 */
class ExceptionHandler extends BaseExceptionHandler {
  /**
   * Handle exception thrown during the HTTP lifecycle.
   * 
   * @method handle
   */
  async handle ({ code, name, status }, { response }) {
    response.status(status || 500)

    /** Handle E_INVALID_SESSION error: */
    if (code === 'E_INVALID_SESSION') {
      return this._handleInvalidSession(...arguments)
    }

    /** Handle 404 error: */
    if (name === 'HttpException' && status === 404) {
      return this._handle404(...arguments)
    }

    /** If is in development: */
    if (Env.get('NODE_ENV') === 'development') {
      return super.handle(...arguments)
    }

    /** Handle 500 error (in production): */
    return this._handle500(...arguments)
  }

  /**
   * Handle invalid session error.
   * 
   * @method _handleInvalidSession
   */
  async _handleInvalidSession (error, { response, view }) {
    return response.send(view.render('errors.401'))
  }

  /**
   * Handle 404 HTTP error.
   * 
   * @method _handle404
   */
  async _handle404 (error, { response, view }) {
    return response.send(view.render('errors.404'))
  }

  /**
   * Handle 500 HTTP error.
   * 
   * @method _handle500
   */
  async _handle500 (error, { response, view }) {
    return response.send(view.render('errors.500'))
  }
}

module.exports = ExceptionHandler

But in views rendered for errors, even when authenticated, I do not have access to the auth object.

How can I solve this problem?

Regards.


#2

What’s you mean by don’t have access to auth?


#3

When I do:

{{ auth.user.username }}

Returns undefined.
But in normal views, it returns the username normally.


String to Number in View
#4

Hello, please help?


#5

A little bump.


#6

Hi guys? Need a little help here…


#7

I just tested it, and you’re right. Annoying to say the least.

I don’t know Adonis enough to tell you what the problem it. I can only confirm it exists.


#8

I noticed that auth.user object (in the context) is empty in error handling too:

auth.username // undefined

This is expected?


#9

Going to look into it today, seems weird, since the same object is passed to the error handler


#10

Okay, thanks a lot, Virk!! :smiley:


#11

A little bump. [2]


#12

Two questions for me.

  • Was it working before?
  • Have you correctly setup the AuthInit middleware?

Note that user is shared with the view layer.

So you may use the code bellow.

{{ user.username }}

#13

@lffg Works fine for me. Created a same repo here https://github.com/thetutlage/exceptions-view-auth

Make sure to run adonis migration:run


#14

@virk Think you were meant to tag @lffg - I haven’t been involved in this one! :grinning:


#15

Nope.

Yes. Here is my kernel.js file:

'use strict'

const Server = use('Server')

/*
|--------------------------------------------------------------------------
| Global Middleware
|--------------------------------------------------------------------------
|
| Global middleware are executed on each http request only when the routes
| match.
|
*/
const globalMiddleware = [
  'Adonis/Middleware/BodyParser',
  'Adonis/Middleware/Session',
  'Adonis/Middleware/Shield',
  'Adonis/Middleware/AuthInit',

  'App/Middleware/View/Userdata',
  'App/Middleware/View/Group',

  'App/Middleware/Shield/ActiveChecker',
  'App/Middleware/Shield/IpCollector'
]

/*
|--------------------------------------------------------------------------
| Named Middleware
|--------------------------------------------------------------------------
|
| Named middleware is key/value object to conditionally add middleware on
| specific routes or group of routes.
|
| // define
| {
|   auth: 'Adonis/Middleware/Auth'
| }
|
| // use
| Route.get().middleware('auth')
|
*/
const namedMiddleware = {
  'auth'       : 'Adonis/Middleware/Auth',
  'not-auth'   : 'App/Middleware/Shield/NotAuth',
  'admin'      : 'App/Middleware/Shield/Admin'
}

/*
|--------------------------------------------------------------------------
| Server Middleware
|--------------------------------------------------------------------------
|
| Server level middleware are executed even when route for a given URL is
| not registered. Features like `static assets` and `cors` needs better
| control over request lifecycle.
|
*/
const serverMiddleware = [
  'Adonis/Middleware/Static',
  'Adonis/Middleware/Cors'
]

Server
  .registerGlobal(globalMiddleware)
  .registerNamed(namedMiddleware)
  .use(serverMiddleware)

@virk, I’ve copied your Handler.js file and put it in my project, but the error persists.

'use strict'

const BaseExceptionHandler = use('BaseExceptionHandler')

class ExceptionHandler extends BaseExceptionHandler {
  async handle (error, { request, view, response, auth }) {
    console.log(auth.user.username)
    response.send(view.render('errors.404'))
  }
}

module.exports = ExceptionHandler

I also updated my dependencies, but the error persists.

"dependencies": {
  "@adonisjs/ace": "^5.0.2",
  "@adonisjs/auth": "^3.0.5",
  "@adonisjs/bodyparser": "^2.0.3",
  "@adonisjs/cors": "^1.0.6",
  "@adonisjs/fold": "^4.0.8",
  "@adonisjs/framework": "^5.0.7",
  "@adonisjs/ignitor": "^2.0.6",
  "@adonisjs/lucid": "^5.0.4",
  "@adonisjs/mail": "^3.0.6",
  "@adonisjs/session": "^1.0.25",
  "@adonisjs/shield": "^1.0.6",
  "@adonisjs/validator": "^5.0.3",
  "got": "^8.3.1",
  "lodash": "^4.17.10",
  "moment": "^2.22.1",
  "mysql": "^2.15.0",
  "yiq": "^1.0.0"
}

What am I missing?


#16

Yeah my bad :hugs:


#17

Guys, after a few attempts, I noticed that the auth.user object is apparently inaccessible in 404 errors. If I emulate an 500 error, for example:

Route.get ('/test', () => {
  throw new Error ('Test.')
})

I can get the auth.user object.
But as I said above, in 404 errors, no (auth.user returns null).

:thinking:


#18

I have shared a repo, please use that to help reproduce the issue


#19

@virk, the result is the same. :frowning:

Note: I ran adonis migration: run.


#20

Did you visited the /404 page directly?