How to set user in nuxt auth after refresh?

480 Views Asked by At

Here is my auth config:

auth: {
    strategies: {
      local: {
        scheme: 'refresh',
        token: {
          property: 'jwtToken',
        },
        refreshToken: {
          property: 'refreshToken',
          data: 'refreshToken',
        },
        user: false,
        endpoints: {
          login: { url: '/api/account/authenticate', method: 'post' },
          logout: { url: '/api/account/logout', method: 'post' },
          refresh: { url: '/api/account/refresh-token', method: 'post' },
          user: false,
        },
      },
    },
  },

Here is my store actions for auth:

async login({ commit }, data) {
    try {
      const {
        data: { jwtToken, refreshToken },
      } = await this.$auth.loginWith('local', { data })
      await this.$auth.setUserToken(jwtToken, refreshToken)

      const decodedJwt = jwtDecode(jwtToken)
      this.$auth.setUser({ userId: decodedJwt.sub })

      await this.$router.push('/dashboard')
    } catch (e) {
      this.$n?.myError()
    }
  },
  async logout() {
    const refreshToken = localStorage.getItem('auth._refresh_token.local')
    await this.$auth.logout({ data: { refreshToken } })
  },

Of course after refresh the user property inside $auth is deleted. I would like to set it again on page refresh. How can I implement this without adding new apis for user? I've tried creating middlewares for this but they are working for all routes instead of specified ones. I just need I simple solution, like getting the jwt token from localStorage and the getting userId from it.

0

There are 0 best solutions below