Files
sistema_base/apps/web/feactures/auth/actions/login-action.ts

59 lines
1.5 KiB
TypeScript

'use server';
import { safeFetchApi } from '@/lib';
import { cookies } from 'next/headers';
import { loginResponseSchema, UserFormValue } from '../schemas/login';
type LoginActionSuccess = {
message: string;
user: {
email: string;
username: string;
id: number;
rol: Array<{ id: number; rol: string }>;
fullname: string;
};
tokens: {
access_token: string;
access_expire_in: number;
refresh_token: string;
refresh_expire_in: number;
};
};
type LoginActionError = {
type: 'API_ERROR' | 'VALIDATION_ERROR' | 'UNKNOWN_ERROR'; // **Asegúrate de que el tipo de `type` sea este aquí**
message: string;
details?: any;
};
// Si SignInAction también puede devolver null, asegúralo en su tipo de retorno
type LoginActionResult = LoginActionSuccess | LoginActionError | null;
export const SignInAction = async (payload: UserFormValue) => {
const [error, data] = await safeFetchApi(
loginResponseSchema,
'/auth/sign-in',
'POST',
payload,
);
if (error) {
return error;
} else {
// 2. GUARDAR REFRESH TOKEN EN COOKIE (La clave del cambio)
(await cookies()).set(
'refresh_token',
String(data?.tokens?.refresh_token),
{
httpOnly: true, // JavaScript no puede leerla
secure: process.env.NODE_ENV === 'production',
sameSite: 'lax',
path: '/',
maxAge: 7 * 24 * 60 * 60, // Ej: 7 días (debe coincidir con tu backend)
},
);
return data;
}
};