riseup-squad21/services/autenticacaoApi.ts
2025-10-20 21:49:35 -03:00

80 lines
2.6 KiB
TypeScript

// Caminho: services/autenticacaoApi.ts
import Cookies from 'js-cookie';
const baseURL = 'https://yuanqfswhberkoevtmfr.supabase.co';
const apiKey = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6Inl1YW5xZnN3aGJlcmtvZXZ0bWZyIiwicm9sZSI6ImFub24iLCJpYXQiOjE3NTQ5NTQzNjksImV4cCI6MjA3MDUzMDM2OX0.g8Fm4XAvtX46zifBZnYVH4tVuQkqUH6Ia9CXQj4DztQ';
interface LoginResponse {
access_token: string;
refresh_token: string;
user: any;
// Adicione outros campos conforme necessário
}
export const autenticacaoApi = {
loginWithEmailAndPassword: async (email: string, password: string): Promise<LoginResponse> => {
const response = await fetch(`${baseURL}/auth/v1/token?grant_type=password`, {
method: 'POST',
headers: {
'apikey': apiKey,
'Content-Type': 'application/json',
},
body: JSON.stringify({ email, password }),
});
if (!response.ok) {
const errorData = await response.json();
throw new Error(errorData.error_description || 'Falha no login');
}
const data: LoginResponse = await response.json();
// Armazena o token nos cookies
Cookies.set('supabase-token', data.access_token, { expires: 1, path: '/' });
return data;
},
logout: async (): Promise<void> => {
const token = Cookies.get('supabase-token');
await fetch(`${baseURL}/auth/v1/logout`, {
method: 'POST',
headers: {
'apikey': apiKey,
'Authorization': `Bearer ${token}`,
},
});
// Remove o token dos cookies
Cookies.remove('supabase-token', { path: '/' });
},
sendMagicLink: async (email: string, redirectTo?: string): Promise<any> => {
const response = await fetch(`${baseURL}/auth/v1/otp`, {
method: 'POST',
headers: {
'apikey': apiKey,
'Content-Type': 'application/json',
},
body: JSON.stringify({ email, options: { emailRedirectTo: redirectTo } }),
});
return response.json();
},
renewToken: async (refreshToken: string): Promise<LoginResponse> => {
const response = await fetch(`${baseURL}/auth/v1/token?grant_type=refresh_token`, {
method: 'POST',
headers: {
'apikey': apiKey,
'Content-Type': 'application/json',
},
body: JSON.stringify({ refresh_token: refreshToken }),
});
if (!response.ok) {
const errorData = await response.json();
throw new Error(errorData.error_description || 'Falha ao renovar token');
}
const data: LoginResponse = await response.json();
Cookies.set('supabase-token', data.access_token, { expires: 1, path: '/' });
return data;
},
};