Compare commits

..

2 Commits

Author SHA1 Message Date
Angel Capetillo Zavala a370f307b5 feat(auth): implementar flujo de login y acceso en WebApp 2026-09-29 10:23:09 -06:00
Roberto Treviño Cervantes 3605d23fc0 initial commit 2026-09-21 10:23:37 -06:00
58 changed files with 3903 additions and 3002 deletions
+4 -3
View File
@@ -1,3 +1,4 @@
node_modules
dist
.angular
node_modules/
dist/
.angular/
.git/
+4
View File
@@ -0,0 +1,4 @@
{
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=827846
"recommendations": ["angular.ng-template"]
}
+20
View File
@@ -0,0 +1,20 @@
{
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0",
"configurations": [
{
"name": "ng serve",
"type": "chrome",
"request": "launch",
"preLaunchTask": "npm: start",
"url": "http://localhost:4200/"
},
{
"name": "ng test",
"type": "chrome",
"request": "launch",
"preLaunchTask": "npm: test",
"url": "http://localhost:9876/debug.html"
}
]
}
+42
View File
@@ -0,0 +1,42 @@
{
// For more information, visit: https://go.microsoft.com/fwlink/?LinkId=733558
"version": "2.0.0",
"tasks": [
{
"type": "npm",
"script": "start",
"isBackground": true,
"problemMatcher": {
"owner": "typescript",
"pattern": "$tsc",
"background": {
"activeOnStart": true,
"beginsPattern": {
"regexp": "Changes detected"
},
"endsPattern": {
"regexp": "bundle generation (complete|failed)"
}
}
}
},
{
"type": "npm",
"script": "test",
"isBackground": true,
"problemMatcher": {
"owner": "typescript",
"pattern": "$tsc",
"background": {
"activeOnStart": true,
"beginsPattern": {
"regexp": "Changes detected"
},
"endsPattern": {
"regexp": "bundle generation (complete|failed)"
}
}
}
}
]
}
+9 -9
View File
@@ -1,10 +1,10 @@
FROM node:24-alpine AS build
WORKDIR /app
COPY package.json package-lock.json ./
RUN npm ci
COPY . .
RUN npx ng build
FROM node:22-slim
FROM nginx:1.29-alpine
COPY nginx.conf /etc/nginx/conf.d/default.conf
COPY --from=build /app/dist/webapp/browser /usr/share/nginx/html
WORKDIR /app
COPY package.json package-lock.json* ./
RUN npm install
COPY . .
EXPOSE 4200
CMD ["npx", "ng", "serve", "--host", "0.0.0.0", "--port", "4200", "--proxy-config", "proxy.docker.json"]
+59
View File
@@ -0,0 +1,59 @@
# WebApp
This project was generated using [Angular CLI](https://github.com/angular/angular-cli) version 22.1.8.
## Development server
To start a local development server, run:
```bash
ng serve
```
Once the server is running, open your browser and navigate to `http://localhost:4200/`. The application will automatically reload whenever you modify any of the source files.
## Code scaffolding
Angular CLI includes powerful code scaffolding tools. To generate a new component, run:
```bash
ng generate component component-name
```
For a complete list of available schematics (such as `components`, `directives`, or `pipes`), run:
```bash
ng generate --help
```
## Building
To build the project run:
```bash
ng build
```
This will compile your project and store the build artifacts in the `dist/` directory. By default, the production build optimizes your application for performance and speed.
## Running unit tests
To execute unit tests with the [Vitest](https://vitest.dev/) test runner, use the following command:
```bash
ng test
```
## Running end-to-end tests
For end-to-end (e2e) testing, run:
```bash
ng e2e
```
Angular CLI does not come with an end-to-end testing framework by default. You can choose one that suits your needs.
## Additional Resources
For more information on using the Angular CLI, including detailed command references, visit the [Angular CLI Overview and Command Reference](https://angular.dev/tools/cli) page.
+9 -4
View File
@@ -6,7 +6,7 @@
},
"newProjectRoot": "projects",
"projects": {
"webapp": {
"WebApp": {
"projectType": "application",
"schematics": {
"@schematics/angular:component": {
@@ -29,7 +29,9 @@
"input": "public"
}
],
"styles": ["src/styles.scss"]
"styles": [
"src/styles.scss"
]
},
"configurations": {
"production": {
@@ -57,12 +59,15 @@
},
"serve": {
"builder": "@angular/build:dev-server",
"options": {
"proxyConfig": "proxy.local.json"
},
"configurations": {
"production": {
"buildTarget": "webapp:build:production"
"buildTarget": "WebApp:build:production"
},
"development": {
"buildTarget": "webapp:build:development"
"buildTarget": "WebApp:build:development"
}
},
"defaultConfiguration": "development"
-6
View File
@@ -1,6 +0,0 @@
{
"$schema": "node_modules/ng-openapi-gen/ng-openapi-gen-schema.json",
"input": "openapi.json",
"output": "src/app/api",
"ignoreUnusedModels": false
}
-11
View File
@@ -1,11 +0,0 @@
server {
listen 80;
root /usr/share/nginx/html;
location /api/ {
proxy_pass http://api:8000/;
proxy_read_timeout 30s;
}
location / {
try_files $uri $uri/ /index.html;
}
}
-162
View File
@@ -1,162 +0,0 @@
{
"components": {
"schemas": {
"Domain": {
"enum": [
"cacu",
"cama",
"tea"
],
"title": "Domain",
"type": "string"
},
"HTTPValidationError": {
"properties": {
"detail": {
"items": {
"$ref": "#/components/schemas/ValidationError"
},
"title": "Detail",
"type": "array"
}
},
"title": "HTTPValidationError",
"type": "object"
},
"ValidationError": {
"properties": {
"ctx": {
"title": "Context",
"type": "object"
},
"input": {
"title": "Input"
},
"loc": {
"items": {
"anyOf": [
{
"type": "string"
},
{
"type": "integer"
}
]
},
"title": "Location",
"type": "array"
},
"msg": {
"title": "Message",
"type": "string"
},
"type": {
"title": "Error Type",
"type": "string"
}
},
"required": [
"loc",
"msg",
"type"
],
"title": "ValidationError",
"type": "object"
}
}
},
"info": {
"title": "ISSSTELEON",
"version": "0.0.0"
},
"openapi": "3.1.0",
"paths": {
"/domains": {
"get": {
"operationId": "domains",
"responses": {
"200": {
"content": {
"application/json": {
"schema": {
"items": {
"$ref": "#/components/schemas/Domain"
},
"title": "Response Domains",
"type": "array"
}
}
},
"description": "Successful Response"
}
},
"summary": "Domains"
}
},
"/health": {
"get": {
"operationId": "health",
"responses": {
"200": {
"content": {
"application/json": {
"schema": {
"additionalProperties": {
"type": "string"
},
"title": "Response Health",
"type": "object"
}
}
},
"description": "Successful Response"
}
},
"summary": "Health"
}
},
"/runs/{run_id}": {
"get": {
"operationId": "run_status",
"parameters": [
{
"in": "path",
"name": "run_id",
"required": true,
"schema": {
"title": "Run Id",
"type": "string"
}
}
],
"responses": {
"200": {
"content": {
"application/json": {
"schema": {
"additionalProperties": {
"type": "string"
},
"title": "Response Run Status",
"type": "object"
}
}
},
"description": "Successful Response"
},
"422": {
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/HTTPValidationError"
}
}
},
"description": "Validation Error"
}
},
"summary": "Run Status"
}
}
}
}
+2711 -2095
View File
File diff suppressed because it is too large Load Diff
+17 -20
View File
@@ -1,37 +1,34 @@
{
"name": "webapp",
"name": "web-app",
"version": "0.0.0",
"scripts": {
"ng": "ng",
"start": "ng serve --proxy-config proxy.conf.json",
"start": "ng serve",
"build": "ng build",
"watch": "ng build --watch --configuration development",
"test": "ng test",
"api": "ng-openapi-gen -c ng-openapi-gen.json"
"test": "ng test"
},
"private": true,
"packageManager": "npm@11.20.0",
"packageManager": "npm@11.17.0",
"dependencies": {
"@angular/cdk": "^22.3.0",
"@angular/common": "^22.3.0",
"@angular/compiler": "^22.3.0",
"@angular/core": "^22.3.0",
"@angular/forms": "^22.3.0",
"@angular/material": "^22.3.0",
"@angular/platform-browser": "^22.3.0",
"@angular/router": "^22.3.0",
"plotly.js-cartesian-dist-min": "4.1.2",
"@angular/cdk": "^22.1.7",
"@angular/common": "^22.1.0",
"@angular/compiler": "^22.1.0",
"@angular/core": "^22.1.0",
"@angular/forms": "^22.1.0",
"@angular/material": "^22.1.7",
"@angular/platform-browser": "^22.1.0",
"@angular/router": "^22.1.0",
"rxjs": "~7.8.0",
"tslib": "^2.3.0"
},
"devDependencies": {
"@angular/build": "^22.3.0",
"@angular/cli": "^22.3.0",
"@angular/compiler-cli": "^22.3.0",
"jsdom": "^31.0.0",
"ng-openapi-gen": "^1.1.0",
"@angular/build": "^22.1.8",
"@angular/cli": "^22.1.8",
"@angular/compiler-cli": "^22.1.0",
"jsdom": "^28.0.0",
"prettier": "^3.8.1",
"typescript": "~6.0.2",
"vitest": "^5.0.0"
"vitest": "^4.0.8"
}
}
-1
View File
@@ -1 +0,0 @@
{ "/api": { "target": "http://127.0.0.1:5711", "pathRewrite": { "^/api": "" } } }
+5
View File
@@ -0,0 +1,5 @@
{
"/auth/**": {
"target": "http://webapi:5000"
}
}
+5
View File
@@ -0,0 +1,5 @@
{
"/auth/**": {
"target": "http://127.0.0.1:5000"
}
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 13 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 17 KiB

-27
View File
@@ -1,27 +0,0 @@
/* eslint-disable */
/* Code generated by ng-openapi-gen DO NOT EDIT. */
import { Injectable } from '@angular/core';
/**
* Provides the ApiConfiguration configuration object with a given root URL.
*/
export function provideApiConfiguration(rootUrl: string) {
var config = new ApiConfiguration();
config.rootUrl = rootUrl;
return {
provide: ApiConfiguration,
useValue: config
};
}
/**
* Global configuration
*/
@Injectable({
providedIn: 'root',
})
export class ApiConfiguration {
rootUrl: string = '';
}
-64
View File
@@ -1,64 +0,0 @@
/* eslint-disable */
/* Code generated by ng-openapi-gen DO NOT EDIT. */
import { Injectable } from '@angular/core';
import { HttpClient, HttpContext, HttpResponse } from '@angular/common/http';
import { Observable, firstValueFrom } from 'rxjs';
import { filter, map } from 'rxjs/operators';
import { ApiConfiguration } from './api-configuration';
import { StrictHttpResponse } from './strict-http-response';
export type ApiFnOptional<P, R> = (http: HttpClient, rootUrl: string, params?: P, context?: HttpContext) => Observable<StrictHttpResponse<R>>;
export type ApiFnRequired<P, R> = (http: HttpClient, rootUrl: string, params: P, context?: HttpContext) => Observable<StrictHttpResponse<R>>;
/**
* Helper service to call API functions directly
*/
@Injectable({ providedIn: 'root' })
export class Api {
constructor(
private config: ApiConfiguration,
private http: HttpClient
) {
}
private _rootUrl?: string;
/**
* Returns the root url for API operations. If not set directly here,
* will fallback to `ApiConfiguration.rootUrl`.
*/
get rootUrl(): string {
return this._rootUrl || this.config.rootUrl;
}
/**
* Sets the root URL for API operations
*/
set rootUrl(rootUrl: string) {
this._rootUrl = rootUrl;
}
/**
* Executes an API call, returning the response body only
*/
invoke<P, R>(fn: ApiFnRequired<P, R>, params: P, context?: HttpContext): Promise<R>;
invoke<P, R>(fn: ApiFnOptional<P, R>, params?: P, context?: HttpContext): Promise<R>;
async invoke<P, R>(fn: ApiFnRequired<P, R> | ApiFnOptional<P, R>, params: P, context?: HttpContext): Promise<R> {
const resp = this.invoke$Response(fn, params, context);
return (await resp).body;
}
/**
* Executes an API call, returning the entire response
*/
invoke$Response<P, R>(fn: ApiFnRequired<P, R>, params: P, context?: HttpContext): Promise<StrictHttpResponse<R>>;
invoke$Response<P, R>(fn: ApiFnOptional<P, R>, params?: P, context?: HttpContext): Promise<StrictHttpResponse<R>>;
invoke$Response<P, R>(fn: ApiFnRequired<P, R> | ApiFnOptional<P, R>, params: P, context?: HttpContext): Promise<StrictHttpResponse<R>> {
const obs = fn(this.http, this.rootUrl, params, context)
.pipe(
filter(r => r instanceof HttpResponse),
map(r => r as StrictHttpResponse<R>));
return firstValueFrom(obs);
}
}
-30
View File
@@ -1,30 +0,0 @@
/* eslint-disable */
/* Code generated by ng-openapi-gen DO NOT EDIT. */
import { HttpClient, HttpContext, HttpResponse } from '@angular/common/http';
import { Observable } from 'rxjs';
import { filter, map } from 'rxjs/operators';
import { StrictHttpResponse } from '../../strict-http-response';
import { RequestBuilder } from '../../request-builder';
import { Domain } from '../../models/domain';
export interface Domains$Params {
}
export function domains(http: HttpClient, rootUrl: string, params?: Domains$Params, context?: HttpContext): Observable<StrictHttpResponse<Array<Domain>>> {
const rb = new RequestBuilder(rootUrl, domains.PATH, 'get');
if (params) {
}
return http.request(
rb.build({ responseType: 'json', accept: 'application/json', context })
).pipe(
filter((r: any): r is HttpResponse<any> => r instanceof HttpResponse),
map((r: HttpResponse<any>) => {
return r as StrictHttpResponse<Array<Domain>>;
})
);
}
domains.PATH = '/domains';
-33
View File
@@ -1,33 +0,0 @@
/* eslint-disable */
/* Code generated by ng-openapi-gen DO NOT EDIT. */
import { HttpClient, HttpContext, HttpResponse } from '@angular/common/http';
import { Observable } from 'rxjs';
import { filter, map } from 'rxjs/operators';
import { StrictHttpResponse } from '../../strict-http-response';
import { RequestBuilder } from '../../request-builder';
export interface Health$Params {
}
export function health(http: HttpClient, rootUrl: string, params?: Health$Params, context?: HttpContext): Observable<StrictHttpResponse<{
[key: string]: string;
}>> {
const rb = new RequestBuilder(rootUrl, health.PATH, 'get');
if (params) {
}
return http.request(
rb.build({ responseType: 'json', accept: 'application/json', context })
).pipe(
filter((r: any): r is HttpResponse<any> => r instanceof HttpResponse),
map((r: HttpResponse<any>) => {
return r as StrictHttpResponse<{
[key: string]: string;
}>;
})
);
}
health.PATH = '/health';
-35
View File
@@ -1,35 +0,0 @@
/* eslint-disable */
/* Code generated by ng-openapi-gen DO NOT EDIT. */
import { HttpClient, HttpContext, HttpResponse } from '@angular/common/http';
import { Observable } from 'rxjs';
import { filter, map } from 'rxjs/operators';
import { StrictHttpResponse } from '../../strict-http-response';
import { RequestBuilder } from '../../request-builder';
export interface RunStatus$Params {
run_id: string;
}
export function runStatus(http: HttpClient, rootUrl: string, params: RunStatus$Params, context?: HttpContext): Observable<StrictHttpResponse<{
[key: string]: string;
}>> {
const rb = new RequestBuilder(rootUrl, runStatus.PATH, 'get');
if (params) {
rb.path('run_id', params.run_id, {});
}
return http.request(
rb.build({ responseType: 'json', accept: 'application/json', context })
).pipe(
filter((r: any): r is HttpResponse<any> => r instanceof HttpResponse),
map((r: HttpResponse<any>) => {
return r as StrictHttpResponse<{
[key: string]: string;
}>;
})
);
}
runStatus.PATH = '/runs/{run_id}';
-9
View File
@@ -1,9 +0,0 @@
/* eslint-disable */
/* Code generated by ng-openapi-gen DO NOT EDIT. */
export type { Domains$Params as Domains$Params } from './fn/operations/domains';
export { domains as domains } from './fn/operations/domains';
export type { Health$Params as Health$Params } from './fn/operations/health';
export { health as health } from './fn/operations/health';
export type { RunStatus$Params as RunStatus$Params } from './fn/operations/run-status';
export { runStatus as runStatus } from './fn/operations/run-status';
-6
View File
@@ -1,6 +0,0 @@
/* eslint-disable */
/* Code generated by ng-openapi-gen DO NOT EDIT. */
export type { Domain } from './models/domain';
export type { HttpValidationError } from './models/http-validation-error';
export type { ValidationError } from './models/validation-error';
-13
View File
@@ -1,13 +0,0 @@
/* eslint-disable */
/* Code generated by ng-openapi-gen DO NOT EDIT. */
import { Domain } from './domain';
/**
* Each possible value of `Domain`
*/
export const DOMAIN: Domain[] = [
'cacu',
'cama',
'tea'
];
-5
View File
@@ -1,5 +0,0 @@
/* eslint-disable */
/* Code generated by ng-openapi-gen DO NOT EDIT. */
export type Domain = 'cacu' | 'cama' | 'tea';
@@ -1,7 +0,0 @@
/* eslint-disable */
/* Code generated by ng-openapi-gen DO NOT EDIT. */
import { ValidationError } from '../models/validation-error';
export interface HttpValidationError {
detail?: Array<ValidationError>;
}
-11
View File
@@ -1,11 +0,0 @@
/* eslint-disable */
/* Code generated by ng-openapi-gen DO NOT EDIT. */
export interface ValidationError {
ctx?: {
};
input?: any;
loc: Array<(string | number)>;
msg: string;
type: string;
}
-369
View File
@@ -1,369 +0,0 @@
/* eslint-disable */
/* Code generated by ng-openapi-gen DO NOT EDIT. */
import { HttpRequest, HttpParameterCodec, HttpParams, HttpHeaders, HttpContext } from '@angular/common/http';
/**
* Custom parameter codec to correctly handle the plus sign in parameter
* values. See https://github.com/angular/angular/issues/18261
*/
class ParameterCodec implements HttpParameterCodec {
encodeKey(key: string): string {
return encodeURIComponent(key);
}
encodeValue(value: string): string {
return encodeURIComponent(value);
}
decodeKey(key: string): string {
return decodeURIComponent(key);
}
decodeValue(value: string): string {
return decodeURIComponent(value);
}
}
const ParameterCodecInstance = new ParameterCodec();
/**
* Defines the options for appending a parameter
*/
interface ParameterOptions {
style?: string;
explode?: boolean;
}
/**
* Base class for a parameter
*/
abstract class Parameter {
constructor(public name: string, public value: any, public options: ParameterOptions, defaultStyle: string, defaultExplode: boolean) {
this.options = options || {};
if (this.options.style === null || this.options.style === undefined) {
this.options.style = defaultStyle;
}
if (this.options.explode === null || this.options.explode === undefined) {
this.options.explode = defaultExplode;
}
}
serializeValue(value: any, separator = ','): string {
if (value === null || value === undefined) {
return '';
} else if (value instanceof Array) {
return value.map(v => this.serializeValue(v).split(separator).join(encodeURIComponent(separator))).join(separator);
} else if (typeof value === 'object') {
const array: string[] = [];
for (const key of Object.keys(value)) {
let propVal = value[key];
if (propVal !== null && propVal !== undefined) {
propVal = this.serializeValue(propVal).split(separator).join(encodeURIComponent(separator));
if (this.options.explode) {
array.push(`${key}=${propVal}`);
} else {
array.push(key);
array.push(propVal);
}
}
}
return array.join(separator);
} else {
return String(value);
}
}
}
/**
* A parameter in the operation path
*/
class PathParameter extends Parameter {
constructor(name: string, value: any, options: ParameterOptions) {
super(name, value, options, 'simple', false);
}
append(path: string): string {
let value = this.value;
if (value === null || value === undefined) {
value = '';
}
let prefix = this.options.style === 'label' ? '.' : '';
let separator = this.options.explode ? prefix === '' ? ',' : prefix : ',';
let alreadySerialized = false;
if (this.options.style === 'matrix') {
// The parameter name is just used as prefix, except in some cases...
prefix = `;${this.name}=`;
if (this.options.explode && typeof value === 'object') {
prefix = ';';
if (value instanceof Array) {
// For arrays we have to repeat the name for each element
value = value.map(v => `${this.name}=${this.serializeValue(v, ';')}`);
value = value.join(';');
alreadySerialized = true;
} else {
// For objects we have to put each the key / value pairs
value = this.serializeValue(value, ';');
alreadySerialized = true
}
}
}
value = prefix + (alreadySerialized ? value : this.serializeValue(value, separator));
// Replace both the plain variable and the corresponding variant taking in the prefix and explode into account
path = path.replace(`{${this.name}}`, value);
path = path.replace(`{${prefix}${this.name}${this.options.explode ? '*' : ''}}`, value);
return path;
}
// @ts-ignore
serializeValue(value: any, separator = ','): string {
var result = typeof value === 'string' ? encodeURIComponent(value) : super.serializeValue(value, separator);
result = result.replace(/%3D/g, '=');
result = result.replace(/%3B/g, ';');
result = result.replace(/%2C/g, ',');
return result;
}
}
/**
* A parameter in the query
*/
class QueryParameter extends Parameter {
constructor(name: string, value: any, options: ParameterOptions) {
super(name, value, options, 'form', true);
}
append(params: HttpParams): HttpParams {
if (this.value instanceof Array) {
// Array serialization
if (this.options.explode) {
for (const v of this.value) {
params = params.append(this.name, this.serializeValue(v));
}
} else {
const separator = this.options.style === 'spaceDelimited'
? ' ' : this.options.style === 'pipeDelimited'
? '|' : ',';
return params.append(this.name, this.serializeValue(this.value, separator));
}
} else if (this.value !== null && typeof this.value === 'object') {
// Object serialization
if (this.options.style === 'deepObject') {
// Append a parameter for each key, in the form `name[key]`
for (const key of Object.keys(this.value)) {
const propVal = this.value[key];
if (propVal !== null && propVal !== undefined) {
params = params.append(`${this.name}[${key}]`, this.serializeValue(propVal));
}
}
} else if (this.options.explode) {
// Append a parameter for each key without using the parameter name
for (const key of Object.keys(this.value)) {
const propVal = this.value[key];
if (propVal !== null && propVal !== undefined) {
params = params.append(key, this.serializeValue(propVal));
}
}
} else {
// Append a single parameter whose values are a comma-separated list of key,value,key,value...
const array: any[] = [];
for (const key of Object.keys(this.value)) {
const propVal = this.value[key];
if (propVal !== null && propVal !== undefined) {
array.push(key);
array.push(propVal);
}
}
params = params.append(this.name, this.serializeValue(array));
}
} else if (this.value !== null && this.value !== undefined) {
// Plain value
params = params.append(this.name, this.serializeValue(this.value));
}
return params;
}
}
/**
* A parameter in the HTTP request header
*/
class HeaderParameter extends Parameter {
constructor(name: string, value: any, options: ParameterOptions) {
super(name, value, options, 'simple', false);
}
append(headers: HttpHeaders): HttpHeaders {
if (this.value !== null && this.value !== undefined) {
if (this.value instanceof Array) {
for (const v of this.value) {
headers = headers.append(this.name, this.serializeValue(v));
}
} else {
headers = headers.append(this.name, this.serializeValue(this.value));
}
}
return headers;
}
}
/**
* Helper to build http requests from parameters
*/
export class RequestBuilder {
private _path = new Map<string, PathParameter>();
private _query = new Map<string, QueryParameter>();
private _header = new Map<string, HeaderParameter>();
_bodyContent: any | null;
_bodyContentType?: string;
constructor(
public rootUrl: string,
public operationPath: string,
public method: string) {
}
/**
* Sets a path parameter
*/
path(name: string, value: any, options?: ParameterOptions): void {
this._path.set(name, new PathParameter(name, value, options || {}));
}
/**
* Sets a query parameter
*/
query(name: string, value: any, options?: ParameterOptions): void {
this._query.set(name, new QueryParameter(name, value, options || {}));
}
/**
* Sets a header parameter
*/
header(name: string, value: any, options?: ParameterOptions): void {
this._header.set(name, new HeaderParameter(name, value, options || {}));
}
/**
* Sets the body content, along with the content type
*/
body(value: any, contentType = 'application/json'): void {
if (value instanceof Blob) {
this._bodyContentType = value.type;
} else {
this._bodyContentType = contentType;
}
if (this._bodyContentType === 'application/x-www-form-urlencoded' && value !== null && typeof value === 'object') {
// Handle URL-encoded data
const pairs: Array<[string, string]> = [];
for (const key of Object.keys(value)) {
let val = value[key];
if (!(val instanceof Array)) {
val = [val];
}
for (const v of val) {
const formValue = this.formDataValue(v);
if (formValue !== null) {
pairs.push([key, formValue]);
}
}
}
this._bodyContent = pairs.map(p => `${encodeURIComponent(p[0])}=${encodeURIComponent(p[1])}`).join('&');
} else if (this._bodyContentType === 'multipart/form-data') {
// Handle multipart form data
const formData = new FormData();
if (value !== null && value !== undefined) {
for (const key of Object.keys(value)) {
const val = value[key];
if (val instanceof Array) {
for (const v of val) {
const toAppend = this.formDataValue(v);
if (toAppend !== null) {
formData.append(key, toAppend);
}
}
} else {
const toAppend = this.formDataValue(val);
if (toAppend !== null) {
formData.set(key, toAppend);
}
}
}
}
this._bodyContent = formData;
} else {
// The body is the plain content
this._bodyContent = value;
}
}
private formDataValue(value: any): any {
if (value === null || value === undefined) {
return null;
}
if (value instanceof Blob) {
return value;
}
if (typeof value === 'object') {
return new Blob([JSON.stringify(value)], {type: 'application/json'})
}
return String(value);
}
/**
* Builds the request with the current set parameters
*/
build<T = any>(options?: {
/** Which content types to accept */
accept?: string;
/** The expected response type */
responseType?: 'json' | 'text' | 'blob' | 'arraybuffer';
/** Whether to report progress on uploads / downloads */
reportProgress?: boolean;
/** Allow passing HttpContext for HttpClient */
context?: HttpContext;
}): HttpRequest<T> {
options = options || {};
// Path parameters
let path = this.operationPath;
for (const pathParam of this._path.values()) {
path = pathParam.append(path);
}
const url = this.rootUrl + path;
// Query parameters
let httpParams = new HttpParams({
encoder: ParameterCodecInstance
});
for (const queryParam of this._query.values()) {
httpParams = queryParam.append(httpParams);
}
// Header parameters
let httpHeaders = new HttpHeaders();
if (options.accept) {
httpHeaders = httpHeaders.append('Accept', options.accept);
}
for (const headerParam of this._header.values()) {
httpHeaders = headerParam.append(httpHeaders);
}
// Request content headers
if (this._bodyContentType && !(this._bodyContent instanceof FormData)) {
httpHeaders = httpHeaders.set('Content-Type', this._bodyContentType);
}
// Perform the request
return new HttpRequest<T>(this.method.toUpperCase(), url, this._bodyContent, {
params: httpParams,
headers: httpHeaders,
responseType: options.responseType,
reportProgress: options.reportProgress,
context: options.context
});
}
}
-11
View File
@@ -1,11 +0,0 @@
/* eslint-disable */
/* Code generated by ng-openapi-gen DO NOT EDIT. */
import { HttpResponse } from '@angular/common/http';
/**
* Constrains the http response to not have the body defined as `T | null`, but `T` only.
*/
export type StrictHttpResponse<T> = HttpResponse<T> & {
readonly body: T;
}
+3 -5
View File
@@ -1,14 +1,12 @@
import { provideHttpClient } from '@angular/common/http';
import { ApplicationConfig, provideBrowserGlobalErrorListeners } from '@angular/core';
import { provideRouter } from '@angular/router';
import { provideApiConfiguration } from './api/api-configuration';
import { provideHttpClient } from '@angular/common/http';
import { routes } from './app.routes';
export const appConfig: ApplicationConfig = {
providers: [
provideBrowserGlobalErrorListeners(),
provideRouter(routes),
provideHttpClient(),
provideApiConfiguration('/api'),
],
provideRouter(routes)
]
};
+9 -15
View File
@@ -1,19 +1,13 @@
<mat-toolbar class="bar">
<span class="brand">ISSSTELEON</span>
<mat-button-toggle-group
aria-label="Dominio"
[value]="domain()"
(change)="domain.set($event.value)"
>
@for (d of domains.value() ?? []; track d) {
<mat-button-toggle [value]="d">{{ labels[d] }}</mat-button-toggle>
}
</mat-button-toggle-group>
@if (auth.isAuthenticated()) {
<mat-toolbar color="primary">
<span>{{ title }}</span>
<span class="spacer"></span>
<span class="status" [class.down]="health.error()">
API {{ health.value()?.['status'] ?? (health.error() ? 'sin conexión' : '…') }}
</span>
<span class="username">{{ auth.user()?.username }}</span>
<button mat-button (click)="auth.logout()">Cerrar sesión</button>
</mat-toolbar>
}
<main>
<router-outlet />
@if (auth.status() === 'checking') { <p role="status">Comprobando sesión…</p> }
<div [hidden]="auth.status() === 'checking'"><router-outlet /></div>
</main>
+12 -1
View File
@@ -1,3 +1,14 @@
import { Routes } from '@angular/router';
import { authGuard, anonymousGuard, areaGuard } from './auth/auth.guard';
import { AreaPlaceholder } from './auth/area-placeholder';
import { Home } from './auth/home';
import { Login } from './auth/login';
export const routes: Routes = [];
export const routes: Routes = [
{ path: 'login', component: Login, canActivate: [anonymousGuard] },
{ path: '', pathMatch: 'full', component: Home, canActivate: [authGuard] },
{ path: 'cacu', component: AreaPlaceholder, data: { area: 'CACU' }, canActivate: [areaGuard('CACU')] },
{ path: 'cama', component: AreaPlaceholder, data: { area: 'CAMA' }, canActivate: [areaGuard('CAMA')] },
{ path: 'tea', component: AreaPlaceholder, data: { area: 'TEA' }, canActivate: [areaGuard('TEA')] },
{ path: '**', redirectTo: '' },
];
+3 -17
View File
@@ -1,19 +1,5 @@
.bar {
gap: 16px;
}
.brand {
font-weight: 500;
}
.spacer {
flex: 1;
}
.status {
font-size: 14px;
opacity: 0.8;
}
.status.down {
color: var(--mat-sys-error);
}
main {
padding: 16px;
padding: 1.5rem;
}
.spacer { flex: 1; }
.username { font-size: .875rem; margin-right: .5rem; overflow: hidden; text-overflow: ellipsis; }
+48 -6
View File
@@ -1,14 +1,56 @@
import { provideHttpClient } from '@angular/common/http';
import { provideHttpClientTesting } from '@angular/common/http/testing';
import { signal } from '@angular/core';
import { TestBed } from '@angular/core/testing';
import { provideRouter } from '@angular/router';
import { vi } from 'vitest';
import { App } from './app';
import { AuthState } from './auth/auth.state';
import { routes } from './app.routes';
import { authGuard, anonymousGuard } from './auth/auth.guard';
describe('App', () => {
it('creates the shell', async () => {
const status = signal('anonymous');
const user = signal({ id: 1, username: 'demo', roles: ['CAMA'] });
const logout = vi.fn();
beforeEach(async () => {
status.set('anonymous'); logout.mockClear();
await TestBed.configureTestingModule({
imports: [App],
providers: [provideHttpClient(), provideHttpClientTesting()],
}).compileComponents();
expect(TestBed.createComponent(App).componentInstance).toBeTruthy();
providers: [provideRouter([]), { provide: AuthState, useValue: {
status, user, isAuthenticated: () => status() === 'authenticated', logout,
} }],
})
.compileComponents();
});
it('should create the app', () => {
const fixture = TestBed.createComponent(App);
const app = fixture.componentInstance;
expect(app).toBeTruthy();
});
it('should render the toolbar title', async () => {
status.set('authenticated');
const fixture = TestBed.createComponent(App);
await fixture.whenStable();
fixture.detectChanges();
const compiled = fixture.nativeElement as HTMLElement;
expect(compiled.querySelector('mat-toolbar')?.textContent).toContain('ISSSTELEON');
});
it('hides shell for anonymous and checking', () => {
const fixture = TestBed.createComponent(App); fixture.detectChanges();
expect(fixture.nativeElement.querySelector('mat-toolbar')).toBeNull();
status.set('checking'); fixture.detectChanges();
expect(fixture.nativeElement.querySelector('mat-toolbar')).toBeNull();
expect(fixture.nativeElement.querySelector('router-outlet').parentElement.hidden).toBe(true);
});
it('invokes local logout from shell', () => {
status.set('authenticated'); const fixture = TestBed.createComponent(App); fixture.detectChanges();
fixture.nativeElement.querySelector('button').click(); expect(logout).toHaveBeenCalledOnce();
});
it('preserves login, protected home and wildcard alongside area routes', () => {
expect(routes.map(route => route.path)).toEqual(['login', '', 'cacu', 'cama', 'tea', '**']);
expect(routes[0].canActivate).toEqual([anonymousGuard]);
expect(routes[1].canActivate).toEqual([authGuard]);
expect(routes.at(-1)?.redirectTo).toBe('');
});
});
+8 -16
View File
@@ -1,24 +1,16 @@
import { Component, inject, resource, signal } from '@angular/core';
import { MatButtonToggleModule } from '@angular/material/button-toggle';
import { MatToolbarModule } from '@angular/material/toolbar';
import { Component, inject } from '@angular/core';
import { RouterOutlet } from '@angular/router';
import { Api } from './api/api';
import { domains } from './api/fn/operations/domains';
import { health } from './api/fn/operations/health';
import { Domain } from './api/models/domain';
const LABELS: Record<Domain, string> = { cacu: 'CaCu', cama: 'CaMa', tea: 'TEA' };
import { MatToolbarModule } from '@angular/material/toolbar';
import { MatButtonModule } from '@angular/material/button';
import { AuthState } from './auth/auth.state';
@Component({
imports: [RouterOutlet, MatToolbarModule, MatButtonModule],
selector: 'app-root',
imports: [RouterOutlet, MatToolbarModule, MatButtonToggleModule],
templateUrl: './app.html',
styleUrl: './app.scss',
templateUrl: './app.html',
})
export class App {
private readonly api = inject(Api);
protected readonly labels = LABELS;
protected readonly domain = signal<Domain>('cacu');
protected readonly domains = resource({ loader: () => this.api.invoke(domains) });
protected readonly health = resource({ loader: () => this.api.invoke(health) });
protected readonly auth = inject(AuthState);
protected readonly title = 'ISSSTELEON';
}
+13
View File
@@ -0,0 +1,13 @@
import { Component, inject } from '@angular/core';
import { ActivatedRoute, RouterLink } from '@angular/router';
import { MatButtonModule } from '@angular/material/button';
import { Area } from './auth.roles';
@Component({
selector: 'app-area-placeholder',
imports: [RouterLink, MatButtonModule],
template: `<h1>Área {{ area }}</h1><a mat-button routerLink="/">Volver a áreas</a>`,
})
export class AreaPlaceholder {
protected readonly area: Area = inject(ActivatedRoute).snapshot.data['area'];
}
+94
View File
@@ -0,0 +1,94 @@
import { TestBed } from '@angular/core/testing';
import { provideHttpClient } from '@angular/common/http';
import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing';
import { ActivatedRouteSnapshot, Router, RouterStateSnapshot, provideRouter } from '@angular/router';
import { authGuard, anonymousGuard, areaGuard } from './auth.guard';
import { Role } from './auth.models';
import { Area } from './auth.roles';
import { routes } from '../app.routes';
import { AuthState } from './auth.state';
describe('Auth guards', () => {
let http: HttpTestingController;
const user = { id: 1, username: 'demo', roles: ['CAMA'] };
beforeEach(() => {
sessionStorage.clear();
TestBed.configureTestingModule({ providers: [provideHttpClient(), provideHttpClientTesting(), provideRouter([])] });
http = TestBed.inject(HttpTestingController);
});
afterEach(() => { http.verify(); sessionStorage.clear(); });
const run = (guard: typeof authGuard) => TestBed.runInInjectionContext(() =>
guard({} as ActivatedRouteSnapshot, {} as RouterStateSnapshot));
const url = (result: unknown) => TestBed.inject(Router).serializeUrl(result as ReturnType<Router['createUrlTree']>);
it('anonymous redirects protected route to login', async () => {
expect(url(await run(authGuard))).toBe('/login');
});
it('anonymous can open login', async () => { expect(await run(anonymousGuard)).toBe(true); });
it('authenticated allows home and redirects login', async () => {
const login = TestBed.inject(AuthState).login('demo', 'test-password');
http.expectOne('/auth/login').flush({ token: 'test-token', expires_in: 28800, user }); await login;
expect(await run(authGuard)).toBe(true); expect(url(await run(anonymousGuard))).toBe('/');
});
it('both guards wait on the same restore', async () => {
sessionStorage.setItem('ISSSTELEON.auth.token', 'test-token');
let resolved = false;
const home = Promise.resolve(run(authGuard)).then(result => { resolved = true; return result; });
const login = run(anonymousGuard);
await Promise.resolve(); expect(resolved).toBe(false);
expect(TestBed.inject(AuthState).status()).toBe('checking');
http.expectOne('/auth/me').flush({ user });
expect(await home).toBe(true); expect(url(await login)).toBe('/');
});
it('rejected restore redirects home and allows login', async () => {
sessionStorage.setItem('ISSSTELEON.auth.token', 'test-token');
const home = run(authGuard); const login = run(anonymousGuard);
http.expectOne('/auth/me').flush({}, { status: 401, statusText: 'Unauthorized' });
expect(url(await home)).toBe('/login'); expect(await login).toBe(true);
});
it('anonymous is redirected to login for every area', async () => {
for (const area of ['CACU', 'CAMA', 'TEA'] as const) {
expect(url(await run(areaGuard(area)))).toBe('/login');
}
});
const cases: [Role[], Area[]][] = [
[['CAMA'], ['CAMA']], [['CACU', 'CAMA'], ['CACU', 'CAMA']],
[['ADMIN'], ['CACU', 'CAMA', 'TEA']], [[], []],
];
for (const [roles, allowed] of cases) {
it(`evaluates area guards and configured routes for ${JSON.stringify(roles)}`, async () => {
const login = TestBed.inject(AuthState).login('demo', 'test-password');
http.expectOne('/auth/login').flush({ token: 'test-token', expires_in: 28800, user: { ...user, roles } });
await login;
for (const area of ['CACU', 'CAMA', 'TEA'] as const) {
const result = await run(areaGuard(area));
expect(result === true ? true : url(result)).toBe(allowed.includes(area) ? true : '/');
const route = routes.find(route => route.path === area.toLowerCase())!;
expect(route.data?.['area']).toBe(area);
expect(route.component).toBeDefined();
expect(route.canActivate?.length).toBe(1);
const routed = await run(route.canActivate![0] as typeof authGuard);
expect(routed === true ? true : url(routed)).toBe(allowed.includes(area) ? true : '/');
}
http.expectNone('/auth/me');
expect(TestBed.inject(AuthState).isAuthenticated()).toBe(true);
});
}
it('waits for shared restore and uses server roles instead of cached roles', async () => {
sessionStorage.setItem('ISSSTELEON.auth.token', 'test-token');
sessionStorage.setItem('ISSSTELEON.auth.user', JSON.stringify({ ...user, roles: ['ADMIN'] }));
let resolved = false;
const cama = Promise.resolve(run(areaGuard('CAMA'))).then(result => { resolved = true; return result; });
const cacu = run(areaGuard('CACU')); const home = run(authGuard);
await Promise.resolve(); expect(resolved).toBe(false);
http.expectOne('/auth/me').flush({ user });
expect(await cama).toBe(true); expect(url(await cacu)).toBe('/'); expect(await home).toBe(true);
expect(await run(areaGuard('CAMA'))).toBe(true); http.expectNone('/auth/me');
});
it('rejected restore redirects pending area guards to login', async () => {
sessionStorage.setItem('ISSSTELEON.auth.token', 'test-token');
const cama = run(areaGuard('CAMA')); const tea = run(areaGuard('TEA'));
http.expectOne('/auth/me').flush({}, { status: 401, statusText: 'Unauthorized' });
expect(url(await cama)).toBe('/login'); expect(url(await tea)).toBe('/login');
});
});
+28
View File
@@ -0,0 +1,28 @@
import { inject } from '@angular/core';
import { CanActivateFn, Router } from '@angular/router';
import { AuthState } from './auth.state';
import { Area, canAccessArea } from './auth.roles';
export function areaGuard(area: Area): CanActivateFn {
return async () => {
const auth = inject(AuthState);
const router = inject(Router);
await auth.restore();
if (!auth.isAuthenticated()) return router.createUrlTree(['/login']);
return canAccessArea(auth.user()?.roles ?? [], area) || router.createUrlTree(['/']);
};
}
export const authGuard: CanActivateFn = async () => {
const auth = inject(AuthState);
const router = inject(Router);
await auth.restore();
return auth.isAuthenticated() || router.createUrlTree(['/login']);
};
export const anonymousGuard: CanActivateFn = async () => {
const auth = inject(AuthState);
const router = inject(Router);
await auth.restore();
return !auth.isAuthenticated() || router.createUrlTree(['/']);
};
+17
View File
@@ -0,0 +1,17 @@
export type Role = 'ADMIN' | 'CACU' | 'CAMA' | 'TEA';
export interface AuthUser {
id: number;
username: string;
roles: Role[];
}
export interface LoginResponse {
token: string;
expires_in: number;
user: AuthUser;
}
export interface MeResponse {
user: AuthUser;
}
+30
View File
@@ -0,0 +1,30 @@
import { Role } from './auth.models';
import { Area, canAccessArea, getAccessibleAreas } from './auth.roles';
describe('Area access', () => {
const cases: [Role[], Area[]][] = [
[[], []],
[['CACU'], ['CACU']],
[['CAMA'], ['CAMA']],
[['TEA'], ['TEA']],
[['CACU', 'CAMA'], ['CACU', 'CAMA']],
[['CACU', 'TEA'], ['CACU', 'TEA']],
[['CAMA', 'TEA'], ['CAMA', 'TEA']],
[['CACU', 'CAMA', 'TEA'], ['CACU', 'CAMA', 'TEA']],
[['ADMIN'], ['CACU', 'CAMA', 'TEA']],
[['ADMIN', 'CAMA'], ['CACU', 'CAMA', 'TEA']],
];
for (const [roles, allowed] of cases) {
it(`evaluates all areas and stable list for ${JSON.stringify(roles)}`, () => {
for (const area of ['CACU', 'CAMA', 'TEA'] as const) {
expect(canAccessArea(roles, area)).toBe(allowed.includes(area));
}
expect(getAccessibleAreas(roles)).toEqual(allowed);
});
}
it('keeps canonical order without modifying or duplicating input', () => {
const roles: readonly Role[] = Object.freeze(['TEA', 'CAMA', 'CACU', 'CAMA']);
expect(getAccessibleAreas(roles)).toEqual(['CACU', 'CAMA', 'TEA']);
expect(roles).toEqual(['TEA', 'CAMA', 'CACU', 'CAMA']);
});
});
+12
View File
@@ -0,0 +1,12 @@
import { Role } from './auth.models';
export type Area = 'CACU' | 'CAMA' | 'TEA';
export function canAccessArea(roles: readonly Role[], area: Area): boolean {
return roles.includes('ADMIN') || roles.includes(area);
}
export function getAccessibleAreas(roles: readonly Role[]): Area[] {
const areas: Area[] = ['CACU', 'CAMA', 'TEA'];
return areas.filter(area => canAccessArea(roles, area));
}
+32
View File
@@ -0,0 +1,32 @@
import { TestBed } from '@angular/core/testing';
import { provideHttpClient } from '@angular/common/http';
import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing';
import { AuthService } from './auth.service';
describe('AuthService', () => {
let api: AuthService;
let http: HttpTestingController;
beforeEach(() => {
TestBed.configureTestingModule({ providers: [provideHttpClient(), provideHttpClientTesting()] });
api = TestBed.inject(AuthService);
http = TestBed.inject(HttpTestingController);
});
afterEach(() => http.verify());
it('posts credentials using a relative URL without Bearer', () => {
const response = { token: 'test-token', expires_in: 28800, user: { id: 1, username: 'demo', roles: [] } };
api.login('demo', 'test-password').subscribe(value => expect(value).toEqual(response));
const request = http.expectOne('/auth/login');
expect(request.request.method).toBe('POST');
expect(request.request.body).toEqual({ username: 'demo', password: 'test-password' });
expect(request.request.headers.has('Authorization')).toBe(false);
request.flush(response);
});
it('gets current identity with explicit Bearer', () => {
const response = { user: { id: 1, username: 'demo', roles: ['CAMA'] } };
api.me('test-token').subscribe(value => expect(value).toEqual(response));
const request = http.expectOne('/auth/me');
expect(request.request.method).toBe('GET');
expect(request.request.headers.get('Authorization')).toBe('Bearer test-token');
request.flush(response);
});
});
+18
View File
@@ -0,0 +1,18 @@
import { inject, Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { LoginResponse, MeResponse } from './auth.models';
@Injectable({ providedIn: 'root' })
export class AuthService {
private readonly http = inject(HttpClient);
login(username: string, password: string) {
return this.http.post<LoginResponse>('/auth/login', { username, password });
}
me(token: string) {
return this.http.get<MeResponse>('/auth/me', {
headers: { Authorization: `Bearer ${token}` },
});
}
}
+79
View File
@@ -0,0 +1,79 @@
import { TestBed } from '@angular/core/testing';
import { provideHttpClient } from '@angular/common/http';
import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing';
import { Router, provideRouter } from '@angular/router';
import { vi } from 'vitest';
import { AuthState } from './auth.state';
import { AuthStorage } from './auth.storage';
describe('AuthState', () => {
const user = { id: 1, username: 'demo', roles: ['CAMA'] };
let auth: AuthState;
let http: HttpTestingController;
beforeEach(() => {
sessionStorage.clear();
TestBed.configureTestingModule({ providers: [provideHttpClient(), provideHttpClientTesting(), provideRouter([])] });
auth = TestBed.inject(AuthState); http = TestBed.inject(HttpTestingController);
});
afterEach(() => { http.verify(); sessionStorage.clear(); vi.restoreAllMocks(); });
const seed = () => sessionStorage.setItem('ISSSTELEON.auth.token', 'test-token');
it('starts checking without trusting cache', () => {
expect(auth.status()).toBe('checking'); expect(auth.user()).toBeNull(); expect(auth.isAuthenticated()).toBe(false);
});
it('restores without token without HTTP and clears cached identity', async () => {
sessionStorage.setItem('ISSSTELEON.auth.user', JSON.stringify(user));
await auth.restore(); expect(auth.status()).toBe('anonymous'); expect(auth.user()).toBeNull();
http.expectNone('/auth/me'); expect(TestBed.inject(AuthStorage).readUser()).toBeNull();
});
it('shares concurrent restore and trusts only the current server identity', async () => {
seed(); sessionStorage.setItem('ISSSTELEON.auth.user', JSON.stringify(user));
const first = auth.restore(); const second = auth.restore(); expect(first).toBe(second);
expect(auth.status()).toBe('checking'); expect(auth.user()).toBeNull();
const current = { ...user, roles: ['TEA'] };
http.expectOne('/auth/me').flush({ user: current }); await Promise.all([first, second]);
expect(auth.isAuthenticated()).toBe(true); expect(auth.user()).toEqual(current);
expect(TestBed.inject(AuthStorage).readUser()).toEqual(current);
expect(TestBed.inject(AuthStorage).readToken()).toBe('test-token');
await auth.restore(); http.expectNone('/auth/me');
});
for (const status of [401, 500, 0]) {
it(`clears session on restore error ${status}`, async () => {
seed(); const pending = auth.restore();
const request = http.expectOne('/auth/me');
if (status === 0) request.error(new ProgressEvent('error'));
else request.flush({}, { status, statusText: 'Rejected' });
await pending; expect(auth.status()).toBe('anonymous'); expect(auth.user()).toBeNull();
expect(TestBed.inject(AuthStorage).readToken()).toBeNull();
});
}
it('login saves identity and local logout clears it and navigates', async () => {
const navigate = vi.spyOn(TestBed.inject(Router), 'navigateByUrl').mockResolvedValue(true);
const pending = auth.login('demo', 'test-password');
http.expectOne('/auth/login').flush({ token: 'test-token', expires_in: 28800, user }); await pending;
expect(auth.isAuthenticated()).toBe(true); expect(auth.user()).toEqual(user);
expect(TestBed.inject(AuthStorage).readToken()).toBe('test-token');
expect(TestBed.inject(AuthStorage).readUser()).toEqual(user);
auth.logout(); expect(auth.status()).toBe('anonymous'); expect(auth.user()).toBeNull();
expect(TestBed.inject(AuthStorage).readToken()).toBeNull(); expect(navigate).toHaveBeenCalledWith('/login');
await auth.restore(); http.expectNone('/auth/me');
});
it('failed login remains anonymous', async () => {
const pending = auth.login('demo', 'test-password');
const assertion = expect(pending).rejects.toMatchObject({ status: 401 });
http.expectOne('/auth/login').flush({}, { status: 401, statusText: 'Unauthorized' });
await assertion; expect(auth.status()).toBe('anonymous'); expect(auth.user()).toBeNull();
});
it('late restore cannot undo logout', async () => {
vi.spyOn(TestBed.inject(Router), 'navigateByUrl').mockResolvedValue(true);
seed(); const pending = auth.restore(); auth.logout();
http.expectOne('/auth/me').flush({ user }); await pending;
expect(auth.status()).toBe('anonymous'); expect(TestBed.inject(AuthStorage).readToken()).toBeNull();
});
it('late restore cannot overwrite a new login', async () => {
seed(); const restoring = auth.restore(); const login = auth.login('demo', 'test-password');
const current = { ...user, roles: ['ADMIN'] };
http.expectOne('/auth/login').flush({ token: 'new-test-token', expires_in: 28800, user: current });
await login; http.expectOne('/auth/me').flush({ user }); await restoring;
expect(auth.user()).toEqual(current); expect(TestBed.inject(AuthStorage).readToken()).toBe('new-test-token');
});
});
+77
View File
@@ -0,0 +1,77 @@
import { computed, inject, Injectable, signal } from '@angular/core';
import { Router } from '@angular/router';
import { firstValueFrom } from 'rxjs';
import { AuthUser } from './auth.models';
import { AuthService } from './auth.service';
import { AuthStorage } from './auth.storage';
@Injectable({ providedIn: 'root' })
export class AuthState {
private readonly api = inject(AuthService);
private readonly storage = inject(AuthStorage);
private readonly router = inject(Router);
private readonly currentUser = signal<AuthUser | null>(null);
private readonly token = signal<string | null>(null);
private readonly currentStatus = signal<'checking' | 'authenticated' | 'anonymous'>('checking');
readonly user = this.currentUser.asReadonly();
readonly status = this.currentStatus.asReadonly();
readonly isAuthenticated = computed(() => this.status() === 'authenticated');
private restoration?: Promise<void>;
private generation = 0;
restore(): Promise<void> {
if (this.restoration) return this.restoration;
if (this.status() !== 'checking') return Promise.resolve();
const token = this.storage.readToken();
if (!token) {
this.clear();
return Promise.resolve();
}
const generation = this.generation;
const pending = this.validate(token, generation);
this.restoration = pending;
void pending.finally(() => {
if (this.restoration === pending) this.restoration = undefined;
});
return pending;
}
private async validate(token: string, generation: number): Promise<void> {
try {
const response = await firstValueFrom(this.api.me(token));
if (generation !== this.generation) return;
this.token.set(token);
this.currentUser.set(response.user);
this.storage.updateUser(response.user);
this.currentStatus.set('authenticated');
} catch {
if (generation === this.generation) this.clear();
}
}
async login(username: string, password: string): Promise<void> {
const generation = ++this.generation;
this.restoration = undefined;
this.clear();
const response = await firstValueFrom(this.api.login(username, password));
if (generation !== this.generation) return;
this.token.set(response.token);
this.currentUser.set(response.user);
this.storage.save(response.token, response.user);
this.currentStatus.set('authenticated');
}
logout(): void {
++this.generation;
this.restoration = undefined;
this.clear();
void this.router.navigateByUrl('/login');
}
private clear(): void {
this.token.set(null);
this.currentUser.set(null);
this.storage.clear();
this.currentStatus.set('anonymous');
}
}
+40
View File
@@ -0,0 +1,40 @@
import { AuthStorage } from './auth.storage';
import { vi } from 'vitest';
describe('AuthStorage', () => {
const user = { id: 1, username: 'demo', roles: ['CAMA'] as const };
let storage: AuthStorage;
beforeEach(() => { sessionStorage.clear(); storage = new AuthStorage(); });
afterEach(() => { vi.restoreAllMocks(); sessionStorage.clear(); });
it('reads empty storage safely', () => {
expect(storage.readToken()).toBeNull(); expect(storage.readUser()).toBeNull();
});
it('saves and clears the tab session', () => {
storage.save('test-token', { ...user, roles: ['CAMA'] });
expect(storage.readToken()).toBe('test-token'); expect(storage.readUser()).toEqual(user);
storage.updateUser({ ...user, roles: ['ADMIN'] });
expect(storage.readUser()?.roles).toEqual(['ADMIN']);
storage.clear(); expect(storage.readToken()).toBeNull(); expect(storage.readUser()).toBeNull();
});
it('ignores malformed JSON and invalid cache shapes', () => {
for (const value of ['{', '123', '{"id":1}', '{"id":1,"username":"demo","roles":["OTHER"]}']) {
sessionStorage.setItem('ISSSTELEON.auth.user', value);
expect(storage.readUser()).toBeNull();
}
});
it('tolerates unavailable sessionStorage', () => {
vi.spyOn(window, 'sessionStorage', 'get').mockImplementation(() => { throw new Error('disabled'); });
expect(storage.readToken()).toBeNull(); expect(storage.readUser()).toBeNull();
expect(() => storage.save('test-token', { ...user, roles: ['CAMA'] })).not.toThrow();
expect(() => storage.updateUser({ ...user, roles: ['CAMA'] })).not.toThrow();
expect(() => storage.clear()).not.toThrow();
});
it('tolerates read, write and removal failures', () => {
vi.spyOn(Storage.prototype, 'getItem').mockImplementation(() => { throw new Error('read'); });
vi.spyOn(Storage.prototype, 'setItem').mockImplementation(() => { throw new Error('write'); });
vi.spyOn(Storage.prototype, 'removeItem').mockImplementation(() => { throw new Error('remove'); });
expect(storage.readToken()).toBeNull(); expect(storage.readUser()).toBeNull();
expect(() => storage.save('test-token', { ...user, roles: ['CAMA'] })).not.toThrow();
expect(() => storage.clear()).not.toThrow();
});
});
+41
View File
@@ -0,0 +1,41 @@
import { Injectable } from '@angular/core';
import { AuthUser } from './auth.models';
@Injectable({ providedIn: 'root' })
export class AuthStorage {
private readonly tokenKey = 'ISSSTELEON.auth.token';
private readonly userKey = 'ISSSTELEON.auth.user';
readToken(): string | null {
try { return sessionStorage.getItem(this.tokenKey); } catch { return null; }
}
readUser(): AuthUser | null {
try {
const value: unknown = JSON.parse(sessionStorage.getItem(this.userKey) ?? 'null');
if (typeof value !== 'object' || value === null) return null;
const user = value as AuthUser;
return typeof user.id === 'number' && typeof user.username === 'string' &&
Array.isArray(user.roles) && user.roles.every(role =>
['ADMIN', 'CACU', 'CAMA', 'TEA'].includes(role)) ? user : null;
} catch { return null; }
}
save(token: string, user: AuthUser): void {
try {
sessionStorage.setItem(this.tokenKey, token);
sessionStorage.setItem(this.userKey, JSON.stringify(user));
} catch { this.clear(); }
}
updateUser(user: AuthUser): void {
try { sessionStorage.setItem(this.userKey, JSON.stringify(user)); } catch { this.clear(); }
}
clear(): void {
// Attempt both removals even if one storage operation fails.
for (const key of [this.tokenKey, this.userKey]) {
try { sessionStorage.removeItem(key); } catch { /* Storage may be disabled. */ }
}
}
}
+40
View File
@@ -0,0 +1,40 @@
import { signal } from '@angular/core';
import { TestBed } from '@angular/core/testing';
import { provideRouter } from '@angular/router';
import { AuthUser, Role } from './auth.models';
import { AuthState } from './auth.state';
import { Home } from './home';
describe('Home areas', () => {
const user = signal<AuthUser>({ id: 1, username: 'demo', roles: [] });
beforeEach(() => {
user.set({ id: 1, username: 'demo', roles: [] });
TestBed.configureTestingModule({ imports: [Home], providers: [
provideRouter([]), { provide: AuthState, useValue: { user } },
] });
});
const cases: [Role[], string[]][] = [
[['CAMA'], ['CAMA']], [['CACU', 'CAMA'], ['CACU', 'CAMA']],
[['ADMIN'], ['CACU', 'CAMA', 'TEA']], [[], []],
];
for (const [roles, areas] of cases) {
it(`renders only authorized links for ${JSON.stringify(roles)}`, () => {
user.set({ id: 1, username: 'demo', roles });
const fixture = TestBed.createComponent(Home); fixture.detectChanges();
const root: HTMLElement = fixture.nativeElement;
const links = Array.from(root.querySelectorAll('a'));
expect(links.map(link => link.textContent?.trim())).toEqual(areas);
expect(links.map(link => link.getAttribute('href'))).toEqual(areas.map(area => '/' + area.toLowerCase()));
expect(root.querySelector('[role="status"]')?.textContent ?? null)
.toBe(areas.length ? null : 'No tienes áreas asignadas.');
});
}
it('updates navigation from current AuthState roles', () => {
user.set({ id: 1, username: 'demo', roles: ['ADMIN'] });
const fixture = TestBed.createComponent(Home); fixture.detectChanges();
expect(fixture.nativeElement.querySelectorAll('a').length).toBe(3);
user.set({ id: 1, username: 'demo', roles: ['TEA'] }); fixture.detectChanges();
expect(Array.from(fixture.nativeElement.querySelectorAll('a') as NodeListOf<HTMLAnchorElement>)
.map(link => link.textContent?.trim())).toEqual(['TEA']);
});
});
+25
View File
@@ -0,0 +1,25 @@
import { Component, computed, inject } from '@angular/core';
import { RouterLink } from '@angular/router';
import { MatButtonModule } from '@angular/material/button';
import { AuthState } from './auth.state';
import { getAccessibleAreas } from './auth.roles';
@Component({
selector: 'app-home',
imports: [RouterLink, MatButtonModule],
template: `
<h1>Áreas disponibles</h1>
<nav aria-label="Áreas disponibles">
@for (area of areas(); track area) {
<a mat-stroked-button [routerLink]="'/' + area.toLowerCase()">{{ area }}</a>
} @empty {
<p role="status">No tienes áreas asignadas.</p>
}
</nav>
`,
styles: `nav { display: flex; flex-wrap: wrap; gap: 1rem; }`,
})
export class Home {
private readonly auth = inject(AuthState);
protected readonly areas = computed(() => getAccessibleAreas(this.auth.user()?.roles ?? []));
}
+39
View File
@@ -0,0 +1,39 @@
<section class="login" aria-labelledby="login-title" lang="es">
<h1 id="login-title">Inicio de sesión</h1>
<form [formGroup]="form" (ngSubmit)="submit()" [attr.aria-busy]="loading()">
<mat-form-field appearance="outline" subscriptSizing="dynamic" class="login-field">
<mat-label>Usuario</mat-label>
<input matInput formControlName="username" autocomplete="username" maxlength="64"
[errorStateMatcher]="usernameErrorMatcher"
(focus)="usernameEditing.set(true)" (blur)="usernameEditing.set(false)" />
@if (showUsernameError()) { <mat-error>Ingresa un usuario válido.</mat-error> }
</mat-form-field>
<mat-form-field appearance="outline" subscriptSizing="dynamic" class="login-field">
<mat-label>Contraseña</mat-label>
<input matInput [type]="passwordVisible() ? 'text' : 'password'" formControlName="password"
autocomplete="current-password" maxlength="128" [errorStateMatcher]="passwordErrorMatcher"
(focus)="passwordEditing.set(true)" (blur)="passwordEditing.set(false)" />
<button mat-icon-button matSuffix type="button" class="password-toggle"
(click)="$event.stopPropagation(); passwordVisible.set(!passwordVisible())"
[attr.aria-label]="passwordVisible() ? 'Ocultar contraseña' : 'Mostrar contraseña'"
[attr.aria-pressed]="passwordVisible()">
<mat-icon aria-hidden="true">
<svg viewBox="0 0 24 24" focusable="false" aria-hidden="true">
<path d="M12 6c4.2 0 7.5 3.1 9 6-1.5 2.9-4.8 6-9 6s-7.5-3.1-9-6c1.5-2.9 4.8-6 9-6Z" />
<circle cx="12" cy="12" r="3" />
@if (passwordVisible()) { <path d="m3 3 18 18" /> }
</svg>
</mat-icon>
</button>
@if (showPasswordError()) { <mat-error>Ingresa tu contraseña.</mat-error> }
</mat-form-field>
<button mat-flat-button class="login-action" type="submit" [disabled]="loading()">
{{ loading() ? 'Iniciando sesión…' : 'Iniciar sesión' }}
</button>
<div class="login-feedback">
@if (error()) { <p role="alert">{{ error() }}</p> }
@if (loading()) { <p role="status">Comprobando credenciales…</p> }
</div>
</form>
<img class="login-logo" src="branding/LogoISSSTELEON.png" alt="ISSSTELEON" width="1125" height="358" />
</section>
+120
View File
@@ -0,0 +1,120 @@
@use '@angular/material' as mat;
:host {
--login-page-bg: #f7f7f7;
--login-surface: #ffffff;
--login-text: #333333;
--login-text-muted: #667085;
--login-border: #cccccc;
--login-focus: #00833c;
--isssteleon-lime: #99ca3c;
--isssteleon-green: #00833c;
--login-icon-teal: #5f9ea0;
--login-action-bg: #f8f9fa;
--login-action-border: #e9ecef;
display: grid;
box-sizing: border-box;
min-height: 100dvh;
margin: -1.5rem; // Compensate the existing main padding only while Login is mounted.
padding: 2rem 24px;
place-items: center;
background: var(--login-page-bg);
color: var(--login-text);
font-family: Roboto, Arial, sans-serif;
}
.login { width: min(100%, 26rem); min-width: 0; }
h1 {
display: flex;
align-items: center;
gap: 1rem;
margin: 0 0 2rem;
font-size: 1.5rem;
font-weight: 500;
line-height: 1.3;
white-space: nowrap;
&::before, &::after {
content: '';
flex: 1;
min-width: 0;
border-top: 1px solid var(--login-border);
}
}
form { display: flex; flex-direction: column; gap: .75rem; }
.login-field {
width: 100%;
position: relative;
isolation: isolate;
@include mat.form-field-overrides((
outlined-container-shape: 5px,
outlined-outline-color: var(--login-border),
outlined-hover-outline-color: var(--login-text-muted),
outlined-focus-outline-color: var(--login-focus),
outlined-focus-label-text-color: var(--login-focus),
outlined-label-text-color: var(--login-text-muted),
outlined-input-text-color: var(--login-text),
outlined-caret-color: var(--login-focus),
container-text-size: 16px,
));
// Keep the validation subscript on the page background.
&::before { content: ''; position: absolute; inset: 0 0 auto; height: 56px;
background: var(--login-surface); border-radius: 5px; z-index: -1; }
}
.password-toggle {
color: var(--login-text-muted);
margin-inline-end: 4px;
min-width: 48px;
min-height: 48px;
svg { width: 24px; height: 24px; fill: none; stroke: currentColor; stroke-width: 1.8; }
}
.login-action.mat-mdc-unelevated-button {
@include mat.button-overrides((
filled-container-color: var(--login-action-bg),
filled-label-text-color: var(--login-text),
filled-container-shape: 8px,
filled-container-height: 50px,
filled-label-text-size: 16px,
filled-label-text-weight: 500,
filled-state-layer-color: var(--login-focus),
filled-disabled-container-color: #e9ecef,
filled-disabled-label-text-color: #707780,
));
width: 100%;
min-height: 50px;
border: 1px solid var(--login-action-border);
border-radius: 8px;
background: var(--login-action-bg);
color: var(--login-text);
font: 500 16px Roboto, Arial, sans-serif;
cursor: pointer;
box-shadow: 0 1px 2px #00000014;
transition: transform 160ms cubic-bezier(.2, 0, 0, 1), background-color 160ms ease,
border-color 160ms ease, box-shadow 160ms ease;
&:hover:not(:disabled) {
transform: translateY(-1px);
background: #eef2ed;
border-color: var(--login-focus);
box-shadow: 0 3px 7px #0000001c;
}
&:active:not(:disabled) { transform: translateY(0) scale(.99); background: #e4ebdf; box-shadow: none; }
&:disabled { transform: none; transition: none; background: #e9ecef; color: #707780; box-shadow: none; cursor: default; }
}
button:focus-visible { outline: 2px solid var(--login-focus); outline-offset: 3px; }
@media (prefers-reduced-motion: reduce) {
.login-action.mat-mdc-unelevated-button {
transition: none;
&:hover:not(:disabled), &:active:not(:disabled) { transform: none; }
}
}
.login-feedback { min-height: 2.5rem; font-size: .875rem; line-height: 1.4; }
[role='alert'] { color: var(--mat-sys-error); margin: 0; }
[role='status'] { color: var(--login-text-muted); margin: 0; }
.login-logo { display: block; width: min(100%, clamp(200px, 17vw, 240px)); height: auto; object-fit: contain; margin: 1.5rem auto 0; }
+139
View File
@@ -0,0 +1,139 @@
import { TestBed } from '@angular/core/testing';
import { HttpErrorResponse } from '@angular/common/http';
import { Router, provideRouter } from '@angular/router';
import { vi } from 'vitest';
import { AuthState } from './auth.state';
import { Login } from './login';
describe('Login', () => {
let login: ReturnType<typeof vi.fn>;
beforeEach(() => {
login = vi.fn().mockResolvedValue(undefined);
TestBed.configureTestingModule({ imports: [Login], providers: [provideRouter([]),
{ provide: AuthState, useValue: { login, isAuthenticated: () => true } }] });
vi.spyOn(TestBed.inject(Router), 'navigateByUrl').mockResolvedValue(true);
});
afterEach(() => vi.restoreAllMocks());
const create = () => {
const fixture = TestBed.createComponent(Login); fixture.detectChanges(); return fixture;
};
const fill = (component: Login) => component.form.setValue({ username: 'Demo', password: 'test-password' });
const usernameInput = (fixture: ReturnType<typeof TestBed.createComponent<Login>>) =>
fixture.nativeElement.querySelector('input[autocomplete="username"]') as HTMLInputElement;
const hasUsernameError = (fixture: { nativeElement: HTMLElement }) =>
!!fixture.nativeElement.querySelector('mat-error');
it('renders required credentials and submit button', () => {
const fixture = create(); const element: HTMLElement = fixture.nativeElement;
expect(element.querySelector('input[autocomplete="username"]')).toBeTruthy();
expect(element.querySelector('input[type="password"]')).toBeTruthy();
expect(element.querySelector('button[type="submit"]')?.textContent).toContain('Iniciar sesión');
expect(fixture.componentInstance.form.invalid).toBe(true);
});
it('rejects empty and invalid credentials', async () => {
const component = create().componentInstance; await component.submit(); expect(login).not.toHaveBeenCalled();
for (const username of ['ab', 'a'.repeat(65), 'demo@']) {
component.form.setValue({ username, password: 'test-password' }); expect(component.form.invalid).toBe(true);
}
component.form.setValue({ username: 'demo', password: 'a'.repeat(129) }); expect(component.form.invalid).toBe(true);
});
it('shows the username error after blur, hides it while editing, and restores it on blur if still invalid', () => {
const fixture = create(); const input = usernameInput(fixture); const control = fixture.componentInstance.form.controls.username;
input.dispatchEvent(new Event('focus')); input.dispatchEvent(new Event('blur')); fixture.detectChanges();
expect(control.invalid).toBe(true);
expect(hasUsernameError(fixture)).toBe(true);
expect(input.closest('mat-form-field')?.classList.contains('mat-form-field-invalid')).toBe(true);
input.dispatchEvent(new Event('focus')); fixture.detectChanges();
expect(fixture.componentInstance.usernameEditing()).toBe(true);
expect(hasUsernameError(fixture)).toBe(false);
expect(input.closest('mat-form-field')?.classList.contains('mat-form-field-invalid')).toBe(false);
input.dispatchEvent(new Event('input')); input.dispatchEvent(new Event('blur')); fixture.detectChanges();
expect(hasUsernameError(fixture)).toBe(true);
expect(input.closest('mat-form-field')?.classList.contains('mat-form-field-invalid')).toBe(true);
});
it('keeps the username error cleared after editing to a valid value', () => {
const fixture = create(); const input = usernameInput(fixture); const control = fixture.componentInstance.form.controls.username;
input.dispatchEvent(new Event('focus')); input.dispatchEvent(new Event('blur')); fixture.detectChanges();
expect(hasUsernameError(fixture)).toBe(true);
input.dispatchEvent(new Event('focus'));
input.value = 'valid-user'; input.dispatchEvent(new Event('input', { bubbles: true }));
input.dispatchEvent(new Event('blur')); fixture.detectChanges();
expect(control.valid).toBe(true);
expect(hasUsernameError(fixture)).toBe(false);
});
it('shows field errors on invalid submit and suppresses them once editing starts', async () => {
const fixture = create(); const component = fixture.componentInstance;
await component.submit(); fixture.detectChanges();
expect(component.submitted()).toBe(true);
expect(fixture.nativeElement.querySelectorAll('mat-error').length).toBe(2);
const input = usernameInput(fixture); input.dispatchEvent(new Event('focus')); fixture.detectChanges();
expect(fixture.nativeElement.querySelectorAll('mat-error').length).toBe(1);
expect(component.form.controls.username.invalid).toBe(true);
});
it('uses dynamic subscripts for both fields', () => {
const fixture = create();
expect(fixture.nativeElement.querySelectorAll('mat-form-field[subscriptsizing="dynamic"]').length).toBe(2);
});
it('submits normalized credentials, clears password and navigates home', async () => {
const component = create().componentInstance; fill(component); await component.submit();
expect(login).toHaveBeenCalledWith('demo', 'test-password');
expect(TestBed.inject(Router).navigateByUrl).toHaveBeenCalledWith('/');
expect(component.form.controls.password.value).toBe(''); expect(component.loading()).toBe(false);
});
it('shows loading and prevents duplicate submissions', async () => {
let resolve!: () => void;
login.mockReturnValue(new Promise<void>(done => { resolve = done; }));
const fixture = create(); const component = fixture.componentInstance; fill(component);
const pending = component.submit(); fixture.detectChanges();
expect(component.loading()).toBe(true);
expect((fixture.nativeElement.querySelector('button[type="submit"]') as HTMLButtonElement).disabled).toBe(true);
expect(fixture.nativeElement.querySelector('[role="status"]')).toBeTruthy();
await component.submit(); expect(login).toHaveBeenCalledTimes(1); resolve(); await pending;
});
it('starts with the password hidden and an accessible unpressed toggle', () => {
const fixture = create();
const element: HTMLElement = fixture.nativeElement;
const toggle = element.querySelector('.password-toggle') as HTMLButtonElement;
expect(element.querySelector('input[autocomplete="current-password"]')?.getAttribute('type')).toBe('password');
expect(toggle.type).toBe('button');
expect(toggle.getAttribute('aria-label')).toBe('Mostrar contraseña');
expect(toggle.getAttribute('aria-pressed')).toBe('false');
});
it('shows and hides the password with matching aria states without submitting', () => {
const fixture = create(); fill(fixture.componentInstance);
const element: HTMLElement = fixture.nativeElement;
const toggle = element.querySelector('.password-toggle') as HTMLButtonElement;
toggle.click(); fixture.detectChanges();
expect(element.querySelector('input[autocomplete="current-password"]')?.getAttribute('type')).toBe('text');
expect(toggle.getAttribute('aria-label')).toBe('Ocultar contraseña');
expect(toggle.getAttribute('aria-pressed')).toBe('true');
expect(login).not.toHaveBeenCalled();
toggle.click(); fixture.detectChanges();
expect(element.querySelector('input[autocomplete="current-password"]')?.getAttribute('type')).toBe('password');
expect(toggle.getAttribute('aria-label')).toBe('Mostrar contraseña');
expect(toggle.getAttribute('aria-pressed')).toBe('false');
expect(login).not.toHaveBeenCalled();
expect(fixture.componentInstance.form.controls.password.value).toBe('test-password');
});
it('submits the unchanged password while it is visible', async () => {
const fixture = create(); fill(fixture.componentInstance);
(fixture.nativeElement.querySelector('.password-toggle') as HTMLButtonElement).click();
fixture.detectChanges();
fixture.nativeElement.querySelector('form').dispatchEvent(new Event('submit', { bubbles: true, cancelable: true }));
await fixture.whenStable();
expect(login).toHaveBeenCalledExactlyOnceWith('demo', 'test-password');
expect(TestBed.inject(Router).navigateByUrl).toHaveBeenCalledWith('/');
expect(fixture.componentInstance.form.controls.password.value).toBe('');
});
for (const status of [401, 500, 0, 404]) {
it(`shows generic error for ${status}`, async () => {
login.mockRejectedValue(new HttpErrorResponse({ status, error: 'PRIVATE TECHNICAL BODY' }));
const fixture = create(); const component = fixture.componentInstance; fill(component); await component.submit();
fixture.detectChanges();
expect(component.error()).toBe(status === 401 ? 'Usuario o contraseña incorrectos.'
: 'No fue posible iniciar sesión. Inténtalo de nuevo.');
expect(fixture.nativeElement.textContent).not.toContain('PRIVATE TECHNICAL BODY');
expect(TestBed.inject(Router).navigateByUrl).not.toHaveBeenCalled();
expect(component.loading()).toBe(false); expect(component.form.controls.password.value).toBe('');
});
}
});
+73
View File
@@ -0,0 +1,73 @@
import { Component, inject, signal } from '@angular/core';
import { HttpErrorResponse } from '@angular/common/http';
import { FormBuilder, FormGroupDirective, NgForm, ReactiveFormsModule, Validators } from '@angular/forms';
import { ErrorStateMatcher } from '@angular/material/core';
import { Router } from '@angular/router';
import { MatIconModule } from '@angular/material/icon';
import { MatFormFieldModule } from '@angular/material/form-field';
import { MatInputModule } from '@angular/material/input';
import { MatButtonModule } from '@angular/material/button';
import { AuthState } from './auth.state';
class LoginFieldErrorStateMatcher implements ErrorStateMatcher {
constructor(private readonly isEditing: () => boolean) {}
isErrorState(control: { invalid: boolean; touched: boolean } | null, form: FormGroupDirective | NgForm | null): boolean {
return !!control?.invalid && (control.touched || !!form?.submitted) && !this.isEditing();
}
}
@Component({
selector: 'app-login',
imports: [ReactiveFormsModule, MatIconModule, MatFormFieldModule, MatInputModule, MatButtonModule],
templateUrl: './login.html',
styleUrl: './login.scss',
})
export class Login {
private readonly auth = inject(AuthState);
private readonly router = inject(Router);
readonly loading = signal(false);
readonly error = signal('');
readonly passwordVisible = signal(false);
readonly submitted = signal(false);
readonly usernameEditing = signal(false);
readonly passwordEditing = signal(false);
readonly usernameErrorMatcher = new LoginFieldErrorStateMatcher(() => this.usernameEditing());
readonly passwordErrorMatcher = new LoginFieldErrorStateMatcher(() => this.passwordEditing());
readonly form = inject(FormBuilder).nonNullable.group({
username: ['', [Validators.required, Validators.minLength(3), Validators.maxLength(64),
Validators.pattern(/^[a-zA-Z0-9._-]+$/)]],
password: ['', [Validators.required, Validators.maxLength(128)]],
});
showUsernameError(): boolean {
return this.form.controls.username.invalid && (this.form.controls.username.touched || this.submitted())
&& !this.usernameEditing();
}
showPasswordError(): boolean {
return this.form.controls.password.invalid && (this.form.controls.password.touched || this.submitted())
&& !this.passwordEditing();
}
async submit(): Promise<void> {
if (this.loading()) return;
this.submitted.set(true);
if (this.form.invalid) { this.form.markAllAsTouched(); return; }
this.loading.set(true);
this.error.set('');
const { username, password } = this.form.getRawValue();
try {
await this.auth.login(username.trim().toLowerCase(), password);
this.form.controls.password.reset();
if (this.auth.isAuthenticated()) await this.router.navigateByUrl('/');
} catch (error) {
this.form.controls.password.reset();
this.error.set(error instanceof HttpErrorResponse && error.status === 401
? 'Usuario o contraseña incorrectos.'
: 'No fue posible iniciar sesión. Inténtalo de nuevo.');
} finally {
this.loading.set(false);
}
}
}
+3 -6
View File
@@ -2,20 +2,17 @@
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Webapp</title>
<title>WebApp</title>
<base href="/" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<link rel="icon" type="image/x-icon" href="favicon.ico" />
<link rel="icon" type="image/png" href="branding/favicon-isssteleon.png" />
<link rel="preconnect" href="https://fonts.googleapis.com" />
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
<link
href="https://fonts.googleapis.com/css2?family=Roboto:wght@300;400;500&display=swap"
rel="stylesheet"
/>
<link
href="https://fonts.googleapis.com/icon?family=Material+Symbols+Outlined"
rel="stylesheet"
/>
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet" />
</head>
<body>
<app-root></app-root>
+2 -1
View File
@@ -2,4 +2,5 @@ import { bootstrapApplication } from '@angular/platform-browser';
import { appConfig } from './app/app.config';
import { App } from './app/app';
bootstrapApplication(App, appConfig).catch((err) => console.error(err));
bootstrapApplication(App, appConfig)
.catch((err) => console.error(err));
+6 -2
View File
@@ -5,6 +5,10 @@
"compilerOptions": {
"types": []
},
"include": ["src/**/*.ts"],
"exclude": ["src/**/*.spec.ts"]
"include": [
"src/**/*.ts"
],
"exclude": [
"src/**/*.spec.ts"
]
}
+7 -2
View File
@@ -3,7 +3,12 @@
{
"extends": "./tsconfig.json",
"compilerOptions": {
"types": ["vitest/globals"]
"types": [
"vitest/globals"
]
},
"include": ["src/**/*.d.ts", "src/**/*.spec.ts"]
"include": [
"src/**/*.d.ts",
"src/**/*.spec.ts"
]
}