anilistAuthService.ts
1 import AsyncStorage from '@react-native-async-storage/async-storage'; 2 3 interface AniListAuthData { 4 accessToken: string; 5 expiresAt: number; 6 lastUpdated: number; 7 } 8 9 const AUTH_KEY = 'anilist_auth'; 10 11 const debug = (message: string, data?: any) => { 12 console.log(`[AniList Auth] ${message}`, data || ''); 13 }; 14 15 export async function saveAuthData( 16 authData: Omit<AniListAuthData, 'lastUpdated'> 17 ): Promise<void> { 18 try { 19 debug('Saving auth data'); 20 const data: AniListAuthData = { 21 ...authData, 22 lastUpdated: Date.now(), 23 }; 24 await AsyncStorage.setItem(AUTH_KEY, JSON.stringify(data)); 25 debug('Auth data saved successfully'); 26 } catch (error) { 27 debug('Error saving auth data:', error); 28 throw error; 29 } 30 } 31 32 export async function getAuthData(): Promise<AniListAuthData | null> { 33 try { 34 debug('Getting auth data from storage'); 35 const authDataString = await AsyncStorage.getItem(AUTH_KEY); 36 37 if (authDataString) { 38 const authData: AniListAuthData = JSON.parse(authDataString); 39 debug('Auth data found, checking expiration'); 40 41 if (Date.now() < authData.expiresAt) { 42 debug('Auth data valid'); 43 return authData; 44 } 45 46 debug('Auth data expired'); 47 await clearAuthData(); 48 } else { 49 debug('No auth data found'); 50 } 51 52 return null; 53 } catch (error) { 54 debug('Error getting auth data:', error); 55 return null; 56 } 57 } 58 59 export async function clearAuthData(): Promise<void> { 60 try { 61 debug('Clearing auth data'); 62 await AsyncStorage.removeItem(AUTH_KEY); 63 debug('Auth data cleared successfully'); 64 } catch (error) { 65 debug('Error clearing auth data:', error); 66 throw error; 67 } 68 } 69 70 export async function isAuthenticated(): Promise<boolean> { 71 try { 72 const authData = await getAuthData(); 73 return !!authData && Date.now() < authData.expiresAt; 74 } catch (error) { 75 debug('Error checking authentication status:', error); 76 return false; 77 } 78 }