All files / src/stores auth.ts

82.6% Statements 57/69
75% Branches 15/20
75% Functions 9/12
82.35% Lines 56/68

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187                                24x 626x 626x 626x     4x 4x   3x 1x 1x 1x   2x 2x   2x 2x         3x 3x                   2x   1x 1x         2x 2x   1x 1x         2x 2x   1x 1x         3x 3x 2x 2x   1x 1x                                             626x             9x 9x 8x 8x   8x 8x                   8x 9x               9x       1x 1x   1x 1x         54x 54x             53x 2x 2x 1x       53x   1x       626x                              
import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import {
  signIn,
  signOut,
  signUp,
  confirmSignUp,
  resendSignUpCode,
  getCurrentUser,
  fetchAuthSession,
  fetchUserAttributes,
  signInWithRedirect
} from 'aws-amplify/auth'
import { Hub } from 'aws-amplify/utils'
import api from '@/services/api'
 
export const useAuthStore = defineStore('auth', () => {
  const user = ref<any>(null)
  const isAuthenticated = computed(() => !!user.value)
  const currentFlow = ref<string | null>(null)
 
  async function login(email: string, password: string) {
    try {
      const result = await signIn({ username: email, password })
      // Amplify v6 may return CONFIRM_SIGN_UP instead of throwing UserNotConfirmedException
      if (!result.isSignedIn && result.nextStep?.signInStep === 'CONFIRM_SIGN_UP') {
        const err = new Error('User is not confirmed.') as any
        err.name = 'UserNotConfirmedException'
        throw err
      }
      await loadUser()
      return result
    } catch (error) {
      console.error('Login error:', error)
      throw error
    }
  }
 
  async function register(email: string, password: string, name: string) {
    try {
      const result = await signUp({
        username: email,
        password,
        options: {
          userAttributes: {
            email,
            name
          }
        }
      })
      return result
    } catch (error) {
      console.error('Signup error:', error)
      throw error
    }
  }
 
  async function confirm(email: string, code: string) {
    try {
      await confirmSignUp({ username: email, confirmationCode: code })
    } catch (error) {
      console.error('Confirmation error:', error)
      throw error
    }
  }
 
  async function resendConfirmation(email: string) {
    try {
      await resendSignUpCode({ username: email })
    } catch (error) {
      console.error('Resend confirmation error:', error)
      throw error
    }
  }
 
  async function logout() {
    try {
      await signOut()
      user.value = null
      currentFlow.value = null
    } catch (error) {
      console.error('Logout error:', error)
      throw error
    }
  }
 
  async function deleteAccount() {
    await api.delete('/v1/users/me')
    await signOut()
    user.value = null
    currentFlow.value = null
  }
 
  async function signInWithGoogle() {
    try {
      await signInWithRedirect({ provider: 'Google' })
    } catch (error) {
      console.error('Google sign-in error:', error)
      throw error
    }
  }
 
  // Handle OAuth redirect callback: Amplify fires 'signInWithRedirect' after
  // exchanging the authorization code for tokens. We reload the user so the
  // app reacts immediately without a full page refresh.
  Hub.listen('auth', ({ payload }) => {
    if (payload.event === 'signInWithRedirect') {
      loadUser()
    }
  })
 
  async function loadUser(forceRefresh = false) {
    try {
      const currentUser = await getCurrentUser()
      const session = await fetchAuthSession({ forceRefresh })
      let cognitoAttributes: Record<string, string | undefined> = {}
 
      try {
        cognitoAttributes = await fetchUserAttributes()
      } catch (attributesError: any) {
        // Social login can temporarily fail here if the cached OAuth token was issued
        // before the required scope was added. We still keep the user signed in based
        // on ID token claims and recover attributes on the next refresh/login.
        if (attributesError?.name !== 'NotAuthorizedException') {
          throw attributesError
        }
      }
 
      const idPayload = session.tokens?.idToken?.payload
      user.value = {
        ...currentUser,
        // Merge idToken payload (has custom:flowId) with real Cognito attributes (has name, email, etc.)
        attributes: {
          ...idPayload,
          ...cognitoAttributes
        }
      }
      currentFlow.value = (idPayload?.['custom:flowId'] as string) || null
    } catch (err) {
      // "UserUnAuthenticatedException" is the normal state for unauthenticated visitors —
      // not an error worth logging. Only log unexpected failures.
      Eif ((err as any)?.name !== 'UserUnAuthenticatedException') {
        console.error('[auth] loadUser failed:', err)
      }
      user.value = null
      currentFlow.value = null
    }
  }
 
  async function getAccessToken(forceRefresh = false): Promise<string | null> {
    try {
      const session = await fetchAuthSession({ forceRefresh })
      // Sync currentFlow when force-refreshing — but only when the JWT actually
      // carries a custom:flowId. Never nullify a known-good in-memory value just
      // because Cognito attribute propagation is still in progress (e.g. right
      // after flow creation, the freshly-signed token may not yet contain the
      // updated claim). This prevents the 401-retry interceptor from destroying
      // currentFlow and making the submit button guard silently bail out.
      if (forceRefresh) {
        const jwtFlowId = session.tokens?.idToken?.payload?.['custom:flowId'] as string | undefined
        if (jwtFlowId) {
          currentFlow.value = jwtFlowId
        }
      }
      // Use ID token for Cognito User Pool authorizer
      return session.tokens?.idToken?.toString() || null
    } catch {
      return null
    }
  }
 
  return {
    user,
    isAuthenticated,
    currentFlow,
    login,
    register,
    confirm,
    resendConfirmation,
    logout,
    deleteAccount,
    signInWithGoogle,
    loadUser,
    getAccessToken
  }
})