feat(web): add login and register pages with auth store
- API client with token refresh interceptor - Auth API functions (login, register, logout, getMe) - Auth store with Zustand persistence - Auth layout with centered card design - Login page with form validation - Register page with company and user data - Environment example file Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
This commit is contained in:
1
apps/web/.env.example
Normal file
1
apps/web/.env.example
Normal file
@@ -0,0 +1 @@
|
||||
NEXT_PUBLIC_API_URL=http://localhost:4000/api
|
||||
11
apps/web/app/(auth)/layout.tsx
Normal file
11
apps/web/app/(auth)/layout.tsx
Normal file
@@ -0,0 +1,11 @@
|
||||
export default function AuthLayout({
|
||||
children,
|
||||
}: {
|
||||
children: React.ReactNode;
|
||||
}) {
|
||||
return (
|
||||
<div className="min-h-screen flex items-center justify-center bg-gradient-to-b from-background to-muted p-4">
|
||||
<div className="w-full max-w-md">{children}</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
90
apps/web/app/(auth)/login/page.tsx
Normal file
90
apps/web/app/(auth)/login/page.tsx
Normal file
@@ -0,0 +1,90 @@
|
||||
'use client';
|
||||
|
||||
import { useState } from 'react';
|
||||
import { useRouter } from 'next/navigation';
|
||||
import Link from 'next/link';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { Label } from '@/components/ui/label';
|
||||
import { Card, CardContent, CardDescription, CardFooter, CardHeader, CardTitle } from '@/components/ui/card';
|
||||
import { login } from '@/lib/api/auth';
|
||||
import { useAuthStore } from '@/stores/auth-store';
|
||||
|
||||
export default function LoginPage() {
|
||||
const router = useRouter();
|
||||
const { setUser, setTokens } = useAuthStore();
|
||||
const [isLoading, setIsLoading] = useState(false);
|
||||
const [error, setError] = useState('');
|
||||
|
||||
async function handleSubmit(e: React.FormEvent<HTMLFormElement>) {
|
||||
e.preventDefault();
|
||||
setIsLoading(true);
|
||||
setError('');
|
||||
|
||||
const formData = new FormData(e.currentTarget);
|
||||
const email = formData.get('email') as string;
|
||||
const password = formData.get('password') as string;
|
||||
|
||||
try {
|
||||
const response = await login({ email, password });
|
||||
setTokens(response.accessToken, response.refreshToken);
|
||||
setUser(response.user);
|
||||
router.push('/dashboard');
|
||||
} catch (err: any) {
|
||||
setError(err.response?.data?.message || 'Error al iniciar sesión');
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<Card>
|
||||
<CardHeader className="text-center">
|
||||
<CardTitle className="text-2xl">Iniciar Sesión</CardTitle>
|
||||
<CardDescription>
|
||||
Ingresa tus credenciales para acceder a tu cuenta
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<form onSubmit={handleSubmit}>
|
||||
<CardContent className="space-y-4">
|
||||
{error && (
|
||||
<div className="p-3 text-sm text-destructive bg-destructive/10 rounded-md">
|
||||
{error}
|
||||
</div>
|
||||
)}
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="email">Email</Label>
|
||||
<Input
|
||||
id="email"
|
||||
name="email"
|
||||
type="email"
|
||||
placeholder="tu@email.com"
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="password">Contraseña</Label>
|
||||
<Input
|
||||
id="password"
|
||||
name="password"
|
||||
type="password"
|
||||
placeholder="••••••••"
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
</CardContent>
|
||||
<CardFooter className="flex flex-col gap-4">
|
||||
<Button type="submit" className="w-full" disabled={isLoading}>
|
||||
{isLoading ? 'Iniciando sesión...' : 'Iniciar Sesión'}
|
||||
</Button>
|
||||
<p className="text-sm text-muted-foreground text-center">
|
||||
¿No tienes cuenta?{' '}
|
||||
<Link href="/register" className="text-primary hover:underline">
|
||||
Regístrate
|
||||
</Link>
|
||||
</p>
|
||||
</CardFooter>
|
||||
</form>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
119
apps/web/app/(auth)/register/page.tsx
Normal file
119
apps/web/app/(auth)/register/page.tsx
Normal file
@@ -0,0 +1,119 @@
|
||||
'use client';
|
||||
|
||||
import { useState } from 'react';
|
||||
import { useRouter } from 'next/navigation';
|
||||
import Link from 'next/link';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { Label } from '@/components/ui/label';
|
||||
import { Card, CardContent, CardDescription, CardFooter, CardHeader, CardTitle } from '@/components/ui/card';
|
||||
import { register } from '@/lib/api/auth';
|
||||
import { useAuthStore } from '@/stores/auth-store';
|
||||
|
||||
export default function RegisterPage() {
|
||||
const router = useRouter();
|
||||
const { setUser, setTokens } = useAuthStore();
|
||||
const [isLoading, setIsLoading] = useState(false);
|
||||
const [error, setError] = useState('');
|
||||
|
||||
async function handleSubmit(e: React.FormEvent<HTMLFormElement>) {
|
||||
e.preventDefault();
|
||||
setIsLoading(true);
|
||||
setError('');
|
||||
|
||||
const formData = new FormData(e.currentTarget);
|
||||
|
||||
try {
|
||||
const response = await register({
|
||||
empresa: {
|
||||
nombre: formData.get('empresaNombre') as string,
|
||||
rfc: formData.get('empresaRfc') as string,
|
||||
},
|
||||
usuario: {
|
||||
nombre: formData.get('nombre') as string,
|
||||
email: formData.get('email') as string,
|
||||
password: formData.get('password') as string,
|
||||
},
|
||||
});
|
||||
setTokens(response.accessToken, response.refreshToken);
|
||||
setUser(response.user);
|
||||
router.push('/dashboard');
|
||||
} catch (err: any) {
|
||||
setError(err.response?.data?.message || 'Error al registrarse');
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<Card>
|
||||
<CardHeader className="text-center">
|
||||
<CardTitle className="text-2xl">Crear Cuenta</CardTitle>
|
||||
<CardDescription>
|
||||
Registra tu empresa y comienza tu prueba gratuita
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<form onSubmit={handleSubmit}>
|
||||
<CardContent className="space-y-4">
|
||||
{error && (
|
||||
<div className="p-3 text-sm text-destructive bg-destructive/10 rounded-md">
|
||||
{error}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="space-y-2">
|
||||
<Label className="text-xs text-muted-foreground uppercase tracking-wide">
|
||||
Datos de la Empresa
|
||||
</Label>
|
||||
<Input
|
||||
name="empresaNombre"
|
||||
placeholder="Nombre de la empresa"
|
||||
required
|
||||
/>
|
||||
<Input
|
||||
name="empresaRfc"
|
||||
placeholder="RFC (ej: ABC123456XY1)"
|
||||
maxLength={13}
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<Label className="text-xs text-muted-foreground uppercase tracking-wide">
|
||||
Datos del Administrador
|
||||
</Label>
|
||||
<Input
|
||||
name="nombre"
|
||||
placeholder="Tu nombre completo"
|
||||
required
|
||||
/>
|
||||
<Input
|
||||
name="email"
|
||||
type="email"
|
||||
placeholder="tu@email.com"
|
||||
required
|
||||
/>
|
||||
<Input
|
||||
name="password"
|
||||
type="password"
|
||||
placeholder="Contraseña (mín. 8 caracteres)"
|
||||
minLength={8}
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
</CardContent>
|
||||
<CardFooter className="flex flex-col gap-4">
|
||||
<Button type="submit" className="w-full" disabled={isLoading}>
|
||||
{isLoading ? 'Creando cuenta...' : 'Crear Cuenta Gratis'}
|
||||
</Button>
|
||||
<p className="text-sm text-muted-foreground text-center">
|
||||
¿Ya tienes cuenta?{' '}
|
||||
<Link href="/login" className="text-primary hover:underline">
|
||||
Inicia sesión
|
||||
</Link>
|
||||
</p>
|
||||
</CardFooter>
|
||||
</form>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
22
apps/web/lib/api/auth.ts
Normal file
22
apps/web/lib/api/auth.ts
Normal file
@@ -0,0 +1,22 @@
|
||||
import { apiClient } from './client';
|
||||
import type { LoginRequest, RegisterRequest, LoginResponse } from '@horux/shared';
|
||||
|
||||
export async function login(data: LoginRequest): Promise<LoginResponse> {
|
||||
const response = await apiClient.post<LoginResponse>('/auth/login', data);
|
||||
return response.data;
|
||||
}
|
||||
|
||||
export async function register(data: RegisterRequest): Promise<LoginResponse> {
|
||||
const response = await apiClient.post<LoginResponse>('/auth/register', data);
|
||||
return response.data;
|
||||
}
|
||||
|
||||
export async function logout(): Promise<void> {
|
||||
const refreshToken = localStorage.getItem('refreshToken');
|
||||
await apiClient.post('/auth/logout', { refreshToken });
|
||||
}
|
||||
|
||||
export async function getMe(): Promise<LoginResponse['user']> {
|
||||
const response = await apiClient.get('/auth/me');
|
||||
return response.data.user;
|
||||
}
|
||||
52
apps/web/lib/api/client.ts
Normal file
52
apps/web/lib/api/client.ts
Normal file
@@ -0,0 +1,52 @@
|
||||
import axios from 'axios';
|
||||
|
||||
export const apiClient = axios.create({
|
||||
baseURL: process.env.NEXT_PUBLIC_API_URL || 'http://localhost:4000/api',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
});
|
||||
|
||||
apiClient.interceptors.request.use((config) => {
|
||||
if (typeof window !== 'undefined') {
|
||||
const token = localStorage.getItem('accessToken');
|
||||
if (token) {
|
||||
config.headers.Authorization = `Bearer ${token}`;
|
||||
}
|
||||
}
|
||||
return config;
|
||||
});
|
||||
|
||||
apiClient.interceptors.response.use(
|
||||
(response) => response,
|
||||
async (error) => {
|
||||
const originalRequest = error.config;
|
||||
|
||||
if (error.response?.status === 401 && !originalRequest._retry) {
|
||||
originalRequest._retry = true;
|
||||
|
||||
try {
|
||||
const refreshToken = localStorage.getItem('refreshToken');
|
||||
if (refreshToken) {
|
||||
const response = await axios.post(
|
||||
`${process.env.NEXT_PUBLIC_API_URL || 'http://localhost:4000/api'}/auth/refresh`,
|
||||
{ refreshToken }
|
||||
);
|
||||
|
||||
const { accessToken, refreshToken: newRefreshToken } = response.data;
|
||||
localStorage.setItem('accessToken', accessToken);
|
||||
localStorage.setItem('refreshToken', newRefreshToken);
|
||||
|
||||
originalRequest.headers.Authorization = `Bearer ${accessToken}`;
|
||||
return apiClient(originalRequest);
|
||||
}
|
||||
} catch {
|
||||
localStorage.removeItem('accessToken');
|
||||
localStorage.removeItem('refreshToken');
|
||||
window.location.href = '/login';
|
||||
}
|
||||
}
|
||||
|
||||
return Promise.reject(error);
|
||||
}
|
||||
);
|
||||
34
apps/web/stores/auth-store.ts
Normal file
34
apps/web/stores/auth-store.ts
Normal file
@@ -0,0 +1,34 @@
|
||||
import { create } from 'zustand';
|
||||
import { persist } from 'zustand/middleware';
|
||||
import type { UserInfo } from '@horux/shared';
|
||||
|
||||
interface AuthState {
|
||||
user: UserInfo | null;
|
||||
isAuthenticated: boolean;
|
||||
setUser: (user: UserInfo | null) => void;
|
||||
setTokens: (accessToken: string, refreshToken: string) => void;
|
||||
logout: () => void;
|
||||
}
|
||||
|
||||
export const useAuthStore = create<AuthState>()(
|
||||
persist(
|
||||
(set) => ({
|
||||
user: null,
|
||||
isAuthenticated: false,
|
||||
setUser: (user) => set({ user, isAuthenticated: !!user }),
|
||||
setTokens: (accessToken, refreshToken) => {
|
||||
localStorage.setItem('accessToken', accessToken);
|
||||
localStorage.setItem('refreshToken', refreshToken);
|
||||
},
|
||||
logout: () => {
|
||||
localStorage.removeItem('accessToken');
|
||||
localStorage.removeItem('refreshToken');
|
||||
set({ user: null, isAuthenticated: false });
|
||||
},
|
||||
}),
|
||||
{
|
||||
name: 'horux-auth',
|
||||
partialize: (state) => ({ user: state.user, isAuthenticated: state.isAuthenticated }),
|
||||
}
|
||||
)
|
||||
);
|
||||
Reference in New Issue
Block a user