Login

This server middleware will hanlde if we are current logging in or if we need to refresh the current session (token).

Situation 1: Currently tryin to login

Then we want to make the API request to get all the tokens so we can get the user profile information for example of get some data where we need an Bearer token etc.

Situation 2: Already logged in once, and comes back a while later (> 1 hour)

When this happens we want to refresh the session and keep the user logged in.

authentication.server.ts
// folder: /plugins/1.authentication.server.ts

import { CODE_LENGTH } from '~/constants'

export default defineNuxtPlugin(async () => {
  const route = useRoute()

  // When we are in the OAuth flow, the middelware will handle authentication
  // In short, the middelware will get the tokens and saves them in a cookie
  // So we can do authenticated API requests later on to get some data.
  if (route.query.code && route.query.code?.length > CODE_LENGTH) {
    return
  }
  const { getUser, user, cookie, refreshToken } = useAuth()

  // // We are logged out or never started a session
  if (!cookie.value) {
    return
  }

  try {
    // We have loggedin once
    // See if the session is still valid
    await getUser()
  } catch (e) {
    // User call failed, token is probably expired
    // Try and get a new one and login again
    try {
      if (!user.value && cookie.value?.access_token.length > 0) {
        await refreshToken()
        await getUser()
      }
    } catch (e) {
      // Don't crash
    }
  }
})