87 lines
2.3 KiB
TypeScript
87 lines
2.3 KiB
TypeScript
import AsyncStorage from '@react-native-async-storage/async-storage';
|
|
import PocketBase, { type AuthRecord } from 'pocketbase';
|
|
|
|
const PB_AUTH_KEY = 'mdb_pb_auth';
|
|
|
|
function resolvePocketBaseUrl(): string {
|
|
const fromEnv = process.env.EXPO_PUBLIC_PB_URL?.replace(/\/$/, '').trim() ?? '';
|
|
if (fromEnv.startsWith('http://') || fromEnv.startsWith('https://')) {
|
|
return fromEnv;
|
|
}
|
|
const fallback = 'http://localhost:8090';
|
|
if (typeof __DEV__ !== 'undefined' && __DEV__) {
|
|
console.warn(
|
|
'[mdb] EXPO_PUBLIC_PB_URL absent ou invalide — utilisation de',
|
|
fallback,
|
|
'(placez EXPO_PUBLIC_PB_URL dans app/.env.local ou mdb/.env.local ; redémarrez Expo)',
|
|
);
|
|
}
|
|
return fallback;
|
|
}
|
|
|
|
const baseUrl = resolvePocketBaseUrl();
|
|
|
|
export const pb = new PocketBase(baseUrl);
|
|
|
|
pb.autoCancellation(false);
|
|
|
|
type StoredAuth = {
|
|
token: string;
|
|
record: AuthRecord;
|
|
};
|
|
|
|
let persistListenerRegistered = false;
|
|
|
|
function registerAuthPersistence(): void {
|
|
if (persistListenerRegistered) return;
|
|
persistListenerRegistered = true;
|
|
|
|
pb.authStore.onChange(() => {
|
|
void (async () => {
|
|
try {
|
|
if (!pb.authStore.isValid || !pb.authStore.token || !pb.authStore.record) {
|
|
await AsyncStorage.removeItem(PB_AUTH_KEY);
|
|
return;
|
|
}
|
|
const payload: StoredAuth = {
|
|
token: pb.authStore.token,
|
|
record: pb.authStore.record,
|
|
};
|
|
await AsyncStorage.setItem(PB_AUTH_KEY, JSON.stringify(payload));
|
|
} catch {
|
|
await AsyncStorage.removeItem(PB_AUTH_KEY);
|
|
}
|
|
})();
|
|
}, true);
|
|
}
|
|
|
|
export async function hydratePocketBaseAuth(): Promise<void> {
|
|
registerAuthPersistence();
|
|
const raw = await AsyncStorage.getItem(PB_AUTH_KEY);
|
|
if (!raw) return;
|
|
try {
|
|
const { token, record } = JSON.parse(raw) as StoredAuth;
|
|
if (!token || !record) {
|
|
await AsyncStorage.removeItem(PB_AUTH_KEY);
|
|
return;
|
|
}
|
|
pb.authStore.save(token, record);
|
|
try {
|
|
await pb.collection('users').authRefresh();
|
|
} catch {
|
|
pb.authStore.clear();
|
|
await AsyncStorage.removeItem(PB_AUTH_KEY);
|
|
}
|
|
} catch {
|
|
await AsyncStorage.removeItem(PB_AUTH_KEY);
|
|
}
|
|
}
|
|
|
|
export function getCurrentUserId(): string | undefined {
|
|
return pb.authStore.record?.id;
|
|
}
|
|
|
|
export function isAuthenticated(): boolean {
|
|
return pb.authStore.isValid;
|
|
}
|