feat(auth): implement authentication service, guards, and interceptors
- Add AuthService for handling login, registration, and session management. - Create auth guards to protect routes based on authentication status. - Implement auth interceptor to attach JWT token to HTTP requests and handle 401 errors. - Add unit tests for AuthService, guards, and interceptor. - Create login and registration components with form validation and error handling. - Update routing to include guards for login and registration pages.
This commit is contained in:
@@ -1,9 +1,11 @@
|
||||
import { provideHttpClient, withFetch } from '@angular/common/http';
|
||||
import { provideHttpClient, withFetch, withInterceptors } from '@angular/common/http';
|
||||
import { ApplicationConfig, provideAppInitializer, provideBrowserGlobalErrorListeners } from '@angular/core';
|
||||
import { provideRouter } from '@angular/router';
|
||||
import { provideClientHydration } from '@angular/platform-browser';
|
||||
|
||||
import { routes } from './app.routes';
|
||||
import { authBootstrap } from './core/services/auth/auth-bootstrap';
|
||||
import { authInterceptor } from './core/services/auth/auth.interceptor';
|
||||
import { tenantBootstrap } from './core/services/tenant-bootstrap';
|
||||
|
||||
export const appConfig: ApplicationConfig = {
|
||||
@@ -11,7 +13,8 @@ export const appConfig: ApplicationConfig = {
|
||||
provideBrowserGlobalErrorListeners(),
|
||||
provideRouter(routes),
|
||||
provideClientHydration(),
|
||||
provideHttpClient(withFetch()),
|
||||
provideHttpClient(withFetch(), withInterceptors([authInterceptor])),
|
||||
provideAppInitializer(authBootstrap),
|
||||
provideAppInitializer(tenantBootstrap)
|
||||
]
|
||||
};
|
||||
|
||||
@@ -1,14 +1,15 @@
|
||||
import { signal } from '@angular/core';
|
||||
import { computed, signal } from '@angular/core';
|
||||
import { TestBed } from '@angular/core/testing';
|
||||
import { provideRouter, Router } from '@angular/router';
|
||||
|
||||
import { of } from 'rxjs';
|
||||
|
||||
import { App } from './app';
|
||||
import { routes } from './app.routes';
|
||||
import { AuthService } from './core/services/auth/auth.service';
|
||||
import { CartService } from './core/services/cart/cart.service';
|
||||
import { Tenant } from './core/services/tenant.interface';
|
||||
import { TenantService } from './core/services/tenant.service';
|
||||
import { CartService } from './core/services/cart/cart.service';
|
||||
import { routes } from './app.routes';
|
||||
|
||||
const tenant: Tenant = {
|
||||
id: 1,
|
||||
@@ -47,9 +48,33 @@ function createTenantServiceStub(
|
||||
};
|
||||
}
|
||||
|
||||
function createAuthServiceStub(isAuthenticated = false) {
|
||||
const tokenState = signal<string | null>(isAuthenticated ? 'test-token' : null);
|
||||
const userState = signal(
|
||||
isAuthenticated ? { id: 1, nombre_apellido: 'Ada Lovelace', email: 'ada@example.com' } : null
|
||||
);
|
||||
|
||||
return {
|
||||
user: userState.asReadonly(),
|
||||
token: tokenState.asReadonly(),
|
||||
isAuthenticated: computed(() => tokenState() !== null),
|
||||
login: vi.fn(),
|
||||
register: vi.fn(),
|
||||
logout: vi.fn(),
|
||||
loadCurrentUser: vi.fn(),
|
||||
hydrateSession: vi.fn(),
|
||||
bootstrap: vi.fn().mockResolvedValue(undefined),
|
||||
clearSession: vi.fn(() => {
|
||||
userState.set(null);
|
||||
tokenState.set(null);
|
||||
})
|
||||
};
|
||||
}
|
||||
|
||||
async function renderAppAt(
|
||||
url: string,
|
||||
tenantService: ReturnType<typeof createTenantServiceStub> = createTenantServiceStub()
|
||||
tenantService: ReturnType<typeof createTenantServiceStub> = createTenantServiceStub(),
|
||||
authService: ReturnType<typeof createAuthServiceStub> = createAuthServiceStub()
|
||||
) {
|
||||
TestBed.resetTestingModule();
|
||||
|
||||
@@ -67,6 +92,10 @@ async function renderAppAt(
|
||||
cart: signal(null).asReadonly(),
|
||||
loadCart: () => of({ id: 1, items: [], subtotal: '0' })
|
||||
}
|
||||
},
|
||||
{
|
||||
provide: AuthService,
|
||||
useValue: authService
|
||||
}
|
||||
]
|
||||
}).compileComponents();
|
||||
@@ -112,33 +141,41 @@ describe('app routes', () => {
|
||||
|
||||
expect(router.url).toBe('/login');
|
||||
expect(compiled.querySelector('app-login-page')).not.toBeNull();
|
||||
expect(compiled.textContent).toContain('Iniciar sesión');
|
||||
expect(compiled.textContent).toContain('Iniciar sesion');
|
||||
expect(compiled.textContent).toContain('Crear cuenta');
|
||||
});
|
||||
|
||||
it('loads the register page at /register and renders the shared auth fields', async () => {
|
||||
const { fixture, router } = await renderAppAt('/register');
|
||||
const compiled = fixture.nativeElement as HTMLElement;
|
||||
const placeholders = Array.from(compiled.querySelectorAll('input')).map((input) =>
|
||||
const registerPage = compiled.querySelector('app-register-page');
|
||||
const placeholders = Array.from(registerPage?.querySelectorAll('input') ?? []).map((input) =>
|
||||
input.getAttribute('placeholder')
|
||||
);
|
||||
|
||||
expect(router.url).toBe('/register');
|
||||
expect(compiled.querySelector('app-register-page')).not.toBeNull();
|
||||
expect(registerPage).not.toBeNull();
|
||||
expect(compiled.textContent).toContain('CREAR CUENTA');
|
||||
expect(compiled.textContent).toContain('Volver');
|
||||
expect(placeholders).toEqual([
|
||||
'Nombre y Apellido',
|
||||
'Email',
|
||||
'Contraseña',
|
||||
'Repetir Contraseña'
|
||||
'Contrasena',
|
||||
'Repetir Contrasena'
|
||||
]);
|
||||
});
|
||||
|
||||
it('redirects authenticated users away from /login', async () => {
|
||||
const { router } = await renderAppAt('/login', createTenantServiceStub(), createAuthServiceStub(true));
|
||||
|
||||
expect(router.url).toBe('/');
|
||||
});
|
||||
|
||||
it('renders the tenant not found screen for any route when the tenant is missing', async () => {
|
||||
const { fixture } = await renderAppAt(
|
||||
'/componentes-test/reutilizables',
|
||||
createTenantServiceStub('not-found', null)
|
||||
createTenantServiceStub('not-found', null),
|
||||
createAuthServiceStub()
|
||||
);
|
||||
const compiled = fixture.nativeElement as HTMLElement;
|
||||
|
||||
|
||||
9
src/app/core/services/auth/auth-bootstrap.ts
Normal file
9
src/app/core/services/auth/auth-bootstrap.ts
Normal file
@@ -0,0 +1,9 @@
|
||||
import { inject } from '@angular/core';
|
||||
|
||||
import { AuthService } from './auth.service';
|
||||
|
||||
export function authBootstrap(): Promise<void> {
|
||||
const authService = inject(AuthService);
|
||||
|
||||
return authService.bootstrap();
|
||||
}
|
||||
62
src/app/core/services/auth/auth.guards.spec.ts
Normal file
62
src/app/core/services/auth/auth.guards.spec.ts
Normal file
@@ -0,0 +1,62 @@
|
||||
import { computed, signal } from '@angular/core';
|
||||
import { TestBed } from '@angular/core/testing';
|
||||
import { provideRouter, Router, UrlTree } from '@angular/router';
|
||||
|
||||
import { AuthService } from './auth.service';
|
||||
import { authGuard, guestOnlyGuard } from './auth.guards';
|
||||
|
||||
function createAuthServiceStub(isAuthenticated = false) {
|
||||
const tokenState = signal<string | null>(isAuthenticated ? 'jwt-token' : null);
|
||||
|
||||
return {
|
||||
isAuthenticated: computed(() => tokenState() !== null)
|
||||
};
|
||||
}
|
||||
|
||||
describe('auth guards', () => {
|
||||
beforeEach(() => {
|
||||
TestBed.resetTestingModule();
|
||||
});
|
||||
|
||||
it('redirects unauthenticated users to /login', () => {
|
||||
TestBed.configureTestingModule({
|
||||
providers: [provideRouter([]), { provide: AuthService, useValue: createAuthServiceStub() }]
|
||||
});
|
||||
|
||||
const result = TestBed.runInInjectionContext(() => authGuard(null as never, null as never));
|
||||
|
||||
expect(result instanceof UrlTree).toBe(true);
|
||||
expect(TestBed.inject(Router).serializeUrl(result as UrlTree)).toBe('/login');
|
||||
});
|
||||
|
||||
it('allows authenticated users through authGuard', () => {
|
||||
TestBed.configureTestingModule({
|
||||
providers: [provideRouter([]), { provide: AuthService, useValue: createAuthServiceStub(true) }]
|
||||
});
|
||||
|
||||
const result = TestBed.runInInjectionContext(() => authGuard(null as never, null as never));
|
||||
|
||||
expect(result).toBe(true);
|
||||
});
|
||||
|
||||
it('redirects authenticated users away from guest routes', () => {
|
||||
TestBed.configureTestingModule({
|
||||
providers: [provideRouter([]), { provide: AuthService, useValue: createAuthServiceStub(true) }]
|
||||
});
|
||||
|
||||
const result = TestBed.runInInjectionContext(() => guestOnlyGuard(null as never, null as never));
|
||||
|
||||
expect(result instanceof UrlTree).toBe(true);
|
||||
expect(TestBed.inject(Router).serializeUrl(result as UrlTree)).toBe('/');
|
||||
});
|
||||
|
||||
it('allows guests into login/register routes', () => {
|
||||
TestBed.configureTestingModule({
|
||||
providers: [provideRouter([]), { provide: AuthService, useValue: createAuthServiceStub() }]
|
||||
});
|
||||
|
||||
const result = TestBed.runInInjectionContext(() => guestOnlyGuard(null as never, null as never));
|
||||
|
||||
expect(result).toBe(true);
|
||||
});
|
||||
});
|
||||
18
src/app/core/services/auth/auth.guards.ts
Normal file
18
src/app/core/services/auth/auth.guards.ts
Normal file
@@ -0,0 +1,18 @@
|
||||
import { inject } from '@angular/core';
|
||||
import { CanActivateFn, Router } from '@angular/router';
|
||||
|
||||
import { AuthService } from './auth.service';
|
||||
|
||||
export const authGuard: CanActivateFn = () => {
|
||||
const authService = inject(AuthService);
|
||||
const router = inject(Router);
|
||||
|
||||
return authService.isAuthenticated() ? true : router.createUrlTree(['/login']);
|
||||
};
|
||||
|
||||
export const guestOnlyGuard: CanActivateFn = () => {
|
||||
const authService = inject(AuthService);
|
||||
const router = inject(Router);
|
||||
|
||||
return authService.isAuthenticated() ? router.createUrlTree(['/']) : true;
|
||||
};
|
||||
96
src/app/core/services/auth/auth.interceptor.spec.ts
Normal file
96
src/app/core/services/auth/auth.interceptor.spec.ts
Normal file
@@ -0,0 +1,96 @@
|
||||
import { HttpClient } from '@angular/common/http';
|
||||
import { provideHttpClient, withInterceptors } from '@angular/common/http';
|
||||
import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing';
|
||||
import { computed, signal } from '@angular/core';
|
||||
import { TestBed } from '@angular/core/testing';
|
||||
|
||||
import { environment } from '../../../../environments/environment';
|
||||
import { AuthService } from './auth.service';
|
||||
import { authInterceptor } from './auth.interceptor';
|
||||
|
||||
function createAuthServiceStub(token: string | null = null) {
|
||||
const tokenState = signal(token);
|
||||
|
||||
return {
|
||||
token: tokenState.asReadonly(),
|
||||
isAuthenticated: computed(() => tokenState() !== null),
|
||||
clearSession: vi.fn(() => tokenState.set(null))
|
||||
};
|
||||
}
|
||||
|
||||
describe('authInterceptor', () => {
|
||||
beforeEach(() => {
|
||||
TestBed.resetTestingModule();
|
||||
});
|
||||
|
||||
it('adds the bearer token when a session exists', () => {
|
||||
const authService = createAuthServiceStub('jwt-token');
|
||||
|
||||
TestBed.configureTestingModule({
|
||||
providers: [
|
||||
provideHttpClient(withInterceptors([authInterceptor])),
|
||||
provideHttpClientTesting(),
|
||||
{ provide: AuthService, useValue: authService }
|
||||
]
|
||||
});
|
||||
|
||||
const client = TestBed.inject(HttpClient);
|
||||
const httpController = TestBed.inject(HttpTestingController);
|
||||
|
||||
client.get(`${environment.url}me`).subscribe();
|
||||
|
||||
const request = httpController.expectOne(`${environment.url}me`);
|
||||
expect(request.request.headers.get('Authorization')).toBe('Bearer jwt-token');
|
||||
request.flush({ id: 1 });
|
||||
|
||||
httpController.verify();
|
||||
});
|
||||
|
||||
it('does not add the authorization header when no token exists', () => {
|
||||
const authService = createAuthServiceStub();
|
||||
|
||||
TestBed.configureTestingModule({
|
||||
providers: [
|
||||
provideHttpClient(withInterceptors([authInterceptor])),
|
||||
provideHttpClientTesting(),
|
||||
{ provide: AuthService, useValue: authService }
|
||||
]
|
||||
});
|
||||
|
||||
const client = TestBed.inject(HttpClient);
|
||||
const httpController = TestBed.inject(HttpTestingController);
|
||||
|
||||
client.get(`${environment.url}productos`).subscribe();
|
||||
|
||||
const request = httpController.expectOne(`${environment.url}productos`);
|
||||
expect(request.request.headers.has('Authorization')).toBe(false);
|
||||
request.flush([]);
|
||||
|
||||
httpController.verify();
|
||||
});
|
||||
|
||||
it('clears the local session when an authenticated request returns 401', () => {
|
||||
const authService = createAuthServiceStub('expired-token');
|
||||
|
||||
TestBed.configureTestingModule({
|
||||
providers: [
|
||||
provideHttpClient(withInterceptors([authInterceptor])),
|
||||
provideHttpClientTesting(),
|
||||
{ provide: AuthService, useValue: authService }
|
||||
]
|
||||
});
|
||||
|
||||
const client = TestBed.inject(HttpClient);
|
||||
const httpController = TestBed.inject(HttpTestingController);
|
||||
|
||||
client.get(`${environment.url}me`).subscribe({
|
||||
error: () => undefined
|
||||
});
|
||||
|
||||
const request = httpController.expectOne(`${environment.url}me`);
|
||||
request.flush({ message: 'Unauthorized' }, { status: 401, statusText: 'Unauthorized' });
|
||||
|
||||
expect(authService.clearSession).toHaveBeenCalledTimes(1);
|
||||
httpController.verify();
|
||||
});
|
||||
});
|
||||
37
src/app/core/services/auth/auth.interceptor.ts
Normal file
37
src/app/core/services/auth/auth.interceptor.ts
Normal file
@@ -0,0 +1,37 @@
|
||||
import {
|
||||
HttpErrorResponse,
|
||||
HttpEvent,
|
||||
HttpHandlerFn,
|
||||
HttpInterceptorFn,
|
||||
HttpRequest
|
||||
} from '@angular/common/http';
|
||||
import { inject } from '@angular/core';
|
||||
import { Observable, catchError, throwError } from 'rxjs';
|
||||
|
||||
import { AuthService } from './auth.service';
|
||||
|
||||
export const authInterceptor: HttpInterceptorFn = (
|
||||
request: HttpRequest<unknown>,
|
||||
next: HttpHandlerFn
|
||||
): Observable<HttpEvent<unknown>> => {
|
||||
const authService = inject(AuthService);
|
||||
const token = authService.token();
|
||||
|
||||
const authenticatedRequest = token
|
||||
? request.clone({
|
||||
setHeaders: {
|
||||
Authorization: `Bearer ${token}`
|
||||
}
|
||||
})
|
||||
: request;
|
||||
|
||||
return next(authenticatedRequest).pipe(
|
||||
catchError((error: unknown) => {
|
||||
if (error instanceof HttpErrorResponse && error.status === 401 && token) {
|
||||
authService.clearSession();
|
||||
}
|
||||
|
||||
return throwError(() => error);
|
||||
})
|
||||
);
|
||||
};
|
||||
29
src/app/core/services/auth/auth.interfaces.ts
Normal file
29
src/app/core/services/auth/auth.interfaces.ts
Normal file
@@ -0,0 +1,29 @@
|
||||
export interface AuthUser {
|
||||
id: number;
|
||||
nombre_apellido: string;
|
||||
email: string;
|
||||
}
|
||||
|
||||
export interface LoginPayload {
|
||||
email: string;
|
||||
password: string;
|
||||
}
|
||||
|
||||
export interface RegisterPayload {
|
||||
nombre_apellido: string;
|
||||
email: string;
|
||||
password: string;
|
||||
password_confirmation: string;
|
||||
}
|
||||
|
||||
export interface LoginResponse {
|
||||
message: string;
|
||||
token: string;
|
||||
token_type: 'Bearer';
|
||||
user: AuthUser;
|
||||
}
|
||||
|
||||
export interface RegisterResponse {
|
||||
message: string;
|
||||
data: AuthUser;
|
||||
}
|
||||
188
src/app/core/services/auth/auth.service.spec.ts
Normal file
188
src/app/core/services/auth/auth.service.spec.ts
Normal file
@@ -0,0 +1,188 @@
|
||||
import { PLATFORM_ID } from '@angular/core';
|
||||
import { TestBed } from '@angular/core/testing';
|
||||
import { provideHttpClient } from '@angular/common/http';
|
||||
import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing';
|
||||
|
||||
import { environment } from '../../../../environments/environment';
|
||||
import { AuthService } from './auth.service';
|
||||
|
||||
describe('AuthService', () => {
|
||||
beforeEach(() => {
|
||||
window.localStorage.clear();
|
||||
TestBed.resetTestingModule();
|
||||
});
|
||||
|
||||
it('stores token and user on successful login', () => {
|
||||
TestBed.configureTestingModule({
|
||||
providers: [provideHttpClient(), provideHttpClientTesting(), AuthService]
|
||||
});
|
||||
|
||||
const service = TestBed.inject(AuthService);
|
||||
const httpController = TestBed.inject(HttpTestingController);
|
||||
|
||||
service.login({ email: 'ada@example.com', password: 'secret123' }).subscribe((user) => {
|
||||
expect(user.email).toBe('ada@example.com');
|
||||
});
|
||||
|
||||
const request = httpController.expectOne(`${environment.url}login`);
|
||||
expect(request.request.method).toBe('POST');
|
||||
request.flush({
|
||||
message: 'Sesion iniciada correctamente.',
|
||||
token: 'plain-text-token',
|
||||
token_type: 'Bearer',
|
||||
user: {
|
||||
id: 1,
|
||||
nombre_apellido: 'Ada Lovelace',
|
||||
email: 'ada@example.com'
|
||||
}
|
||||
});
|
||||
|
||||
expect(service.token()).toBe('plain-text-token');
|
||||
expect(service.user()?.email).toBe('ada@example.com');
|
||||
expect(service.isAuthenticated()).toBe(true);
|
||||
expect(window.localStorage.getItem('shopit.auth.token')).toBe('plain-text-token');
|
||||
|
||||
httpController.verify();
|
||||
});
|
||||
|
||||
it('hydrates token from localStorage and loads the current user during bootstrap', async () => {
|
||||
window.localStorage.setItem('shopit.auth.token', 'persisted-token');
|
||||
|
||||
TestBed.configureTestingModule({
|
||||
providers: [provideHttpClient(), provideHttpClientTesting(), AuthService]
|
||||
});
|
||||
|
||||
const service = TestBed.inject(AuthService);
|
||||
const httpController = TestBed.inject(HttpTestingController);
|
||||
|
||||
const bootstrapPromise = service.bootstrap();
|
||||
const request = httpController.expectOne(`${environment.url}me`);
|
||||
|
||||
expect(request.request.method).toBe('GET');
|
||||
request.flush({
|
||||
id: 9,
|
||||
nombre_apellido: 'Grace Hopper',
|
||||
email: 'grace@example.com'
|
||||
});
|
||||
|
||||
await expect(bootstrapPromise).resolves.toBeUndefined();
|
||||
expect(service.user()?.email).toBe('grace@example.com');
|
||||
expect(service.isAuthenticated()).toBe(true);
|
||||
|
||||
httpController.verify();
|
||||
});
|
||||
|
||||
it('clears the session when bootstrap receives 401 from /me', async () => {
|
||||
window.localStorage.setItem('shopit.auth.token', 'expired-token');
|
||||
|
||||
TestBed.configureTestingModule({
|
||||
providers: [provideHttpClient(), provideHttpClientTesting(), AuthService]
|
||||
});
|
||||
|
||||
const service = TestBed.inject(AuthService);
|
||||
const httpController = TestBed.inject(HttpTestingController);
|
||||
|
||||
const bootstrapPromise = service.bootstrap();
|
||||
const request = httpController.expectOne(`${environment.url}me`);
|
||||
|
||||
request.flush({ message: 'Unauthorized' }, { status: 401, statusText: 'Unauthorized' });
|
||||
|
||||
await expect(bootstrapPromise).resolves.toBeUndefined();
|
||||
expect(service.user()).toBeNull();
|
||||
expect(service.token()).toBeNull();
|
||||
expect(service.isAuthenticated()).toBe(false);
|
||||
expect(window.localStorage.getItem('shopit.auth.token')).toBeNull();
|
||||
|
||||
httpController.verify();
|
||||
});
|
||||
|
||||
it('registers without creating a session', () => {
|
||||
TestBed.configureTestingModule({
|
||||
providers: [provideHttpClient(), provideHttpClientTesting(), AuthService]
|
||||
});
|
||||
|
||||
const service = TestBed.inject(AuthService);
|
||||
const httpController = TestBed.inject(HttpTestingController);
|
||||
|
||||
service
|
||||
.register({
|
||||
nombre_apellido: 'Ada Lovelace',
|
||||
email: 'ada@example.com',
|
||||
password: 'secret123',
|
||||
password_confirmation: 'secret123'
|
||||
})
|
||||
.subscribe((response) => {
|
||||
expect(response.data.email).toBe('ada@example.com');
|
||||
});
|
||||
|
||||
const request = httpController.expectOne(`${environment.url}register`);
|
||||
expect(request.request.method).toBe('POST');
|
||||
request.flush({
|
||||
message: 'Usuario registrado correctamente.',
|
||||
data: {
|
||||
id: 1,
|
||||
nombre_apellido: 'Ada Lovelace',
|
||||
email: 'ada@example.com'
|
||||
}
|
||||
});
|
||||
|
||||
expect(service.token()).toBeNull();
|
||||
expect(service.user()).toBeNull();
|
||||
expect(service.isAuthenticated()).toBe(false);
|
||||
|
||||
httpController.verify();
|
||||
});
|
||||
|
||||
it('clears local session even when logout request fails', () => {
|
||||
TestBed.configureTestingModule({
|
||||
providers: [provideHttpClient(), provideHttpClientTesting(), AuthService]
|
||||
});
|
||||
|
||||
const service = TestBed.inject(AuthService);
|
||||
const httpController = TestBed.inject(HttpTestingController);
|
||||
|
||||
service.login({ email: 'ada@example.com', password: 'secret123' }).subscribe();
|
||||
httpController.expectOne(`${environment.url}login`).flush({
|
||||
message: 'Sesion iniciada correctamente.',
|
||||
token: 'plain-text-token',
|
||||
token_type: 'Bearer',
|
||||
user: {
|
||||
id: 1,
|
||||
nombre_apellido: 'Ada Lovelace',
|
||||
email: 'ada@example.com'
|
||||
}
|
||||
});
|
||||
|
||||
service.logout().subscribe({
|
||||
error: () => undefined
|
||||
});
|
||||
|
||||
const logoutRequest = httpController.expectOne(`${environment.url}logout`);
|
||||
expect(logoutRequest.request.method).toBe('POST');
|
||||
logoutRequest.flush({ message: 'Unauthorized' }, { status: 401, statusText: 'Unauthorized' });
|
||||
|
||||
expect(service.token()).toBeNull();
|
||||
expect(service.user()).toBeNull();
|
||||
expect(window.localStorage.getItem('shopit.auth.token')).toBeNull();
|
||||
|
||||
httpController.verify();
|
||||
});
|
||||
|
||||
it('does not access localStorage on the server', () => {
|
||||
TestBed.configureTestingModule({
|
||||
providers: [
|
||||
provideHttpClient(),
|
||||
provideHttpClientTesting(),
|
||||
AuthService,
|
||||
{ provide: PLATFORM_ID, useValue: 'server' }
|
||||
]
|
||||
});
|
||||
|
||||
const service = TestBed.inject(AuthService);
|
||||
|
||||
service.hydrateSession();
|
||||
|
||||
expect(service.token()).toBeNull();
|
||||
expect(service.isAuthenticated()).toBe(false);
|
||||
});
|
||||
});
|
||||
115
src/app/core/services/auth/auth.service.ts
Normal file
115
src/app/core/services/auth/auth.service.ts
Normal file
@@ -0,0 +1,115 @@
|
||||
import { HttpClient, HttpErrorResponse } from '@angular/common/http';
|
||||
import { isPlatformBrowser } from '@angular/common';
|
||||
import { computed, inject, Injectable, PLATFORM_ID, signal } from '@angular/core';
|
||||
import { firstValueFrom, map, Observable, of, tap } from 'rxjs';
|
||||
|
||||
import { environment } from '../../../../environments/environment';
|
||||
import {
|
||||
AuthUser,
|
||||
LoginPayload,
|
||||
LoginResponse,
|
||||
RegisterPayload,
|
||||
RegisterResponse
|
||||
} from './auth.interfaces';
|
||||
|
||||
const AUTH_TOKEN_STORAGE_KEY = 'shopit.auth.token';
|
||||
|
||||
@Injectable({
|
||||
providedIn: 'root'
|
||||
})
|
||||
export class AuthService {
|
||||
private readonly http = inject(HttpClient);
|
||||
private readonly platformId = inject(PLATFORM_ID);
|
||||
|
||||
private readonly userState = signal<AuthUser | null>(null);
|
||||
private readonly tokenState = signal<string | null>(null);
|
||||
|
||||
readonly user = this.userState.asReadonly();
|
||||
readonly token = this.tokenState.asReadonly();
|
||||
readonly isAuthenticated = computed(() => this.tokenState() !== null);
|
||||
|
||||
login(payload: LoginPayload): Observable<AuthUser> {
|
||||
return this.http.post<LoginResponse>(`${environment.url}login`, payload).pipe(
|
||||
tap((response) => this.applyAuthenticatedState(response.token, response.user)),
|
||||
map((response) => response.user)
|
||||
);
|
||||
}
|
||||
|
||||
register(payload: RegisterPayload): Observable<RegisterResponse> {
|
||||
return this.http.post<RegisterResponse>(`${environment.url}register`, payload);
|
||||
}
|
||||
|
||||
logout(): Observable<void> {
|
||||
if (!this.tokenState()) {
|
||||
this.clearSession();
|
||||
return of(void 0);
|
||||
}
|
||||
|
||||
return this.http.post<void>(`${environment.url}logout`, {}).pipe(
|
||||
tap({
|
||||
next: () => this.clearSession(),
|
||||
error: () => this.clearSession()
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
async bootstrap(): Promise<void> {
|
||||
this.hydrateSession();
|
||||
|
||||
if (!this.tokenState() || this.userState()) {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
await firstValueFrom(this.loadCurrentUser());
|
||||
} catch (error) {
|
||||
if (this.isUnauthorizedError(error)) {
|
||||
this.clearSession();
|
||||
return;
|
||||
}
|
||||
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
loadCurrentUser(): Observable<AuthUser> {
|
||||
return this.http.get<AuthUser>(`${environment.url}me`).pipe(
|
||||
tap((user) => this.userState.set(user))
|
||||
);
|
||||
}
|
||||
|
||||
hydrateSession(): void {
|
||||
if (!isPlatformBrowser(this.platformId)) {
|
||||
return;
|
||||
}
|
||||
|
||||
const token = window.localStorage.getItem(AUTH_TOKEN_STORAGE_KEY);
|
||||
this.tokenState.set(token);
|
||||
}
|
||||
|
||||
clearSession(): void {
|
||||
this.userState.set(null);
|
||||
this.tokenState.set(null);
|
||||
|
||||
if (!isPlatformBrowser(this.platformId)) {
|
||||
return;
|
||||
}
|
||||
|
||||
window.localStorage.removeItem(AUTH_TOKEN_STORAGE_KEY);
|
||||
}
|
||||
|
||||
private applyAuthenticatedState(token: string, user: AuthUser): void {
|
||||
this.tokenState.set(token);
|
||||
this.userState.set(user);
|
||||
|
||||
if (!isPlatformBrowser(this.platformId)) {
|
||||
return;
|
||||
}
|
||||
|
||||
window.localStorage.setItem(AUTH_TOKEN_STORAGE_KEY, token);
|
||||
}
|
||||
|
||||
private isUnauthorizedError(error: unknown): error is HttpErrorResponse {
|
||||
return error instanceof HttpErrorResponse && error.status === 401;
|
||||
}
|
||||
}
|
||||
@@ -1,29 +1,67 @@
|
||||
<header class="login-page__header text-center">
|
||||
<h1 id="login-title" class="auth-title">Iniciar sesión</h1>
|
||||
<h1 id="login-title" class="auth-title">Iniciar sesion</h1>
|
||||
</header>
|
||||
|
||||
<form class="login-page__form d-grid gap-3" novalidate aria-labelledby="login-title">
|
||||
<form
|
||||
class="login-page__form d-grid gap-3"
|
||||
novalidate
|
||||
aria-labelledby="login-title"
|
||||
[formGroup]="form"
|
||||
(ngSubmit)="onSubmit()"
|
||||
>
|
||||
<div class="d-grid gap-3">
|
||||
<label class="visually-hidden" for="login-email">Email</label>
|
||||
<app-input id="login-email" type="email" placeholder="Email" />
|
||||
<app-input
|
||||
id="login-email"
|
||||
type="email"
|
||||
placeholder="Email"
|
||||
[value]="form.controls.email.value"
|
||||
[invalid]="showControlError('email')"
|
||||
(valueChange)="updateEmail($event)"
|
||||
/>
|
||||
@if (getControlError('email'); as errorMessage) {
|
||||
<small class="text-danger">{{ errorMessage }}</small>
|
||||
}
|
||||
|
||||
<div class="d-grid gap-1">
|
||||
<label class="visually-hidden" for="login-password">Contraseña</label>
|
||||
<app-input id="login-password" type="password" placeholder="Contrasena" />
|
||||
<label class="visually-hidden" for="login-password">Contrasena</label>
|
||||
<app-input
|
||||
id="login-password"
|
||||
type="password"
|
||||
placeholder="Contrasena"
|
||||
[value]="form.controls.password.value"
|
||||
[invalid]="showControlError('password')"
|
||||
(valueChange)="updatePassword($event)"
|
||||
/>
|
||||
@if (getControlError('password'); as errorMessage) {
|
||||
<small class="text-danger">{{ errorMessage }}</small>
|
||||
}
|
||||
<div class="text-end">
|
||||
<button type="button" class="login-page__forgot-password btn btn-link p-0 border-0 text-decoration-none">
|
||||
Olvidé mi contraseña
|
||||
Olvide mi contrasena
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="d-grid gap-2 text-center">
|
||||
<app-button hostClass="w-100 d-block" buttonClass="w-100">Ingresar</app-button>
|
||||
@if (serverError(); as errorMessage) {
|
||||
<small class="text-danger">{{ errorMessage }}</small>
|
||||
}
|
||||
<app-button
|
||||
type="submit"
|
||||
hostClass="w-100 d-block"
|
||||
buttonClass="w-100"
|
||||
[disabled]="isSubmitting()"
|
||||
>
|
||||
{{ isSubmitting() ? 'Ingresando...' : 'Ingresar' }}
|
||||
</app-button>
|
||||
<app-button
|
||||
type="button"
|
||||
variant="borderless"
|
||||
hostClass="w-100 d-block text-center"
|
||||
buttonClass="login-page__create-account px-3 py-2"
|
||||
[disabled]="isSubmitting()"
|
||||
(click)="goToRegister()"
|
||||
>
|
||||
Crear cuenta
|
||||
@@ -38,6 +76,7 @@
|
||||
</div>
|
||||
|
||||
<app-button
|
||||
type="button"
|
||||
variant="neutral-outline"
|
||||
hostClass="w-100 d-block"
|
||||
buttonClass="w-100 d-inline-flex align-items-center justify-content-center gap-2 py-2 fw-semibold"
|
||||
|
||||
@@ -0,0 +1,102 @@
|
||||
import { TestBed } from '@angular/core/testing';
|
||||
import { provideRouter, Router } from '@angular/router';
|
||||
import { of, throwError } from 'rxjs';
|
||||
|
||||
import { AuthService } from '../../../../core/services/auth/auth.service';
|
||||
import { LoginPageComponent } from './login-page.component';
|
||||
|
||||
describe('LoginPageComponent', () => {
|
||||
beforeEach(() => {
|
||||
TestBed.resetTestingModule();
|
||||
});
|
||||
|
||||
it('submits credentials and navigates to home on success', async () => {
|
||||
const authService = {
|
||||
login: vi.fn().mockReturnValue(
|
||||
of({
|
||||
id: 1,
|
||||
nombre_apellido: 'Ada Lovelace',
|
||||
email: 'ada@example.com'
|
||||
})
|
||||
)
|
||||
};
|
||||
|
||||
await TestBed.configureTestingModule({
|
||||
imports: [LoginPageComponent],
|
||||
providers: [provideRouter([]), { provide: AuthService, useValue: authService }]
|
||||
}).compileComponents();
|
||||
|
||||
const fixture = TestBed.createComponent(LoginPageComponent);
|
||||
const component = fixture.componentInstance as any;
|
||||
const router = TestBed.inject(Router);
|
||||
const navigateSpy = vi.spyOn(router, 'navigate').mockResolvedValue(true);
|
||||
|
||||
component.form.setValue({
|
||||
email: 'ada@example.com',
|
||||
password: 'secret123'
|
||||
});
|
||||
|
||||
component.onSubmit();
|
||||
|
||||
expect(authService.login).toHaveBeenCalledWith({
|
||||
email: 'ada@example.com',
|
||||
password: 'secret123'
|
||||
});
|
||||
expect(navigateSpy).toHaveBeenCalledWith(['/']);
|
||||
});
|
||||
|
||||
it('surfaces backend login errors', async () => {
|
||||
const authService = {
|
||||
login: vi.fn().mockReturnValue(
|
||||
throwError(() => ({
|
||||
error: {
|
||||
errors: {
|
||||
email: ['Las credenciales son invalidas.']
|
||||
}
|
||||
}
|
||||
}))
|
||||
)
|
||||
};
|
||||
|
||||
await TestBed.configureTestingModule({
|
||||
imports: [LoginPageComponent],
|
||||
providers: [provideRouter([]), { provide: AuthService, useValue: authService }]
|
||||
}).compileComponents();
|
||||
|
||||
const fixture = TestBed.createComponent(LoginPageComponent);
|
||||
const component = fixture.componentInstance as any;
|
||||
|
||||
component.form.setValue({
|
||||
email: 'ada@example.com',
|
||||
password: 'wrong-password'
|
||||
});
|
||||
|
||||
component.onSubmit();
|
||||
|
||||
expect(component.serverError()).toBe('Las credenciales son invalidas.');
|
||||
});
|
||||
|
||||
it('validates email length and password minimum length before submit', async () => {
|
||||
const authService = {
|
||||
login: vi.fn()
|
||||
};
|
||||
|
||||
await TestBed.configureTestingModule({
|
||||
imports: [LoginPageComponent],
|
||||
providers: [provideRouter([]), { provide: AuthService, useValue: authService }]
|
||||
}).compileComponents();
|
||||
|
||||
const fixture = TestBed.createComponent(LoginPageComponent);
|
||||
const component = fixture.componentInstance as any;
|
||||
|
||||
component.form.setValue({
|
||||
email: `${'a'.repeat(250)}@example.com`,
|
||||
password: '1234567'
|
||||
});
|
||||
component.onSubmit();
|
||||
|
||||
expect(authService.login).not.toHaveBeenCalled();
|
||||
expect(component.getControlError('email')).toBe('No puede superar los 255 caracteres.');
|
||||
expect(component.getControlError('password')).toBe('Debe tener al menos 8 caracteres.');
|
||||
});
|
||||
});
|
||||
@@ -1,20 +1,122 @@
|
||||
import { ChangeDetectionStrategy, Component, inject } from '@angular/core';
|
||||
import { ChangeDetectionStrategy, Component, inject, signal } from '@angular/core';
|
||||
import { FormBuilder, ReactiveFormsModule, Validators } from '@angular/forms';
|
||||
import { Router } from '@angular/router';
|
||||
|
||||
import { AuthService } from '../../../../core/services/auth/auth.service';
|
||||
import { ButtonComponent } from '../../../../shared/components/button/button.component';
|
||||
import { InputComponent } from '../../../../shared/components/input/input.component';
|
||||
|
||||
const PASSWORD_MIN_LENGTH = 8;
|
||||
const EMAIL_MAX_LENGTH = 255;
|
||||
|
||||
@Component({
|
||||
selector: 'app-login-page',
|
||||
imports: [InputComponent, ButtonComponent],
|
||||
imports: [ReactiveFormsModule, InputComponent, ButtonComponent],
|
||||
templateUrl: './login-page.component.html',
|
||||
styleUrl: './login-page.component.scss',
|
||||
changeDetection: ChangeDetectionStrategy.OnPush
|
||||
})
|
||||
export class LoginPageComponent {
|
||||
private readonly formBuilder = inject(FormBuilder);
|
||||
private readonly router = inject(Router);
|
||||
private readonly authService = inject(AuthService);
|
||||
|
||||
private readonly submittedState = signal(false);
|
||||
private readonly serverErrorState = signal<string | null>(null);
|
||||
private readonly isSubmittingState = signal(false);
|
||||
|
||||
protected readonly form = this.formBuilder.nonNullable.group({
|
||||
email: ['', [Validators.required, Validators.email, Validators.maxLength(EMAIL_MAX_LENGTH)]],
|
||||
password: ['', [Validators.required, Validators.minLength(PASSWORD_MIN_LENGTH)]]
|
||||
});
|
||||
protected readonly submitted = this.submittedState.asReadonly();
|
||||
protected readonly serverError = this.serverErrorState.asReadonly();
|
||||
protected readonly isSubmitting = this.isSubmittingState.asReadonly();
|
||||
|
||||
goToRegister(): void {
|
||||
void this.router.navigate(['/register']);
|
||||
}
|
||||
|
||||
onSubmit(): void {
|
||||
this.submittedState.set(true);
|
||||
this.serverErrorState.set(null);
|
||||
|
||||
if (this.form.invalid) {
|
||||
this.form.markAllAsTouched();
|
||||
return;
|
||||
}
|
||||
|
||||
this.isSubmittingState.set(true);
|
||||
|
||||
this.authService.login(this.form.getRawValue()).subscribe({
|
||||
next: () => {
|
||||
this.isSubmittingState.set(false);
|
||||
void this.router.navigate(['/']);
|
||||
},
|
||||
error: (error: unknown) => {
|
||||
this.isSubmittingState.set(false);
|
||||
this.serverErrorState.set(this.resolveErrorMessage(error));
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
protected updateEmail(value: string | number): void {
|
||||
this.form.controls.email.setValue(String(value));
|
||||
}
|
||||
|
||||
protected updatePassword(value: string | number): void {
|
||||
this.form.controls.password.setValue(String(value));
|
||||
}
|
||||
|
||||
protected showControlError(controlName: 'email' | 'password'): boolean {
|
||||
const control = this.form.controls[controlName];
|
||||
|
||||
return control.invalid && (control.touched || this.submitted());
|
||||
}
|
||||
|
||||
protected getControlError(controlName: 'email' | 'password'): string | null {
|
||||
const control = this.form.controls[controlName];
|
||||
|
||||
if (!this.showControlError(controlName)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (control.hasError('required')) {
|
||||
return 'Este campo es obligatorio.';
|
||||
}
|
||||
|
||||
if (control.hasError('maxlength')) {
|
||||
return `No puede superar los ${EMAIL_MAX_LENGTH} caracteres.`;
|
||||
}
|
||||
|
||||
if (control.hasError('email')) {
|
||||
return 'Ingresa un email valido.';
|
||||
}
|
||||
|
||||
if (control.hasError('minlength')) {
|
||||
return `Debe tener al menos ${PASSWORD_MIN_LENGTH} caracteres.`;
|
||||
}
|
||||
|
||||
return 'El valor ingresado no es valido.';
|
||||
}
|
||||
|
||||
private resolveErrorMessage(error: unknown): string {
|
||||
const errorPayload =
|
||||
typeof error === 'object' && error !== null && 'error' in error
|
||||
? (error as { error?: { errors?: Record<string, string[]>; message?: string } }).error
|
||||
: undefined;
|
||||
const apiErrors = errorPayload?.errors;
|
||||
const emailMessages = apiErrors?.['email'];
|
||||
const emailError = Array.isArray(emailMessages) ? emailMessages[0] : null;
|
||||
|
||||
if (typeof emailError === 'string' && emailError.trim()) {
|
||||
return emailError;
|
||||
}
|
||||
|
||||
if (typeof errorPayload?.message === 'string' && errorPayload.message.trim()) {
|
||||
return errorPayload.message;
|
||||
}
|
||||
|
||||
return 'No se pudo iniciar sesion. Intenta nuevamente.';
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,31 +2,84 @@
|
||||
<h1 id="register-title" class="auth-title">CREAR CUENTA</h1>
|
||||
</header>
|
||||
|
||||
<form class="register-page__form d-grid gap-3" novalidate aria-labelledby="register-title">
|
||||
<form
|
||||
class="register-page__form d-grid gap-3"
|
||||
novalidate
|
||||
aria-labelledby="register-title"
|
||||
[formGroup]="form"
|
||||
(ngSubmit)="onSubmit()"
|
||||
>
|
||||
<div class="d-grid gap-3">
|
||||
<label class="visually-hidden" for="register-full-name">Nombre y Apellido</label>
|
||||
<app-input id="register-full-name" placeholder="Nombre y Apellido" />
|
||||
<app-input
|
||||
id="register-full-name"
|
||||
placeholder="Nombre y Apellido"
|
||||
[value]="form.controls.nombre_apellido.value"
|
||||
[invalid]="showControlError('nombre_apellido')"
|
||||
(valueChange)="updateField('nombre_apellido', $event)"
|
||||
/>
|
||||
@if (getControlError('nombre_apellido'); as errorMessage) {
|
||||
<small class="text-danger">{{ errorMessage }}</small>
|
||||
}
|
||||
|
||||
<label class="visually-hidden" for="register-email">Email</label>
|
||||
<app-input id="register-email" type="email" placeholder="Email" />
|
||||
<app-input
|
||||
id="register-email"
|
||||
type="email"
|
||||
placeholder="Email"
|
||||
[value]="form.controls.email.value"
|
||||
[invalid]="showControlError('email')"
|
||||
(valueChange)="updateField('email', $event)"
|
||||
/>
|
||||
@if (getControlError('email'); as errorMessage) {
|
||||
<small class="text-danger">{{ errorMessage }}</small>
|
||||
}
|
||||
|
||||
<label class="visually-hidden" for="register-password">Contraseña</label>
|
||||
<app-input id="register-password" type="password" placeholder="Contraseña" />
|
||||
<label class="visually-hidden" for="register-password">Contrasena</label>
|
||||
<app-input
|
||||
id="register-password"
|
||||
type="password"
|
||||
placeholder="Contrasena"
|
||||
[value]="form.controls.password.value"
|
||||
[invalid]="showControlError('password')"
|
||||
(valueChange)="updateField('password', $event)"
|
||||
/>
|
||||
@if (getControlError('password'); as errorMessage) {
|
||||
<small class="text-danger">{{ errorMessage }}</small>
|
||||
}
|
||||
|
||||
<label class="visually-hidden" for="register-password-repeat">Repetir Contraseña</label>
|
||||
<label class="visually-hidden" for="register-password-repeat">Repetir Contrasena</label>
|
||||
<app-input
|
||||
id="register-password-repeat"
|
||||
type="password"
|
||||
placeholder="Repetir Contraseña"
|
||||
placeholder="Repetir Contrasena"
|
||||
[value]="form.controls.password_confirmation.value"
|
||||
[invalid]="showControlError('password_confirmation')"
|
||||
(valueChange)="updateField('password_confirmation', $event)"
|
||||
/>
|
||||
@if (getControlError('password_confirmation'); as errorMessage) {
|
||||
<small class="text-danger">{{ errorMessage }}</small>
|
||||
}
|
||||
</div>
|
||||
|
||||
<div class="d-grid gap-2 text-center">
|
||||
<app-button hostClass="w-100 d-block" buttonClass="w-100">Crear Cuenta</app-button>
|
||||
@if (serverError(); as errorMessage) {
|
||||
<small class="text-danger">{{ errorMessage }}</small>
|
||||
}
|
||||
<app-button
|
||||
type="submit"
|
||||
hostClass="w-100 d-block"
|
||||
buttonClass="w-100"
|
||||
[disabled]="isSubmitting()"
|
||||
>
|
||||
{{ isSubmitting() ? 'Creando cuenta...' : 'Crear Cuenta' }}
|
||||
</app-button>
|
||||
<app-button
|
||||
type="button"
|
||||
variant="borderless"
|
||||
hostClass="w-100 d-block text-center"
|
||||
buttonClass="register-page__back-action px-3 py-2"
|
||||
[disabled]="isSubmitting()"
|
||||
(click)="goToLogin()"
|
||||
>
|
||||
Volver
|
||||
|
||||
@@ -0,0 +1,138 @@
|
||||
import { TestBed } from '@angular/core/testing';
|
||||
import { provideRouter, Router } from '@angular/router';
|
||||
import { of, throwError } from 'rxjs';
|
||||
|
||||
import { AuthService } from '../../../../core/services/auth/auth.service';
|
||||
import { RegisterPageComponent } from './register-page.component';
|
||||
|
||||
describe('RegisterPageComponent', () => {
|
||||
beforeEach(() => {
|
||||
TestBed.resetTestingModule();
|
||||
});
|
||||
|
||||
it('submits registration data and redirects to /login on success', async () => {
|
||||
const authService = {
|
||||
register: vi.fn().mockReturnValue(
|
||||
of({
|
||||
message: 'Usuario registrado correctamente.',
|
||||
data: {
|
||||
id: 1,
|
||||
nombre_apellido: 'Ada Lovelace',
|
||||
email: 'ada@example.com'
|
||||
}
|
||||
})
|
||||
)
|
||||
};
|
||||
|
||||
await TestBed.configureTestingModule({
|
||||
imports: [RegisterPageComponent],
|
||||
providers: [provideRouter([]), { provide: AuthService, useValue: authService }]
|
||||
}).compileComponents();
|
||||
|
||||
const fixture = TestBed.createComponent(RegisterPageComponent);
|
||||
const component = fixture.componentInstance as any;
|
||||
const router = TestBed.inject(Router);
|
||||
const navigateSpy = vi.spyOn(router, 'navigate').mockResolvedValue(true);
|
||||
|
||||
component.form.setValue({
|
||||
nombre_apellido: 'Ada Lovelace',
|
||||
email: 'ada@example.com',
|
||||
password: 'secret123',
|
||||
password_confirmation: 'secret123'
|
||||
});
|
||||
|
||||
component.onSubmit();
|
||||
|
||||
expect(authService.register).toHaveBeenCalledWith({
|
||||
nombre_apellido: 'Ada Lovelace',
|
||||
email: 'ada@example.com',
|
||||
password: 'secret123',
|
||||
password_confirmation: 'secret123'
|
||||
});
|
||||
expect(navigateSpy).toHaveBeenCalledWith(['/login']);
|
||||
});
|
||||
|
||||
it('shows a mismatch message when passwords do not match', async () => {
|
||||
const authService = {
|
||||
register: vi.fn()
|
||||
};
|
||||
|
||||
await TestBed.configureTestingModule({
|
||||
imports: [RegisterPageComponent],
|
||||
providers: [provideRouter([]), { provide: AuthService, useValue: authService }]
|
||||
}).compileComponents();
|
||||
|
||||
const fixture = TestBed.createComponent(RegisterPageComponent);
|
||||
const component = fixture.componentInstance as any;
|
||||
|
||||
component.form.setValue({
|
||||
nombre_apellido: 'Ada Lovelace',
|
||||
email: 'ada@example.com',
|
||||
password: 'secret123',
|
||||
password_confirmation: 'different'
|
||||
});
|
||||
component.onSubmit();
|
||||
|
||||
expect(authService.register).not.toHaveBeenCalled();
|
||||
expect(component.getControlError('password_confirmation')).toBe('Las contrasenas no coinciden.');
|
||||
});
|
||||
|
||||
it('validates max length and password minimum length before submit', async () => {
|
||||
const authService = {
|
||||
register: vi.fn()
|
||||
};
|
||||
|
||||
await TestBed.configureTestingModule({
|
||||
imports: [RegisterPageComponent],
|
||||
providers: [provideRouter([]), { provide: AuthService, useValue: authService }]
|
||||
}).compileComponents();
|
||||
|
||||
const fixture = TestBed.createComponent(RegisterPageComponent);
|
||||
const component = fixture.componentInstance as any;
|
||||
|
||||
component.form.setValue({
|
||||
nombre_apellido: 'A'.repeat(256),
|
||||
email: `${'a'.repeat(250)}@example.com`,
|
||||
password: '1234567',
|
||||
password_confirmation: '1234567'
|
||||
});
|
||||
component.onSubmit();
|
||||
|
||||
expect(authService.register).not.toHaveBeenCalled();
|
||||
expect(component.getControlError('nombre_apellido')).toBe('No puede superar los 255 caracteres.');
|
||||
expect(component.getControlError('email')).toBe('No puede superar los 255 caracteres.');
|
||||
expect(component.getControlError('password')).toBe('Debe tener al menos 8 caracteres.');
|
||||
});
|
||||
|
||||
it('surfaces backend register errors', async () => {
|
||||
const authService = {
|
||||
register: vi.fn().mockReturnValue(
|
||||
throwError(() => ({
|
||||
error: {
|
||||
errors: {
|
||||
email: ['El email ya esta en uso.']
|
||||
}
|
||||
}
|
||||
}))
|
||||
)
|
||||
};
|
||||
|
||||
await TestBed.configureTestingModule({
|
||||
imports: [RegisterPageComponent],
|
||||
providers: [provideRouter([]), { provide: AuthService, useValue: authService }]
|
||||
}).compileComponents();
|
||||
|
||||
const fixture = TestBed.createComponent(RegisterPageComponent);
|
||||
const component = fixture.componentInstance as any;
|
||||
|
||||
component.form.setValue({
|
||||
nombre_apellido: 'Ada Lovelace',
|
||||
email: 'ada@example.com',
|
||||
password: 'secret123',
|
||||
password_confirmation: 'secret123'
|
||||
});
|
||||
component.onSubmit();
|
||||
|
||||
expect(component.serverError()).toBe('El email ya esta en uso.');
|
||||
});
|
||||
});
|
||||
@@ -1,20 +1,164 @@
|
||||
import { ChangeDetectionStrategy, Component, inject } from '@angular/core';
|
||||
import { ChangeDetectionStrategy, Component, inject, signal } from '@angular/core';
|
||||
import {
|
||||
AbstractControl,
|
||||
FormBuilder,
|
||||
ReactiveFormsModule,
|
||||
ValidationErrors,
|
||||
ValidatorFn,
|
||||
Validators
|
||||
} from '@angular/forms';
|
||||
import { Router } from '@angular/router';
|
||||
|
||||
import { AuthService } from '../../../../core/services/auth/auth.service';
|
||||
import { ButtonComponent } from '../../../../shared/components/button/button.component';
|
||||
import { InputComponent } from '../../../../shared/components/input/input.component';
|
||||
|
||||
const PASSWORD_MIN_LENGTH = 8;
|
||||
const TEXT_MAX_LENGTH = 255;
|
||||
|
||||
const passwordsMatchValidator: ValidatorFn = (
|
||||
control: AbstractControl
|
||||
): ValidationErrors | null => {
|
||||
const password = control.get('password')?.value;
|
||||
const passwordConfirmation = control.get('password_confirmation')?.value;
|
||||
|
||||
if (!password || !passwordConfirmation) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return password === passwordConfirmation ? null : { passwordMismatch: true };
|
||||
};
|
||||
|
||||
@Component({
|
||||
selector: 'app-register-page',
|
||||
imports: [InputComponent, ButtonComponent],
|
||||
imports: [ReactiveFormsModule, InputComponent, ButtonComponent],
|
||||
templateUrl: './register-page.component.html',
|
||||
styleUrl: './register-page.component.scss',
|
||||
changeDetection: ChangeDetectionStrategy.OnPush
|
||||
})
|
||||
export class RegisterPageComponent {
|
||||
private readonly formBuilder = inject(FormBuilder);
|
||||
private readonly router = inject(Router);
|
||||
private readonly authService = inject(AuthService);
|
||||
|
||||
private readonly submittedState = signal(false);
|
||||
private readonly serverErrorState = signal<string | null>(null);
|
||||
private readonly isSubmittingState = signal(false);
|
||||
|
||||
protected readonly form = this.formBuilder.nonNullable.group({
|
||||
nombre_apellido: ['', [Validators.required, Validators.maxLength(TEXT_MAX_LENGTH)]],
|
||||
email: [
|
||||
'',
|
||||
[Validators.required, Validators.email, Validators.maxLength(TEXT_MAX_LENGTH)]
|
||||
],
|
||||
password: ['', [Validators.required, Validators.minLength(PASSWORD_MIN_LENGTH)]],
|
||||
password_confirmation: ['', [Validators.required]]
|
||||
}, {
|
||||
validators: [passwordsMatchValidator]
|
||||
});
|
||||
protected readonly submitted = this.submittedState.asReadonly();
|
||||
protected readonly serverError = this.serverErrorState.asReadonly();
|
||||
protected readonly isSubmitting = this.isSubmittingState.asReadonly();
|
||||
|
||||
goToLogin(): void {
|
||||
void this.router.navigate(['/login']);
|
||||
}
|
||||
|
||||
onSubmit(): void {
|
||||
this.submittedState.set(true);
|
||||
this.serverErrorState.set(null);
|
||||
|
||||
if (this.form.invalid) {
|
||||
this.form.markAllAsTouched();
|
||||
return;
|
||||
}
|
||||
|
||||
this.isSubmittingState.set(true);
|
||||
|
||||
this.authService.register(this.form.getRawValue()).subscribe({
|
||||
next: () => {
|
||||
this.isSubmittingState.set(false);
|
||||
void this.router.navigate(['/login']);
|
||||
},
|
||||
error: (error: unknown) => {
|
||||
this.isSubmittingState.set(false);
|
||||
this.serverErrorState.set(this.resolveErrorMessage(error));
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
protected updateField(
|
||||
controlName: 'nombre_apellido' | 'email' | 'password' | 'password_confirmation',
|
||||
value: string | number
|
||||
): void {
|
||||
this.form.controls[controlName].setValue(String(value));
|
||||
}
|
||||
|
||||
protected showControlError(
|
||||
controlName: 'nombre_apellido' | 'email' | 'password' | 'password_confirmation'
|
||||
): boolean {
|
||||
const control = this.form.controls[controlName];
|
||||
const hasPasswordMismatch =
|
||||
controlName === 'password_confirmation' &&
|
||||
this.form.hasError('passwordMismatch') &&
|
||||
(control.touched || this.submitted());
|
||||
|
||||
return (control.invalid && (control.touched || this.submitted())) || hasPasswordMismatch;
|
||||
}
|
||||
|
||||
protected getControlError(
|
||||
controlName: 'nombre_apellido' | 'email' | 'password' | 'password_confirmation'
|
||||
): string | null {
|
||||
const control = this.form.controls[controlName];
|
||||
|
||||
if (!this.showControlError(controlName)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (control.hasError('required')) {
|
||||
return 'Este campo es obligatorio.';
|
||||
}
|
||||
|
||||
if (control.hasError('maxlength')) {
|
||||
return `No puede superar los ${TEXT_MAX_LENGTH} caracteres.`;
|
||||
}
|
||||
|
||||
if (control.hasError('email')) {
|
||||
return 'Ingresa un email valido.';
|
||||
}
|
||||
|
||||
if (control.hasError('minlength')) {
|
||||
return `Debe tener al menos ${PASSWORD_MIN_LENGTH} caracteres.`;
|
||||
}
|
||||
|
||||
if (controlName === 'password_confirmation' && this.form.hasError('passwordMismatch')) {
|
||||
return 'Las contrasenas no coinciden.';
|
||||
}
|
||||
|
||||
return 'El valor ingresado no es valido.';
|
||||
}
|
||||
|
||||
private resolveErrorMessage(error: unknown): string {
|
||||
const errorPayload =
|
||||
typeof error === 'object' && error !== null && 'error' in error
|
||||
? (error as { error?: { errors?: Record<string, string[]>; message?: string } }).error
|
||||
: undefined;
|
||||
const apiErrors = errorPayload?.errors;
|
||||
|
||||
if (apiErrors && typeof apiErrors === 'object') {
|
||||
for (const field of ['nombre_apellido', 'email', 'password'] as const) {
|
||||
const messages = apiErrors[field];
|
||||
|
||||
if (Array.isArray(messages) && typeof messages[0] === 'string' && messages[0].trim()) {
|
||||
return messages[0];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (typeof errorPayload?.message === 'string' && errorPayload.message.trim()) {
|
||||
return errorPayload.message;
|
||||
}
|
||||
|
||||
return 'No se pudo crear la cuenta. Intenta nuevamente.';
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,6 +2,7 @@ import { Routes } from '@angular/router';
|
||||
|
||||
import { AuthLayoutComponent } from '../../core/layout/auth-layout/auth-layout.component';
|
||||
import { StoreLayoutComponent } from '../../core/layout/store-layout/store-layout.component';
|
||||
import { guestOnlyGuard } from '../../core/services/auth/auth.guards';
|
||||
import { LoginPageComponent } from './pages/login-page/login-page.component';
|
||||
import { RegisterPageComponent } from './pages/register-page/register-page.component';
|
||||
import { StoreHomePageComponent } from './pages/store-home-page/store-home-page.component';
|
||||
@@ -17,6 +18,7 @@ export const routes: Routes = [
|
||||
},
|
||||
{
|
||||
path: 'login',
|
||||
canActivate: [guestOnlyGuard],
|
||||
component: AuthLayoutComponent,
|
||||
children: [
|
||||
{
|
||||
@@ -27,6 +29,7 @@ export const routes: Routes = [
|
||||
},
|
||||
{
|
||||
path: 'register',
|
||||
canActivate: [guestOnlyGuard],
|
||||
component: AuthLayoutComponent,
|
||||
children: [
|
||||
{
|
||||
|
||||
Reference in New Issue
Block a user