Files
Craze-Data-check/src/lib/auth.ts
T

116 lines
3.4 KiB
TypeScript

const SUPABASE_URL = 'https://hwithddwaapyhnfwcesj.supabase.co';
const SUPABASE_ANON_KEY = 'sb_publishable_fGXkh0bSrAOqSk2jWKAzSg_NJD9YPCv';
const SESSION_KEY = 'craze_auth_session';
export interface AuthSession {
access_token: string;
refresh_token: string;
user: { id: string; email: string };
}
export async function signUp(email: string, password: string): Promise<void> {
const response = await fetch(`${SUPABASE_URL}/auth/v1/signup`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'apikey': SUPABASE_ANON_KEY,
},
body: JSON.stringify({ email, password }),
});
if (!response.ok) {
const err = await response.json().catch(() => ({}));
throw new Error(err.error_description || err.message || 'Registration failed.');
}
}
export async function signIn(email: string, password: string): Promise<AuthSession> {
const response = await fetch(`${SUPABASE_URL}/auth/v1/token?grant_type=password`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'apikey': SUPABASE_ANON_KEY,
},
body: JSON.stringify({ email, password }),
});
if (!response.ok) {
const err = await response.json().catch(() => ({}));
throw new Error(err.error_description || err.message || 'Invalid email or password.');
}
const data = await response.json();
// Validate status before signing in
try {
const statusRes = await fetch('/api/users-admin', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${data.access_token}`
},
body: JSON.stringify({ action: 'check-status' })
});
if (!statusRes.ok) {
const err = await statusRes.json().catch(() => ({}));
throw new Error(err.error || 'Failed to verify account validation status.');
}
const statusData = await statusRes.json();
if (!statusData.validated) {
throw new Error('Tu usuario aún no ha sido validado por un administrador.');
}
} catch (err: any) {
throw new Error(err.message || 'Error de validación del usuario.');
}
const session: AuthSession = {
access_token: data.access_token,
refresh_token: data.refresh_token,
user: { id: data.user.id, email: data.user.email },
};
localStorage.setItem(SESSION_KEY, JSON.stringify(session));
return session;
}
export async function refreshSession(refreshToken: string): Promise<AuthSession> {
const response = await fetch(`${SUPABASE_URL}/auth/v1/token?grant_type=refresh_token`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'apikey': SUPABASE_ANON_KEY,
},
body: JSON.stringify({ refresh_token: refreshToken }),
});
if (!response.ok) {
localStorage.removeItem(SESSION_KEY);
throw new Error('Session expired. Please sign in again.');
}
const data = await response.json();
const session: AuthSession = {
access_token: data.access_token,
refresh_token: data.refresh_token,
user: { id: data.user.id, email: data.user.email },
};
localStorage.setItem(SESSION_KEY, JSON.stringify(session));
return session;
}
export function signOut(): void {
localStorage.removeItem(SESSION_KEY);
}
export function getStoredSession(): AuthSession | null {
try {
const raw = localStorage.getItem(SESSION_KEY);
return raw ? (JSON.parse(raw) as AuthSession) : null;
} catch {
return null;
}
}