Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feat/auth provider proposal #116

Merged
merged 9 commits into from
Jan 17, 2025
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,7 @@
"@tanstack/react-query": "^5.52.1",
"app-icon-badge": "^0.0.15",
"axios": "^1.7.5",
"dayjs": "^1.11.13",
"expo": "~51.0.39",
"expo-constants": "~16.0.2",
"expo-dev-client": "~4.0.29",
Expand Down
3 changes: 3 additions & 0 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

14 changes: 7 additions & 7 deletions src/app/(app)/_layout.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
import { Link, Redirect, SplashScreen, Tabs } from 'expo-router';
import { useCallback, useEffect } from 'react';

import { useAuth, useIsFirstTime } from '@/core';
import { useAuth } from '@/components/providers/auth';
import { useIsFirstTime } from '@/core';
import { Pressable, Text } from '@/ui';
import {
Feed as FeedIcon,
Expand All @@ -10,24 +11,25 @@ import {
} from '@/ui/icons';

export default function TabLayout() {
const status = useAuth.use.status();
const { isAuthenticated, ready } = useAuth();
const [isFirstTime] = useIsFirstTime();
const hideSplash = useCallback(async () => {
await SplashScreen.hideAsync();
}, []);

useEffect(() => {
const TIMEOUT = 1000;
if (status !== 'idle') {
if (!ready) {
setTimeout(() => {
hideSplash();
}, TIMEOUT);
}
}, [hideSplash, status]);
}, [hideSplash, ready]);

if (isFirstTime) {
return <Redirect href="/onboarding" />;
}
if (status === 'signOut') {
if (!isAuthenticated && ready) {
return <Redirect href="/sign-in" />;
}
return (
Expand All @@ -45,7 +47,6 @@ export default function TabLayout() {
name="style"
options={{
title: 'Style',
headerShown: false,
tabBarIcon: ({ color }) => <StyleIcon color={color} />,
tabBarTestID: 'style-tab',
}}
Expand All @@ -54,7 +55,6 @@ export default function TabLayout() {
name="settings"
options={{
title: 'Settings',
headerShown: false,
tabBarIcon: ({ color }) => <SettingsIcon color={color} />,
tabBarTestID: 'settings-tab',
}}
Expand Down
7 changes: 4 additions & 3 deletions src/app/(app)/settings.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,16 +3,17 @@ import { Link } from 'expo-router';
import { useColorScheme } from 'nativewind';
import React from 'react';

import { useAuth } from '@/components/providers/auth';
import { Item } from '@/components/settings/item';
import { ItemsContainer } from '@/components/settings/items-container';
import { LanguageItem } from '@/components/settings/language-item';
import { ThemeItem } from '@/components/settings/theme-item';
import { translate, useAuth } from '@/core';
import { translate } from '@/core';
import { colors, FocusAwareStatusBar, ScrollView, Text, View } from '@/ui';
import { Website } from '@/ui/icons';

export default function Settings() {
const signOut = useAuth.use.signOut();
const { logout } = useAuth();
const { colorScheme } = useColorScheme();
const iconColor =
colorScheme === 'dark' ? colors.neutral[400] : colors.neutral[500];
Expand Down Expand Up @@ -67,7 +68,7 @@ export default function Settings() {

<View className="my-8">
<ItemsContainer>
<Item text="settings.logout" onPress={signOut} />
<Item text="settings.logout" onPress={logout} />
</ItemsContainer>
</View>
</View>
Expand Down
11 changes: 7 additions & 4 deletions src/app/_layout.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import { KeyboardProvider } from 'react-native-keyboard-controller';

import { APIProvider } from '@/api';
import interceptors from '@/api/common/interceptors';
import { AuthProvider } from '@/components/providers/auth';
import { hydrateAuth, loadSelectedTheme } from '@/core';
import { useThemeConfig } from '@/core/use-theme-config';

Expand Down Expand Up @@ -61,10 +62,12 @@ function Providers({ children }: { children: React.ReactNode }) {
<KeyboardProvider>
<ThemeProvider value={theme}>
<APIProvider>
<BottomSheetModalProvider>
{children}
<FlashMessage position="top" />
</BottomSheetModalProvider>
<AuthProvider>
<BottomSheetModalProvider>
{children}
<FlashMessage position="top" />
</BottomSheetModalProvider>
</AuthProvider>
</APIProvider>
</ThemeProvider>
</KeyboardProvider>
Expand Down
127 changes: 127 additions & 0 deletions src/components/providers/auth.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,127 @@
/* eslint-disable max-lines-per-function */
import { act, screen, waitFor } from '@testing-library/react-native';
import React from 'react';

import { render } from '@/core/test-utils';

import { AuthProvider, authStorage, HEADER_KEYS, useAuth } from './auth';

jest.mock('@/api', () => {
const originalModule = jest.requireActual('@/api'); // Import the original module
const mockStore: Record<string, string> = {};

return {
...originalModule, // Spread the original module to keep other exports
authStorage: {
getString: jest.fn((key: string) => mockStore[key] || null),
set: jest.fn((key: string, value: string) => {
mockStore[key] = value;
}),
delete: jest.fn((key: string) => {
delete mockStore[key];
}),
},
client: {
interceptors: {
request: { use: jest.fn(), eject: jest.fn() },
response: { use: jest.fn(), eject: jest.fn() },
},
},
};
});

const TestComponent: React.FC = () => {
const { token, isAuthenticated, loading, ready, logout } = useAuth();

return (
<div>
<p data-testid="token">{token}</p>
<p data-testid="isAuthenticated">{isAuthenticated ? 'true' : 'false'}</p>
<p data-testid="loading">{loading ? 'true' : 'false'}</p>
<p data-testid="ready">{ready ? 'true' : 'false'}</p>
<button data-testid="logout" onClick={logout}>
Logout
</button>
</div>
);
};

describe('AuthProvider', () => {
render(
<AuthProvider>
<TestComponent />
</AuthProvider>,
);

afterEach(() => {
jest.clearAllMocks();
});

it('should initialize with loading and ready states', async () => {
(authStorage.getString as jest.Mock).mockImplementation((key) => {
if (key === HEADER_KEYS.ACCESS_TOKEN) {
return 'mockToken';
}
if (key === HEADER_KEYS.EXPIRY) {
return '2100-01-01T00:00:00.000Z';
}
return null;
});

expect(screen.getByTestId('loading').textContent).toBe('true');
expect(screen.getByTestId('ready').textContent).toBe('false');

await waitFor(() =>
expect(screen.getByTestId('loading').textContent).toBe('false'),
);
expect(screen.getByTestId('ready').textContent).toBe('true');
expect(screen.getByTestId('isAuthenticated').textContent).toBe('true');
expect(screen.getByTestId('token').textContent).toBe('mockToken');
});

it('should handle expired token', async () => {
(authStorage.getString as jest.Mock).mockImplementation((key) => {
if (key === HEADER_KEYS.ACCESS_TOKEN) {
return 'expiredToken';
}
if (key === HEADER_KEYS.EXPIRY) {
return '2000-01-01T00:00:00.000Z';
}
return null;
});

await waitFor(() =>
expect(screen.getByTestId('loading').textContent).toBe('false'),
);
expect(screen.getByTestId('isAuthenticated').textContent).toBe('false');
expect(screen.getByTestId('token').textContent).toBe('');
});

it('should clear storage and state on logout', async () => {
(authStorage.getString as jest.Mock).mockImplementation((key) => {
if (key === HEADER_KEYS.ACCESS_TOKEN) {
return 'mockToken';
}
if (key === HEADER_KEYS.EXPIRY) {
return '2100-01-01T00:00:00.000Z';
}
return null;
});

await waitFor(() =>
expect(screen.getByTestId('loading').textContent).toBe('false'),
);

act(() => {
screen.getByTestId('logout').click();
});

expect(authStorage.delete).toHaveBeenCalledWith(HEADER_KEYS.ACCESS_TOKEN);
expect(authStorage.delete).toHaveBeenCalledWith(HEADER_KEYS.REFRESH_TOKEN);
expect(authStorage.delete).toHaveBeenCalledWith(HEADER_KEYS.USER_ID);
expect(authStorage.delete).toHaveBeenCalledWith(HEADER_KEYS.EXPIRY);

expect(screen.getByTestId('isAuthenticated').textContent).toBe('false');
expect(screen.getByTestId('token').textContent).toBe('');
});
});
Loading
Loading