0
votes

I'm stumbling my way around learning how to use Nuxt-Auth, and I currently have a local strategy working with JWT. I'm now looking to get the current user (on the server via express) before making a call to the database.

My first thought is to parse the JWT in the request header and grab the stored user id. However, seeing that I am using nuxt-auth middleware, perhaps there is a built-in method available? The documentation for nuxt-auth is particularly light.

In short, I know how to get the current user on the client side using nuxt-auth. Is there a server-side method? Pointing me to any documentation would be super helpful. Thanks!

1

1 Answers

0
votes

Searching for a nuxt-auth solution did not yield any results, so I have opted to write a simple express middleware that decodes the JWT and include the payload (which contains the user information) in the req object.

Edit: As per @kamal's request:

const jsonwebtoken = require('jsonwebtoken')
const tokenSecret = 'whateversecrethere'
const accessTokenExpiry = 15 * 1000 // 15 seconds

// @param user {object} - contains user information. eg: { id, name, email }
// returns {object} - access token and refresh token

_createJWTs(user) {
    try {

      let refreshTokenID = Math.floor(Math.random() * (1000000000000000 - 1 + 1)) + 1
      let refresh = { userID: user.id, tokenID: refreshTokenID }
      let accessToken = jsonwebtoken.sign(user, tokenSecret, { expiresIn: accessTokenExpiry })
      let refreshToken = jsonwebtoken.sign(refresh, tokenSecret)

      return { accessToken, refreshToken }
    } catch (err) {
      console.log(err)
    }
  }