267 lines
9.7 KiB
TypeScript
267 lines
9.7 KiB
TypeScript
/**
|
|
* AuthContext (src/contexts/AuthContext.tsx) — the paths that only run against
|
|
* the REAL provider: session restore from storage, getSelfData handling, the
|
|
* real login()/register() mutations, and the post-login redirect.
|
|
*
|
|
* tests/setup.ts stubs this module globally, so it is unmocked here. Known bugs
|
|
* are pinned — see tests/KNOWN-GAPS.md.
|
|
*/
|
|
|
|
jest.mock('expo-router', () => require('../mocks/router').expoRouterMock())
|
|
jest.unmock('@/src/contexts/AuthContext')
|
|
|
|
import React from 'react'
|
|
import { Text, TouchableOpacity } from 'react-native'
|
|
import { fireEvent, screen, waitFor } from '@testing-library/react-native'
|
|
import { StorageService } from 'common-ui/src/services/StorageService'
|
|
import { StorageServiceCasual } from 'common-ui/src/services/StorageServiceCasual'
|
|
|
|
import { AuthProvider, useAuth, useUserDetails } from '@/src/contexts/AuthContext'
|
|
import { getAuthToken, getUserId } from '@/hooks/useJWT'
|
|
import constants from '@/src/constants'
|
|
import { resetStorage, setupApiMocks } from '../mocks/api'
|
|
import { routerMock } from '../mocks/router'
|
|
import { renderWithProviders } from '../helpers/render'
|
|
|
|
const USER = {
|
|
id: 5,
|
|
name: 'Test User',
|
|
email: 'test@example.com',
|
|
mobile: '9876543210',
|
|
profileImage: '',
|
|
createdAt: '',
|
|
}
|
|
|
|
/**
|
|
* getCurrentUserId decodes the JWT payload, so a restore test needs a token
|
|
* jwtDecode accepts. Only the payload is inspected — the signature is a stub.
|
|
*/
|
|
const jwtFor = (payload: Record<string, unknown>) => {
|
|
const enc = (obj: unknown) =>
|
|
Buffer.from(JSON.stringify(obj)).toString('base64url')
|
|
return `${enc({ alg: 'HS256', typ: 'JWT' })}.${enc(payload)}.sig`
|
|
}
|
|
|
|
const USER_JWT = jwtFor({ id: USER.id })
|
|
|
|
const Probe = () => {
|
|
const auth = useAuth()
|
|
const details = useUserDetails()
|
|
const [loginError, setLoginError] = React.useState('')
|
|
return (
|
|
<>
|
|
<Text testID="state">
|
|
{`${auth.isAuthenticated}|${auth.isLoading}|${auth.user?.id ?? 'none'}`}
|
|
</Text>
|
|
<Text testID="details">{details ? 'yes' : 'no'}</Text>
|
|
<Text testID="login-error">{loginError}</Text>
|
|
<TouchableOpacity
|
|
testID="do-login"
|
|
onPress={() =>
|
|
auth
|
|
.login({ mobile: '9876543210', password: 'pw' } as never)
|
|
.catch(() => setLoginError('failed'))
|
|
}
|
|
>
|
|
<Text>login</Text>
|
|
</TouchableOpacity>
|
|
<TouchableOpacity
|
|
testID="do-register"
|
|
onPress={() =>
|
|
auth.register({ name: 'T', email: 't@e.com', mobile: '9876543210', password: 'pw' } as never)
|
|
}
|
|
>
|
|
<Text>register</Text>
|
|
</TouchableOpacity>
|
|
<TouchableOpacity testID="do-login-token" onPress={() => auth.loginWithToken('tok', USER as never)}>
|
|
<Text>token</Text>
|
|
</TouchableOpacity>
|
|
</>
|
|
)
|
|
}
|
|
|
|
const SELF_DATA = { data: { user: USER } }
|
|
|
|
const renderAuth = (procedures: Record<string, unknown> = {}) =>
|
|
renderWithProviders(
|
|
<AuthProvider>
|
|
<Probe />
|
|
</AuthProvider>,
|
|
{ centralStores: false }
|
|
)
|
|
|
|
/** A getSelfData mock that rejects, to drive the invalid-token path. */
|
|
const failingSelfData = () => {
|
|
throw new Error('UNAUTHORIZED')
|
|
}
|
|
|
|
describe('Auth lifecycle (real provider)', () => {
|
|
beforeEach(async () => {
|
|
await resetStorage()
|
|
await StorageService.clearAll(['authToken', 'userId'])
|
|
await StorageServiceCasual.clearAll([constants.AUTH_REDIRECT_KEY])
|
|
routerMock.back.mockClear()
|
|
routerMock.replace.mockClear()
|
|
})
|
|
|
|
it('restores the session from a stored token and populates userDetails', async () => {
|
|
await StorageService.setItem('authToken', USER_JWT)
|
|
await StorageService.setItem('userId', String(USER.id))
|
|
|
|
setupApiMocks({
|
|
procedures: { 'user.user.getSelfData': SELF_DATA },
|
|
})
|
|
renderAuth()
|
|
|
|
// Restored from storage before the query settles: authenticated, still loading.
|
|
await waitFor(() => expect(screen.getByTestId('state')).toHaveTextContent('true|true|5'))
|
|
|
|
// getSelfData then fills the profile in and drops the loading flag.
|
|
await waitFor(() => expect(screen.getByTestId('state')).toHaveTextContent('true|false|5'))
|
|
expect(screen.getByTestId('details')).toHaveTextContent('yes')
|
|
})
|
|
|
|
it('settles to signed-out when the stored token carries no user id', async () => {
|
|
// getCurrentUserId derives the id from the JWT payload, not the userId key.
|
|
await StorageService.setItem('authToken', jwtFor({ role: 'guest' }))
|
|
await StorageService.setItem('userId', '5')
|
|
|
|
setupApiMocks({ procedures: { 'user.user.getSelfData': SELF_DATA } })
|
|
renderAuth()
|
|
|
|
await waitFor(() => expect(screen.getByTestId('state')).toHaveTextContent('false|false|none'))
|
|
expect(screen.getByTestId('details')).toHaveTextContent('no')
|
|
})
|
|
|
|
it('settles to signed-out when the stored token cannot be decoded', async () => {
|
|
await StorageService.setItem('authToken', 'not-a-jwt')
|
|
await StorageService.setItem('userId', '5')
|
|
|
|
setupApiMocks({ procedures: { 'user.user.getSelfData': SELF_DATA } })
|
|
renderAuth()
|
|
|
|
await waitFor(() => expect(screen.getByTestId('state')).toHaveTextContent('false|false|none'))
|
|
})
|
|
|
|
/**
|
|
* KNOWN GAP: AuthContext clears the in-memory session on a getSelfData error
|
|
* but `deleteAuthToken()` is commented out, so the dead token is restored on
|
|
* the next cold start. This pins that behaviour — it should fail once the
|
|
* token is actually deleted.
|
|
*/
|
|
it('clears the session when getSelfData fails but leaves the stale token in storage', async () => {
|
|
await StorageService.setItem('authToken', USER_JWT)
|
|
await StorageService.setItem('userId', String(USER.id))
|
|
|
|
setupApiMocks({
|
|
procedures: { 'user.user.getSelfData': failingSelfData },
|
|
})
|
|
renderAuth()
|
|
|
|
await waitFor(() => expect(screen.getByTestId('state')).toHaveTextContent('false|false|none'))
|
|
// The bug: the token survives and would re-authenticate on next launch.
|
|
expect(await getAuthToken()).toBe(USER_JWT)
|
|
expect(await getUserId()).toBe(String(USER.id))
|
|
})
|
|
|
|
it('login() persists the token and user id and authenticates', async () => {
|
|
setupApiMocks({
|
|
procedures: {
|
|
'user.user.getSelfData': SELF_DATA,
|
|
'user.auth.login': { data: { token: 'tok-login', user: USER } },
|
|
},
|
|
})
|
|
renderAuth()
|
|
await waitFor(() => expect(screen.getByTestId('state')).toHaveTextContent('false|false|none'))
|
|
|
|
fireEvent.press(screen.getByTestId('do-login'))
|
|
|
|
await waitFor(() => expect(screen.getByTestId('state')).toHaveTextContent('true|false|5'))
|
|
expect(await getAuthToken()).toBe('tok-login')
|
|
expect(await getUserId()).toBe(String(USER.id))
|
|
expect(screen.getByTestId('details')).toHaveTextContent('yes')
|
|
})
|
|
|
|
it('login() surfaces the failure and stays signed-out', async () => {
|
|
setupApiMocks({
|
|
procedures: {
|
|
'user.auth.login': () => {
|
|
throw new Error('bad credentials')
|
|
},
|
|
},
|
|
})
|
|
renderAuth()
|
|
await waitFor(() => expect(screen.getByTestId('state')).toHaveTextContent('false|false|none'))
|
|
|
|
fireEvent.press(screen.getByTestId('do-login'))
|
|
|
|
await waitFor(() => expect(screen.getByTestId('login-error')).toHaveTextContent('failed'))
|
|
expect(screen.getByTestId('state')).toHaveTextContent('false|false|none')
|
|
expect(await getAuthToken()).toBeNull()
|
|
})
|
|
|
|
it('register() persists the token and user id and authenticates', async () => {
|
|
setupApiMocks({
|
|
procedures: {
|
|
'user.user.getSelfData': SELF_DATA,
|
|
'user.auth.register': { data: { token: 'tok-reg', user: USER } },
|
|
},
|
|
})
|
|
renderAuth()
|
|
await waitFor(() => expect(screen.getByTestId('state')).toHaveTextContent('false|false|none'))
|
|
|
|
fireEvent.press(screen.getByTestId('do-register'))
|
|
|
|
await waitFor(() => expect(screen.getByTestId('state')).toHaveTextContent('true|false|5'))
|
|
expect(await getAuthToken()).toBe('tok-reg')
|
|
expect(await getUserId()).toBe(String(USER.id))
|
|
})
|
|
|
|
it('consumes the stored post-login redirect and calls router.back()', async () => {
|
|
const redirectState = {
|
|
targetUrl: '/(drawer)/(tabs)/home/checkout',
|
|
queryParams: { slots: '1:1' },
|
|
timestamp: Date.now(),
|
|
}
|
|
await StorageServiceCasual.setItem(constants.AUTH_REDIRECT_KEY, JSON.stringify(redirectState))
|
|
|
|
setupApiMocks({ procedures: { 'user.user.getSelfData': SELF_DATA } })
|
|
renderAuth()
|
|
await waitFor(() => expect(screen.getByTestId('state')).toHaveTextContent('false|false|none'))
|
|
|
|
fireEvent.press(screen.getByTestId('do-login-token'))
|
|
|
|
await waitFor(() => expect(routerMock.back).toHaveBeenCalled())
|
|
// The redirect state is single-use.
|
|
expect(await StorageServiceCasual.getItem(constants.AUTH_REDIRECT_KEY)).toBeNull()
|
|
})
|
|
|
|
it('falls back to router.back() when the redirect state has expired', async () => {
|
|
const stale = {
|
|
targetUrl: '/somewhere',
|
|
queryParams: {},
|
|
timestamp: Date.now() - 25 * 60 * 60 * 1000,
|
|
}
|
|
await StorageServiceCasual.setItem(constants.AUTH_REDIRECT_KEY, JSON.stringify(stale))
|
|
|
|
setupApiMocks({ procedures: { 'user.user.getSelfData': SELF_DATA } })
|
|
renderAuth()
|
|
await waitFor(() => expect(screen.getByTestId('state')).toHaveTextContent('false|false|none'))
|
|
|
|
fireEvent.press(screen.getByTestId('do-login-token'))
|
|
|
|
await waitFor(() => expect(routerMock.back).toHaveBeenCalled())
|
|
expect(routerMock.replace).not.toHaveBeenCalled()
|
|
expect(await StorageServiceCasual.getItem(constants.AUTH_REDIRECT_KEY)).toBeNull()
|
|
})
|
|
|
|
it('calls router.back() when there is no stored redirect state', async () => {
|
|
setupApiMocks({ procedures: { 'user.user.getSelfData': SELF_DATA } })
|
|
renderAuth()
|
|
await waitFor(() => expect(screen.getByTestId('state')).toHaveTextContent('false|false|none'))
|
|
|
|
fireEvent.press(screen.getByTestId('do-login-token'))
|
|
|
|
await waitFor(() => expect(routerMock.back).toHaveBeenCalled())
|
|
})
|
|
})
|