2

I'm building RESTful api with adonisjs. I face this problem in jwt login module. Look at the code below:

async login({request, auth, response}) {

    let {email, password} = request.all()

    try {
      if (await auth.attempt(email, password)) {
        let user = await User.findBy('email', email)
        let token = await auth.generate(user)
        user.password = undefined
        Object.assign(user, token)
        //------------------------------------------
        const assignedToken = await Token.create({
          user_id: user.id,
          token,
        })
        // -------- i'd like to catch exception here...
        return response.json({
          success: true,
          user
        })
      }
    } catch(e) {
        return response.json({
          success: false,
          message: 'login_failed'
        })
    }
  }

I'd like to catch possible exception while persisting jwt token to database. I am rather new to adonis. I checked their doc but cannot find exact return type. Do they throw an exception? Or just return null/false? I have no idea. Do you have any?

glinda93
  • 7,659
  • 5
  • 40
  • 78

1 Answers1

1

Do they throw an exception?

Yes

An exception will appear if there is a problem during creation. You can create a new try/catch inside you try/catch. Like:

async login({request, auth, response}) {
...
  try {
    ...
    try { // New try/catch
      const assignedToken = await Token.create({
        user_id: user.id,
        token,
      })
    } catch (error) {
      // Your exception
      return ...
    }
    return response.json({
      success: true,
      user
    })
  }catch (e) {
    ...
  }
}

It's the simplest solution. I would do it this way because there can be different types of errors.

crbast
  • 2,192
  • 1
  • 11
  • 21
  • 2
    You're right. Btw, do you think persisting jwt token is a good idea? Esp. when it's done by myself? Do they have any 'official' way to do this in a proper way? – glinda93 Jan 05 '20 at 17:12
  • 1
    Normally tokens (not refresh tokens) are not saved in the db. I don't think there's any point in saving the tokens. Because the principle is to be able to use them without storing them in the db. Except the refresh token which is stored in the db. – crbast Jan 05 '20 at 17:16
  • 1
    In stateless REST api, how does node.js remember jwt tokens? In memory? I recently migrated from Laravel to adonis. So I might not have common sense in nodejs way. – glinda93 Jan 05 '20 at 17:18
  • 1
    Refresh tokens : https://auth0.com/blog/refresh-tokens-what-are-they-and-when-to-use-them/ – crbast Jan 05 '20 at 17:51