All files / src/stores auth.ts

82.92% Statements 68/82
82.14% Branches 23/28
80% Functions 12/15
82.5% Lines 66/80

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 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244                                110x 1906x 1906x         1906x     1906x 1906x         1906x 92x       4x 4x   3x 1x 1x 1x   2x 2x   2x 2x                                 5x 5x                       4x   1x 1x               3x 3x     2x 1x       1x         2x 2x   1x 1x         3x 3x         1x 1x         17x 17x 3x 3x 3x   14x 14x                                                         1906x             8x 8x 7x 7x   7x 7x                   7x 8x                     8x 8x 6x   6x         1x 1x   1x 1x 1x         149x 149x   148x   1x       1906x                                      
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)
  // The tab's active flow: the flow of its URL (/flows/:slug/...), set by the
  // router (see router/flowRoutes.ts) and sent with every API request
  // (X-Flow-Id, services/api.ts). Never stored on the user, so each tab or
  // device works in its own flow.
  const currentFlow = ref<string | null>(null)
  // Backend-only attributes not carried by the Cognito JWT (e.g. isPlatformAdmin).
  // Populated by loadUser() via GET /v1/users/me.
  const profile = ref<{ isPlatformAdmin?: boolean; nickname?: string | null } | null>(null)
  const isPlatformAdmin = computed(() => profile.value?.isPlatformAdmin ?? false)
  // Amplify's getCurrentUser() has no `.sub` — the Cognito sub only comes through
  // on the ID token payload, merged into `user.attributes` by loadUser(). Some
  // user objects still carry `.sub` or `.userId` directly (e.g. right after
  // sign-up), so fall back through all three shapes.
  const userId = computed(
    (): string => user.value?.attributes?.sub || user.value?.sub || user.value?.userId || ''
  )
 
  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
    }
  }
 
  /**
   * `clientMetadata` reaches the Cognito Custom Message trigger, which writes
   * the verification email: the UI language, and the flow when the sign-up
   * started from its join page (UC-SPACE-008.1). `validationData` reaches the
   * Pre Sign-up trigger only: the Turnstile token (UC-AUTH-009.1).
   */
  async function register(
    email: string,
    password: string,
    name: string,
    clientMetadata?: Record<string, string>,
    validationData?: Record<string, string>
  ) {
    try {
      const result = await signUp({
        username: email,
        password,
        options: {
          userAttributes: {
            email,
            name
          },
          ...(clientMetadata && { clientMetadata }),
          ...(validationData && { validationData })
        }
      })
      return result
    } catch (error) {
      console.error('Signup error:', error)
      throw error
    }
  }
 
  // Nickname reservation lives entirely in DynamoDB (see set-nickname Lambda) —
  // Cognito never stores it. Called once the user has a valid session right after
  // sign-up, so it needs an authenticated request rather than a Cognito attribute.
  async function claimNickname(nickname: string) {
    try {
      const response = await api.put('/v1/users/me/nickname', { nickname })
      // login() loaded the profile before the claim, so it still holds a null
      // nickname — sync it or MissingNicknameModal asks for one again.
      if (profile.value) {
        profile.value = { ...profile.value, nickname: response.data.nickname }
      }
    } catch (error) {
      // Non-fatal: the user can still set a nickname later from the Profile page.
      console.error('Failed to claim nickname after sign-up:', 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, clientMetadata?: Record<string, string>) {
    try {
      await resendSignUpCode({
        username: email,
        ...(clientMetadata && { options: { clientMetadata } })
      })
    } catch (error) {
      console.error('Resend confirmation error:', error)
      throw error
    }
  }
 
  async function logout() {
    try {
      await signOut()
      user.value = null
      currentFlow.value = null
      profile.value = null
    } catch (error) {
      console.error('Logout error:', error)
      throw error
    }
  }
 
  async function deleteAccount() {
    await api.delete('/v1/users/me')
    try {
      await signOut()
    } catch {
      // signOut may fail if the Cognito user was already removed by the backend;
      // local tokens are still cleared by Amplify even when the request fails.
    }
    user.value = null
    currentFlow.value = null
    profile.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 with real Cognito attributes (has name, email, etc.)
        attributes: {
          ...idPayload,
          ...cognitoAttributes
        }
      }
 
      // Non-fatal: if this fails, isPlatformAdmin simply stays false — the user
      // still gets a normal (non-admin) session rather than being logged out.
      try {
        const response = await api.get('/v1/users/me')
        profile.value = response.data
      } catch (profileError) {
        console.error('[auth] Failed to load user profile:', profileError)
      }
    } 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
      profile.value = null
    }
  }
 
  async function getAccessToken(forceRefresh = false): Promise<string | null> {
    try {
      const session = await fetchAuthSession({ forceRefresh })
      // Use ID token for Cognito User Pool authorizer
      return session.tokens?.idToken?.toString() || null
    } catch {
      return null
    }
  }
 
  return {
    user,
    isAuthenticated,
    currentFlow,
    userId,
    profile,
    isPlatformAdmin,
    login,
    register,
    claimNickname,
    confirm,
    resendConfirmation,
    logout,
    deleteAccount,
    signInWithGoogle,
    loadUser,
    getAccessToken
  }
})