first commit
This commit is contained in:
22
libs/web/identity/application/README.md
Normal file
22
libs/web/identity/application/README.md
Normal file
@@ -0,0 +1,22 @@
|
||||
# web-identity-application
|
||||
|
||||
Estado de autenticación (NgRx Signals con eventos) detrás de una facade.
|
||||
|
||||
- **Import**: `@task-stream/web/identity/application`
|
||||
- **Capa**: `application` · **Tags**: `scope:web-identity`, `type:application`
|
||||
|
||||
## Contenido
|
||||
|
||||
- `AuthFacade` (lo único que se exporta, junto al tipo `AuthStatus`): sesión y usuario como señales; `signInWith*()`,
|
||||
`completeSignIn()`, `signOut()`, `validAccessToken()`.
|
||||
- Interno: `AuthStore` (login con PKCE o email y contraseña de Pireon; restaura la sesión al arrancar y renueva el
|
||||
token) y eventos `authPageEvents`, `authApiEvents`, `sessionEvents`.
|
||||
|
||||
## Comandos
|
||||
|
||||
```sh
|
||||
npx nx lint web-identity-application
|
||||
npx nx test web-identity-application # Vitest
|
||||
```
|
||||
|
||||
Reglas de dependencia entre capas: [Arquitectura](../../../../docs/02-arquitectura.md#21-capas-hexagonales).
|
||||
34
libs/web/identity/application/eslint.config.mjs
Normal file
34
libs/web/identity/application/eslint.config.mjs
Normal file
@@ -0,0 +1,34 @@
|
||||
import nx from '@nx/eslint-plugin';
|
||||
import baseConfig from '../../../../eslint.config.mjs';
|
||||
|
||||
export default [
|
||||
...nx.configs['flat/angular'],
|
||||
...nx.configs['flat/angular-template'],
|
||||
...baseConfig,
|
||||
{
|
||||
files: ['**/*.ts'],
|
||||
rules: {
|
||||
'@angular-eslint/directive-selector': [
|
||||
'error',
|
||||
{
|
||||
type: 'attribute',
|
||||
prefix: 'ts',
|
||||
style: 'camelCase',
|
||||
},
|
||||
],
|
||||
'@angular-eslint/component-selector': [
|
||||
'error',
|
||||
{
|
||||
type: 'element',
|
||||
prefix: 'ts',
|
||||
style: 'kebab-case',
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
{
|
||||
files: ['**/*.html'],
|
||||
// Override or add rules here
|
||||
rules: {},
|
||||
},
|
||||
];
|
||||
20
libs/web/identity/application/project.json
Normal file
20
libs/web/identity/application/project.json
Normal file
@@ -0,0 +1,20 @@
|
||||
{
|
||||
"name": "web-identity-application",
|
||||
"$schema": "../../../../node_modules/nx/schemas/project-schema.json",
|
||||
"sourceRoot": "libs/web/identity/application/src",
|
||||
"prefix": "ts",
|
||||
"projectType": "library",
|
||||
"tags": ["scope:web-identity", "type:application"],
|
||||
"targets": {
|
||||
"test": {
|
||||
"executor": "@nx/vitest:test",
|
||||
"outputs": ["{options.reportsDirectory}"],
|
||||
"options": {
|
||||
"reportsDirectory": "coverage/libs/web/identity/application"
|
||||
}
|
||||
},
|
||||
"lint": {
|
||||
"executor": "@nx/eslint:lint"
|
||||
}
|
||||
}
|
||||
}
|
||||
2
libs/web/identity/application/src/index.ts
Normal file
2
libs/web/identity/application/src/index.ts
Normal file
@@ -0,0 +1,2 @@
|
||||
export * from './lib/auth.facade';
|
||||
export type { AuthStatus } from './lib/auth.store';
|
||||
51
libs/web/identity/application/src/lib/auth.events.ts
Normal file
51
libs/web/identity/application/src/lib/auth.events.ts
Normal file
@@ -0,0 +1,51 @@
|
||||
import { type } from '@ngrx/signals';
|
||||
import { eventGroup } from '@ngrx/signals/events';
|
||||
import {
|
||||
AuthConfig,
|
||||
CurrentUser,
|
||||
Session,
|
||||
} from '@task-stream/web/identity/domain';
|
||||
|
||||
/** What the user does on the sign-in screens. */
|
||||
export const authPageEvents = eventGroup({
|
||||
source: 'Auth Page',
|
||||
events: {
|
||||
opened: type<void>(),
|
||||
signInWithPireon: type<{ returnUrl: string }>(),
|
||||
signInWithPassword: type<{
|
||||
username: string;
|
||||
password: string;
|
||||
returnUrl: string;
|
||||
}>(),
|
||||
callbackReceived: type<{ query: string }>(),
|
||||
},
|
||||
});
|
||||
|
||||
/** Anywhere in the app. */
|
||||
export const sessionEvents = eventGroup({
|
||||
source: 'Session',
|
||||
events: {
|
||||
signOutRequested: type<void>(),
|
||||
/** The API rejected the token (expired / revoked / user deactivated). */
|
||||
expired: type<void>(),
|
||||
},
|
||||
});
|
||||
|
||||
/** Results of talking to the API / identity server. */
|
||||
export const authApiEvents = eventGroup({
|
||||
source: 'Auth API',
|
||||
events: {
|
||||
configLoaded: type<AuthConfig | null>(),
|
||||
signedIn: type<{
|
||||
session: Session;
|
||||
user: CurrentUser;
|
||||
returnUrl: string;
|
||||
}>(),
|
||||
signInFailed: type<string>(),
|
||||
sessionRestored: type<{ session: Session; user: CurrentUser }>(),
|
||||
sessionRefreshed: type<Session>(),
|
||||
signedOut: type<void>(),
|
||||
/** Startup without a usable stored session (no redirect: guards decide). */
|
||||
anonymous: type<void>(),
|
||||
},
|
||||
});
|
||||
65
libs/web/identity/application/src/lib/auth.facade.ts
Normal file
65
libs/web/identity/application/src/lib/auth.facade.ts
Normal file
@@ -0,0 +1,65 @@
|
||||
import { computed, inject, Injectable } from '@angular/core';
|
||||
import { injectDispatch } from '@ngrx/signals/events';
|
||||
import { authPageEvents, sessionEvents } from './auth.events';
|
||||
import { AuthStore } from './auth.store';
|
||||
|
||||
/**
|
||||
* Entry point to the session for presenters (and other contexts): read state
|
||||
* as signals, express intentions as methods. Behind it, each method dispatches
|
||||
* an event that the `AuthStore` reduces and handles.
|
||||
*/
|
||||
@Injectable({ providedIn: 'root' })
|
||||
export class AuthFacade {
|
||||
private readonly store = inject(AuthStore);
|
||||
private readonly page = injectDispatch(authPageEvents);
|
||||
private readonly session = injectDispatch(sessionEvents);
|
||||
|
||||
readonly status = this.store.status;
|
||||
readonly user = this.store.user;
|
||||
/** undefined = not loaded yet, null = only personal access tokens. */
|
||||
readonly config = this.store.config;
|
||||
readonly error = this.store.error;
|
||||
readonly isAuthenticated = this.store.isAuthenticated;
|
||||
readonly initials = this.store.initials;
|
||||
readonly signingIn = computed(() => this.store.status() === 'signing-in');
|
||||
/** False until the stored session has been restored (or discarded). */
|
||||
readonly settled = computed(
|
||||
() => !['restoring', 'signing-in'].includes(this.store.status()),
|
||||
);
|
||||
|
||||
/** The sign-in screen opened: loads how the API lets users sign in. */
|
||||
openSignIn(): void {
|
||||
this.page.opened();
|
||||
}
|
||||
|
||||
signInWithPireon(returnUrl: string): void {
|
||||
this.page.signInWithPireon({ returnUrl });
|
||||
}
|
||||
|
||||
signInWithPassword(
|
||||
username: string,
|
||||
password: string,
|
||||
returnUrl: string,
|
||||
): void {
|
||||
this.page.signInWithPassword({ username, password, returnUrl });
|
||||
}
|
||||
|
||||
/** Back from Pireon with `?code=…&state=…`. */
|
||||
completeSignIn(query: string): void {
|
||||
this.page.callbackReceived({ query });
|
||||
}
|
||||
|
||||
signOut(): void {
|
||||
this.session.signOutRequested();
|
||||
}
|
||||
|
||||
/** A valid access token for API calls, refreshed when about to expire. */
|
||||
validAccessToken(): Promise<string | null> {
|
||||
return this.store.validAccessToken();
|
||||
}
|
||||
|
||||
/** The API rejected the token. */
|
||||
expire(): void {
|
||||
this.store.expire();
|
||||
}
|
||||
}
|
||||
289
libs/web/identity/application/src/lib/auth.store.ts
Normal file
289
libs/web/identity/application/src/lib/auth.store.ts
Normal file
@@ -0,0 +1,289 @@
|
||||
import { HttpErrorResponse } from '@angular/common/http';
|
||||
import { computed, inject } from '@angular/core';
|
||||
import { Router } from '@angular/router';
|
||||
import { mapResponse } from '@ngrx/operators';
|
||||
import {
|
||||
signalStore,
|
||||
withComputed,
|
||||
withHooks,
|
||||
withMethods,
|
||||
withState,
|
||||
} from '@ngrx/signals';
|
||||
import {
|
||||
Dispatcher,
|
||||
Events,
|
||||
on,
|
||||
withEventHandlers,
|
||||
withReducer,
|
||||
} from '@ngrx/signals/events';
|
||||
import {
|
||||
AuthConfig,
|
||||
AuthGateway,
|
||||
AuthorizationFlow,
|
||||
CurrentUser,
|
||||
isExpired,
|
||||
ProfileGateway,
|
||||
Session,
|
||||
SessionStorage,
|
||||
} from '@task-stream/web/identity/domain';
|
||||
import { exhaustMap, firstValueFrom, from, map, switchMap, tap } from 'rxjs';
|
||||
import { authApiEvents, authPageEvents, sessionEvents } from './auth.events';
|
||||
|
||||
export type AuthStatus =
|
||||
| 'restoring'
|
||||
| 'anonymous'
|
||||
| 'signing-in'
|
||||
| 'authenticated';
|
||||
|
||||
interface AuthState {
|
||||
status: AuthStatus;
|
||||
session: Session | null;
|
||||
user: CurrentUser | null;
|
||||
/** undefined = not loaded yet, null = only personal access tokens. */
|
||||
config: AuthConfig | null | undefined;
|
||||
error: string | null;
|
||||
}
|
||||
|
||||
const initialState: AuthState = {
|
||||
status: 'restoring',
|
||||
session: null,
|
||||
user: null,
|
||||
config: undefined,
|
||||
error: null,
|
||||
};
|
||||
|
||||
function describe(error: unknown): string {
|
||||
if (error instanceof HttpErrorResponse) {
|
||||
return (
|
||||
(error.error as { message?: string } | null)?.message ?? error.message
|
||||
);
|
||||
}
|
||||
return error instanceof Error ? error.message : String(error);
|
||||
}
|
||||
|
||||
export const AuthStore = signalStore(
|
||||
{ providedIn: 'root' },
|
||||
withState(initialState),
|
||||
withComputed(({ status, user }) => ({
|
||||
isAuthenticated: computed(() => status() === 'authenticated'),
|
||||
initials: computed(() =>
|
||||
(user()?.name ?? '')
|
||||
.split(/\s+/)
|
||||
.map((part) => part[0])
|
||||
.join('')
|
||||
.slice(0, 2)
|
||||
.toUpperCase(),
|
||||
),
|
||||
})),
|
||||
withReducer(
|
||||
on(authApiEvents.configLoaded, ({ payload }) => ({ config: payload })),
|
||||
on(
|
||||
authPageEvents.signInWithPassword,
|
||||
authPageEvents.signInWithPireon,
|
||||
authPageEvents.callbackReceived,
|
||||
() => ({ status: 'signing-in' as const, error: null }),
|
||||
),
|
||||
on(
|
||||
authApiEvents.signedIn,
|
||||
authApiEvents.sessionRestored,
|
||||
({ payload }) => ({
|
||||
status: 'authenticated' as const,
|
||||
session: payload.session,
|
||||
user: payload.user,
|
||||
error: null,
|
||||
}),
|
||||
),
|
||||
on(authApiEvents.sessionRefreshed, ({ payload }) => ({ session: payload })),
|
||||
on(authApiEvents.signInFailed, ({ payload }) => ({
|
||||
status: 'anonymous' as const,
|
||||
session: null,
|
||||
user: null,
|
||||
error: payload,
|
||||
})),
|
||||
on(authApiEvents.signedOut, authApiEvents.anonymous, () => ({
|
||||
status: 'anonymous' as const,
|
||||
session: null,
|
||||
user: null,
|
||||
})),
|
||||
),
|
||||
withEventHandlers(
|
||||
(
|
||||
store,
|
||||
events = inject(Events),
|
||||
auth = inject(AuthGateway),
|
||||
profile = inject(ProfileGateway),
|
||||
flow = inject(AuthorizationFlow),
|
||||
storage = inject(SessionStorage),
|
||||
router = inject(Router),
|
||||
) => {
|
||||
/** Token → who is it → signed in. */
|
||||
const signIn = (
|
||||
session$: ReturnType<AuthGateway['password']>,
|
||||
returnUrl: string,
|
||||
) =>
|
||||
session$.pipe(
|
||||
switchMap((session) =>
|
||||
profile
|
||||
.me(session.accessToken)
|
||||
.pipe(map((user) => ({ session, user }))),
|
||||
),
|
||||
mapResponse({
|
||||
next: ({ session, user }) =>
|
||||
authApiEvents.signedIn({ session, user, returnUrl }),
|
||||
error: (error) => authApiEvents.signInFailed(describe(error)),
|
||||
}),
|
||||
);
|
||||
|
||||
return {
|
||||
loadConfig$: events.on(authPageEvents.opened).pipe(
|
||||
exhaustMap(() =>
|
||||
auth.config().pipe(
|
||||
mapResponse({
|
||||
next: (config) => authApiEvents.configLoaded(config),
|
||||
error: () => authApiEvents.configLoaded(null),
|
||||
}),
|
||||
),
|
||||
),
|
||||
),
|
||||
redirectToPireon$: events.on(authPageEvents.signInWithPireon).pipe(
|
||||
exhaustMap(({ payload }) => {
|
||||
const config = store.config();
|
||||
if (!config)
|
||||
return [
|
||||
authApiEvents.signInFailed(
|
||||
'Pireon sign-in is not configured on the API',
|
||||
),
|
||||
];
|
||||
return from(flow.start(config, payload.returnUrl)).pipe(
|
||||
map(() => null),
|
||||
);
|
||||
}),
|
||||
),
|
||||
password$: events
|
||||
.on(authPageEvents.signInWithPassword)
|
||||
.pipe(
|
||||
exhaustMap(({ payload }) =>
|
||||
signIn(
|
||||
auth.password(payload.username, payload.password),
|
||||
payload.returnUrl,
|
||||
),
|
||||
),
|
||||
),
|
||||
callback$: events.on(authPageEvents.callbackReceived).pipe(
|
||||
exhaustMap(({ payload }) => {
|
||||
try {
|
||||
const response = flow.complete(
|
||||
new URLSearchParams(payload.query),
|
||||
);
|
||||
return signIn(
|
||||
auth.exchangeCode(
|
||||
response.code,
|
||||
response.codeVerifier,
|
||||
response.redirectUri,
|
||||
),
|
||||
response.returnUrl,
|
||||
);
|
||||
} catch (error) {
|
||||
return [authApiEvents.signInFailed(describe(error))];
|
||||
}
|
||||
}),
|
||||
),
|
||||
persist$: events
|
||||
.on(authApiEvents.signedIn, authApiEvents.sessionRefreshed)
|
||||
.pipe(
|
||||
tap(() => {
|
||||
const session = store.session();
|
||||
if (session) storage.save(session);
|
||||
}),
|
||||
),
|
||||
navigateIn$: events
|
||||
.on(authApiEvents.signedIn)
|
||||
.pipe(
|
||||
tap(
|
||||
({ payload }) =>
|
||||
void router.navigateByUrl(payload.returnUrl || '/'),
|
||||
),
|
||||
),
|
||||
signOut$: events
|
||||
.on(sessionEvents.signOutRequested, sessionEvents.expired)
|
||||
.pipe(
|
||||
tap(() => storage.clear()),
|
||||
map(() => authApiEvents.signedOut()),
|
||||
),
|
||||
navigateOut$: events
|
||||
.on(authApiEvents.signedOut)
|
||||
.pipe(tap(() => void router.navigateByUrl('/login'))),
|
||||
};
|
||||
},
|
||||
),
|
||||
withMethods(
|
||||
(store, auth = inject(AuthGateway), dispatcher = inject(Dispatcher)) => {
|
||||
let refreshing: Promise<string | null> | null = null;
|
||||
|
||||
return {
|
||||
/**
|
||||
* A valid access token for API calls: refreshed when about to expire
|
||||
* (once, even if many requests ask at the same time).
|
||||
*/
|
||||
async validAccessToken(): Promise<string | null> {
|
||||
const session = store.session();
|
||||
if (!session) return null;
|
||||
if (!isExpired(session)) return session.accessToken;
|
||||
if (!session.refreshToken) {
|
||||
dispatcher.dispatch(sessionEvents.expired());
|
||||
return null;
|
||||
}
|
||||
refreshing ??= firstValueFrom(auth.refresh(session.refreshToken))
|
||||
.then((fresh) => {
|
||||
dispatcher.dispatch(authApiEvents.sessionRefreshed(fresh));
|
||||
return fresh.accessToken;
|
||||
})
|
||||
.catch(() => {
|
||||
dispatcher.dispatch(sessionEvents.expired());
|
||||
return null;
|
||||
})
|
||||
.finally(() => (refreshing = null));
|
||||
return refreshing;
|
||||
},
|
||||
expire(): void {
|
||||
if (store.status() === 'authenticated')
|
||||
dispatcher.dispatch(sessionEvents.expired());
|
||||
},
|
||||
};
|
||||
},
|
||||
),
|
||||
withHooks({
|
||||
/** Restores the stored session (and checks it is still accepted). */
|
||||
onInit(store) {
|
||||
const storage = inject(SessionStorage);
|
||||
const profile = inject(ProfileGateway);
|
||||
const dispatcher = inject(Dispatcher);
|
||||
const stored = storage.load();
|
||||
if (!stored) {
|
||||
dispatcher.dispatch(authApiEvents.anonymous());
|
||||
return;
|
||||
}
|
||||
// Seed the token so validAccessToken() can refresh it if needed.
|
||||
dispatcher.dispatch(authApiEvents.sessionRefreshed(stored));
|
||||
void store.validAccessToken().then((token) => {
|
||||
if (!token) {
|
||||
dispatcher.dispatch(authApiEvents.anonymous());
|
||||
return;
|
||||
}
|
||||
profile.me(token).subscribe({
|
||||
next: (user) =>
|
||||
dispatcher.dispatch(
|
||||
authApiEvents.sessionRestored({
|
||||
session: store.session() ?? stored,
|
||||
user,
|
||||
}),
|
||||
),
|
||||
error: () => {
|
||||
storage.clear();
|
||||
dispatcher.dispatch(authApiEvents.anonymous());
|
||||
},
|
||||
});
|
||||
});
|
||||
},
|
||||
}),
|
||||
);
|
||||
5
libs/web/identity/application/src/test-setup.ts
Normal file
5
libs/web/identity/application/src/test-setup.ts
Normal file
@@ -0,0 +1,5 @@
|
||||
import '@angular/compiler';
|
||||
import '@analogjs/vitest-angular/setup-snapshots';
|
||||
import { setupTestBed } from '@analogjs/vitest-angular/setup-testbed';
|
||||
|
||||
setupTestBed();
|
||||
30
libs/web/identity/application/tsconfig.json
Normal file
30
libs/web/identity/application/tsconfig.json
Normal file
@@ -0,0 +1,30 @@
|
||||
{
|
||||
"extends": "../../../../tsconfig.base.json",
|
||||
"compilerOptions": {
|
||||
"isolatedModules": true,
|
||||
"target": "es2022",
|
||||
"strict": true,
|
||||
"noImplicitOverride": true,
|
||||
"noPropertyAccessFromIndexSignature": true,
|
||||
"noImplicitReturns": true,
|
||||
"noFallthroughCasesInSwitch": true,
|
||||
"emitDecoratorMetadata": false,
|
||||
"module": "preserve"
|
||||
},
|
||||
"angularCompilerOptions": {
|
||||
"enableI18nLegacyMessageIdFormat": false,
|
||||
"strictInjectionParameters": true,
|
||||
"strictInputAccessModifiers": true,
|
||||
"strictTemplates": true
|
||||
},
|
||||
"files": [],
|
||||
"include": [],
|
||||
"references": [
|
||||
{
|
||||
"path": "./tsconfig.lib.json"
|
||||
},
|
||||
{
|
||||
"path": "./tsconfig.spec.json"
|
||||
}
|
||||
]
|
||||
}
|
||||
26
libs/web/identity/application/tsconfig.lib.json
Normal file
26
libs/web/identity/application/tsconfig.lib.json
Normal file
@@ -0,0 +1,26 @@
|
||||
{
|
||||
"extends": "./tsconfig.json",
|
||||
"compilerOptions": {
|
||||
"outDir": "../../../../dist/out-tsc",
|
||||
"declaration": true,
|
||||
"declarationMap": true,
|
||||
"inlineSources": true,
|
||||
"types": []
|
||||
},
|
||||
"include": ["src/**/*.ts"],
|
||||
"exclude": [
|
||||
"src/**/*.spec.ts",
|
||||
"src/**/*.test.ts",
|
||||
"vite.config.ts",
|
||||
"vite.config.mts",
|
||||
"vitest.config.ts",
|
||||
"vitest.config.mts",
|
||||
"src/**/*.test.tsx",
|
||||
"src/**/*.spec.tsx",
|
||||
"src/**/*.test.js",
|
||||
"src/**/*.spec.js",
|
||||
"src/**/*.test.jsx",
|
||||
"src/**/*.spec.jsx",
|
||||
"src/test-setup.ts"
|
||||
]
|
||||
}
|
||||
29
libs/web/identity/application/tsconfig.spec.json
Normal file
29
libs/web/identity/application/tsconfig.spec.json
Normal file
@@ -0,0 +1,29 @@
|
||||
{
|
||||
"extends": "./tsconfig.json",
|
||||
"compilerOptions": {
|
||||
"outDir": "../../../../dist/out-tsc",
|
||||
"types": [
|
||||
"vitest/globals",
|
||||
"vitest/importMeta",
|
||||
"vite/client",
|
||||
"node",
|
||||
"vitest"
|
||||
]
|
||||
},
|
||||
"include": [
|
||||
"vite.config.ts",
|
||||
"vite.config.mts",
|
||||
"vitest.config.ts",
|
||||
"vitest.config.mts",
|
||||
"src/**/*.test.ts",
|
||||
"src/**/*.spec.ts",
|
||||
"src/**/*.test.tsx",
|
||||
"src/**/*.spec.tsx",
|
||||
"src/**/*.test.js",
|
||||
"src/**/*.spec.js",
|
||||
"src/**/*.test.jsx",
|
||||
"src/**/*.spec.jsx",
|
||||
"src/**/*.d.ts"
|
||||
],
|
||||
"files": ["src/test-setup.ts"]
|
||||
}
|
||||
29
libs/web/identity/application/vite.config.mts
Normal file
29
libs/web/identity/application/vite.config.mts
Normal file
@@ -0,0 +1,29 @@
|
||||
/// <reference types='vitest' />
|
||||
import { defineConfig } from 'vite';
|
||||
import angular from '@analogjs/vite-plugin-angular';
|
||||
import { nxViteTsPaths } from '@nx/vite/plugins/nx-tsconfig-paths.plugin';
|
||||
import { nxCopyAssetsPlugin } from '@nx/vite/plugins/nx-copy-assets.plugin';
|
||||
|
||||
export default defineConfig(() => ({
|
||||
root: import.meta.dirname,
|
||||
cacheDir: '../../../../node_modules/.vite/libs/web/identity/application',
|
||||
plugins: [angular(), nxViteTsPaths(), nxCopyAssetsPlugin(['*.md'])],
|
||||
// Uncomment this if you are using workers.
|
||||
// worker: {
|
||||
// plugins: () => [ nxViteTsPaths() ],
|
||||
// },
|
||||
test: {
|
||||
name: 'web-identity-application',
|
||||
watch: false,
|
||||
passWithNoTests: true,
|
||||
globals: true,
|
||||
environment: 'jsdom',
|
||||
include: ['{src,tests}/**/*.{test,spec}.{js,mjs,cjs,ts,mts,cts,jsx,tsx}'],
|
||||
setupFiles: ['src/test-setup.ts'],
|
||||
reporters: ['default'],
|
||||
coverage: {
|
||||
reportsDirectory: '../../../../coverage/libs/web/identity/application',
|
||||
provider: 'v8' as const,
|
||||
},
|
||||
},
|
||||
}));
|
||||
20
libs/web/identity/domain/README.md
Normal file
20
libs/web/identity/domain/README.md
Normal file
@@ -0,0 +1,20 @@
|
||||
# web-identity-domain
|
||||
|
||||
Sesión y usuario en el navegador.
|
||||
|
||||
- **Import**: `@task-stream/web/identity/domain`
|
||||
- **Capa**: `domain` · **Tags**: `scope:web-identity`, `type:domain`
|
||||
|
||||
## Contenido
|
||||
|
||||
- `Session`, `CurrentUser`, `AuthConfig`, `isExpired`, `sessionFrom`.
|
||||
- Puertos: `AuthGateway`, `ProfileGateway`, `SessionStorage`, `AuthorizationFlow`.
|
||||
|
||||
## Comandos
|
||||
|
||||
```sh
|
||||
npx nx lint web-identity-domain
|
||||
npx nx test web-identity-domain # Jest
|
||||
```
|
||||
|
||||
Reglas de dependencia entre capas: [Arquitectura](../../../../docs/02-arquitectura.md#21-capas-hexagonales).
|
||||
3
libs/web/identity/domain/eslint.config.mjs
Normal file
3
libs/web/identity/domain/eslint.config.mjs
Normal file
@@ -0,0 +1,3 @@
|
||||
import baseConfig from '../../../../eslint.config.mjs';
|
||||
|
||||
export default [...baseConfig];
|
||||
11
libs/web/identity/domain/jest.config.cts
Normal file
11
libs/web/identity/domain/jest.config.cts
Normal file
@@ -0,0 +1,11 @@
|
||||
module.exports = {
|
||||
displayName: 'web-identity-domain',
|
||||
preset: '../../../../jest.preset.js',
|
||||
testEnvironment: 'node',
|
||||
passWithNoTests: true,
|
||||
transform: {
|
||||
'^.+\\.[tj]s$': ['ts-jest', { tsconfig: '<rootDir>/tsconfig.spec.json' }],
|
||||
},
|
||||
moduleFileExtensions: ['ts', 'js', 'html'],
|
||||
coverageDirectory: '../../../../coverage/libs/web/identity/domain',
|
||||
};
|
||||
9
libs/web/identity/domain/project.json
Normal file
9
libs/web/identity/domain/project.json
Normal file
@@ -0,0 +1,9 @@
|
||||
{
|
||||
"name": "web-identity-domain",
|
||||
"$schema": "../../../../node_modules/nx/schemas/project-schema.json",
|
||||
"sourceRoot": "libs/web/identity/domain/src",
|
||||
"projectType": "library",
|
||||
"tags": ["scope:web-identity", "type:domain"],
|
||||
"// targets": "to see all targets run: nx show project web-identity-domain --web",
|
||||
"targets": {}
|
||||
}
|
||||
2
libs/web/identity/domain/src/index.ts
Normal file
2
libs/web/identity/domain/src/index.ts
Normal file
@@ -0,0 +1,2 @@
|
||||
export * from './lib/session';
|
||||
export * from './lib/ports';
|
||||
41
libs/web/identity/domain/src/lib/ports.ts
Normal file
41
libs/web/identity/domain/src/lib/ports.ts
Normal file
@@ -0,0 +1,41 @@
|
||||
import { Observable } from 'rxjs';
|
||||
import { AuthConfig, CurrentUser, Session } from './session';
|
||||
|
||||
/** The API's sign-in endpoints (/api/auth/*). */
|
||||
export abstract class AuthGateway {
|
||||
abstract config(): Observable<AuthConfig | null>;
|
||||
abstract exchangeCode(
|
||||
code: string,
|
||||
codeVerifier: string,
|
||||
redirectUri: string,
|
||||
): Observable<Session>;
|
||||
abstract password(username: string, password: string): Observable<Session>;
|
||||
abstract refresh(refreshToken: string): Observable<Session>;
|
||||
}
|
||||
|
||||
/** Who the current token belongs to (GraphQL `me`). */
|
||||
export abstract class ProfileGateway {
|
||||
abstract me(accessToken: string): Observable<CurrentUser>;
|
||||
}
|
||||
|
||||
export abstract class SessionStorage {
|
||||
abstract load(): Session | null;
|
||||
abstract save(session: Session): void;
|
||||
abstract clear(): void;
|
||||
}
|
||||
|
||||
export interface AuthorizationResponse {
|
||||
code: string;
|
||||
codeVerifier: string;
|
||||
redirectUri: string;
|
||||
/** Where the user wanted to go before signing in. */
|
||||
returnUrl: string;
|
||||
}
|
||||
|
||||
/** Authorization Code + PKCE in the browser (redirect out and back). */
|
||||
export abstract class AuthorizationFlow {
|
||||
/** Leaves the app towards the identity server's authorize page. */
|
||||
abstract start(config: AuthConfig, returnUrl: string): Promise<void>;
|
||||
/** Validates `state` and returns what is needed to exchange the code. */
|
||||
abstract complete(params: URLSearchParams): AuthorizationResponse;
|
||||
}
|
||||
23
libs/web/identity/domain/src/lib/session.spec.ts
Normal file
23
libs/web/identity/domain/src/lib/session.spec.ts
Normal file
@@ -0,0 +1,23 @@
|
||||
import { isExpired, sessionFrom } from './session';
|
||||
|
||||
describe('session', () => {
|
||||
it('computes the expiry from expires_in', () => {
|
||||
const session = sessionFrom(
|
||||
{ accessToken: 't', refreshToken: 'r', expiresIn: 3600 },
|
||||
1_000,
|
||||
);
|
||||
expect(session).toEqual({
|
||||
accessToken: 't',
|
||||
refreshToken: 'r',
|
||||
expiresAt: 3_601_000,
|
||||
});
|
||||
});
|
||||
|
||||
it('treats tokens about to expire as expired', () => {
|
||||
const session = sessionFrom({ accessToken: 't', expiresIn: 30 }, 0);
|
||||
expect(isExpired(session, 0)).toBe(true);
|
||||
expect(
|
||||
isExpired(sessionFrom({ accessToken: 't', expiresIn: 3600 }, 0), 0),
|
||||
).toBe(false);
|
||||
});
|
||||
});
|
||||
46
libs/web/identity/domain/src/lib/session.ts
Normal file
46
libs/web/identity/domain/src/lib/session.ts
Normal file
@@ -0,0 +1,46 @@
|
||||
/** Tokens issued by Pireon (through the API's /api/auth/token proxy). */
|
||||
export interface Session {
|
||||
accessToken: string;
|
||||
refreshToken: string | null;
|
||||
/** Epoch milliseconds. */
|
||||
expiresAt: number;
|
||||
}
|
||||
|
||||
export interface CurrentUser {
|
||||
id: string;
|
||||
name: string;
|
||||
email: string;
|
||||
appRoles: string[];
|
||||
}
|
||||
|
||||
/** How the browser can sign in (null config = the API has no Pireon client yet). */
|
||||
export interface AuthConfig {
|
||||
authorizeUrl: string;
|
||||
clientId: string;
|
||||
scopes: string[];
|
||||
passwordGrant: boolean;
|
||||
}
|
||||
|
||||
/** Refresh a little before the token actually expires. */
|
||||
export const EXPIRY_MARGIN_MS = 60_000;
|
||||
|
||||
export function isExpired(session: Session, now = Date.now()): boolean {
|
||||
return session.expiresAt - EXPIRY_MARGIN_MS <= now;
|
||||
}
|
||||
|
||||
export function sessionFrom(
|
||||
token: {
|
||||
accessToken: string;
|
||||
refreshToken?: string | null;
|
||||
expiresIn?: number | null;
|
||||
},
|
||||
now = Date.now(),
|
||||
): Session {
|
||||
// Personal access tokens are long-lived and come without expiry: one year.
|
||||
const expiresIn = token.expiresIn ?? 365 * 24 * 3600;
|
||||
return {
|
||||
accessToken: token.accessToken,
|
||||
refreshToken: token.refreshToken ?? null,
|
||||
expiresAt: now + expiresIn * 1000,
|
||||
};
|
||||
}
|
||||
23
libs/web/identity/domain/tsconfig.json
Normal file
23
libs/web/identity/domain/tsconfig.json
Normal file
@@ -0,0 +1,23 @@
|
||||
{
|
||||
"extends": "../../../../tsconfig.base.json",
|
||||
"compilerOptions": {
|
||||
"module": "commonjs",
|
||||
"forceConsistentCasingInFileNames": true,
|
||||
"strict": true,
|
||||
"importHelpers": true,
|
||||
"noImplicitOverride": true,
|
||||
"noImplicitReturns": true,
|
||||
"noFallthroughCasesInSwitch": true,
|
||||
"noPropertyAccessFromIndexSignature": true
|
||||
},
|
||||
"files": [],
|
||||
"include": [],
|
||||
"references": [
|
||||
{
|
||||
"path": "./tsconfig.lib.json"
|
||||
},
|
||||
{
|
||||
"path": "./tsconfig.spec.json"
|
||||
}
|
||||
]
|
||||
}
|
||||
15
libs/web/identity/domain/tsconfig.lib.json
Normal file
15
libs/web/identity/domain/tsconfig.lib.json
Normal file
@@ -0,0 +1,15 @@
|
||||
{
|
||||
"extends": "./tsconfig.json",
|
||||
"compilerOptions": {
|
||||
"outDir": "../../../../dist/out-tsc",
|
||||
"declaration": true,
|
||||
"types": ["node"]
|
||||
},
|
||||
"include": ["src/**/*.ts"],
|
||||
"exclude": [
|
||||
"jest.config.ts",
|
||||
"jest.config.cts",
|
||||
"src/**/*.spec.ts",
|
||||
"src/**/*.test.ts"
|
||||
]
|
||||
}
|
||||
16
libs/web/identity/domain/tsconfig.spec.json
Normal file
16
libs/web/identity/domain/tsconfig.spec.json
Normal file
@@ -0,0 +1,16 @@
|
||||
{
|
||||
"extends": "./tsconfig.json",
|
||||
"compilerOptions": {
|
||||
"outDir": "../../../../dist/out-tsc",
|
||||
"module": "commonjs",
|
||||
"moduleResolution": "bundler",
|
||||
"types": ["jest", "node"]
|
||||
},
|
||||
"include": [
|
||||
"jest.config.ts",
|
||||
"jest.config.cts",
|
||||
"src/**/*.test.ts",
|
||||
"src/**/*.spec.ts",
|
||||
"src/**/*.d.ts"
|
||||
]
|
||||
}
|
||||
21
libs/web/identity/infrastructure/README.md
Normal file
21
libs/web/identity/infrastructure/README.md
Normal file
@@ -0,0 +1,21 @@
|
||||
# web-identity-infrastructure
|
||||
|
||||
Adaptadores de identidad del navegador.
|
||||
|
||||
- **Import**: `@task-stream/web/identity/infrastructure`
|
||||
- **Capa**: `infrastructure` · **Tags**: `scope:web-identity`, `type:infrastructure`
|
||||
|
||||
## Contenido
|
||||
|
||||
- `HttpAuthGateway` (`/api/auth/*`), `GraphqlProfileGateway` (`me`), `LocalSessionStorage`.
|
||||
- `BrowserAuthorizationFlow`: Authorization Code + PKCE con Web Crypto y `state`.
|
||||
- `SessionTokenSource`: conecta el cliente GraphQL con la `AuthFacade`.
|
||||
- `provideIdentityInfrastructure()`.
|
||||
|
||||
## Comandos
|
||||
|
||||
```sh
|
||||
npx nx lint web-identity-infrastructure
|
||||
```
|
||||
|
||||
Reglas de dependencia entre capas: [Arquitectura](../../../../docs/02-arquitectura.md#21-capas-hexagonales).
|
||||
34
libs/web/identity/infrastructure/eslint.config.mjs
Normal file
34
libs/web/identity/infrastructure/eslint.config.mjs
Normal file
@@ -0,0 +1,34 @@
|
||||
import nx from '@nx/eslint-plugin';
|
||||
import baseConfig from '../../../../eslint.config.mjs';
|
||||
|
||||
export default [
|
||||
...nx.configs['flat/angular'],
|
||||
...nx.configs['flat/angular-template'],
|
||||
...baseConfig,
|
||||
{
|
||||
files: ['**/*.ts'],
|
||||
rules: {
|
||||
'@angular-eslint/directive-selector': [
|
||||
'error',
|
||||
{
|
||||
type: 'attribute',
|
||||
prefix: 'ts',
|
||||
style: 'camelCase',
|
||||
},
|
||||
],
|
||||
'@angular-eslint/component-selector': [
|
||||
'error',
|
||||
{
|
||||
type: 'element',
|
||||
prefix: 'ts',
|
||||
style: 'kebab-case',
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
{
|
||||
files: ['**/*.html'],
|
||||
// Override or add rules here
|
||||
rules: {},
|
||||
},
|
||||
];
|
||||
13
libs/web/identity/infrastructure/project.json
Normal file
13
libs/web/identity/infrastructure/project.json
Normal file
@@ -0,0 +1,13 @@
|
||||
{
|
||||
"name": "web-identity-infrastructure",
|
||||
"$schema": "../../../../node_modules/nx/schemas/project-schema.json",
|
||||
"sourceRoot": "libs/web/identity/infrastructure/src",
|
||||
"prefix": "ts",
|
||||
"projectType": "library",
|
||||
"tags": ["scope:web-identity", "type:infrastructure"],
|
||||
"targets": {
|
||||
"lint": {
|
||||
"executor": "@nx/eslint:lint"
|
||||
}
|
||||
}
|
||||
}
|
||||
2
libs/web/identity/infrastructure/src/index.ts
Normal file
2
libs/web/identity/infrastructure/src/index.ts
Normal file
@@ -0,0 +1,2 @@
|
||||
export * from './lib/identity-infrastructure.providers';
|
||||
export { CALLBACK_PATH } from './lib/adapters/browser-authorization.flow';
|
||||
@@ -0,0 +1,90 @@
|
||||
import { DOCUMENT } from '@angular/common';
|
||||
import { inject, Injectable } from '@angular/core';
|
||||
import {
|
||||
AuthConfig,
|
||||
AuthorizationFlow,
|
||||
AuthorizationResponse,
|
||||
} from '@task-stream/web/identity/domain';
|
||||
|
||||
const PENDING_KEY = 'task-stream.pkce';
|
||||
export const CALLBACK_PATH = '/auth/callback';
|
||||
|
||||
interface PendingAuthorization {
|
||||
state: string;
|
||||
codeVerifier: string;
|
||||
returnUrl: string;
|
||||
}
|
||||
|
||||
/** Authorization Code + PKCE (RFC 7636) with the browser's Web Crypto. */
|
||||
@Injectable()
|
||||
export class BrowserAuthorizationFlow extends AuthorizationFlow {
|
||||
private readonly document = inject(DOCUMENT);
|
||||
|
||||
async start(config: AuthConfig, returnUrl: string): Promise<void> {
|
||||
const codeVerifier = randomString(64);
|
||||
const state = randomString(32);
|
||||
sessionStorage.setItem(
|
||||
PENDING_KEY,
|
||||
JSON.stringify({
|
||||
state,
|
||||
codeVerifier,
|
||||
returnUrl,
|
||||
} satisfies PendingAuthorization),
|
||||
);
|
||||
|
||||
const url = new URL(config.authorizeUrl);
|
||||
url.search = new URLSearchParams({
|
||||
client_id: config.clientId,
|
||||
redirect_uri: this.redirectUri(),
|
||||
response_type: 'code',
|
||||
scope: config.scopes.join(' '),
|
||||
state,
|
||||
code_challenge: await challengeOf(codeVerifier),
|
||||
code_challenge_method: 'S256',
|
||||
}).toString();
|
||||
this.document.location.assign(url.toString());
|
||||
}
|
||||
|
||||
complete(params: URLSearchParams): AuthorizationResponse {
|
||||
const raw = sessionStorage.getItem(PENDING_KEY);
|
||||
sessionStorage.removeItem(PENDING_KEY);
|
||||
const pending = raw ? (JSON.parse(raw) as PendingAuthorization) : null;
|
||||
|
||||
const error = params.get('error_description') ?? params.get('error');
|
||||
if (error) throw new Error(error);
|
||||
const code = params.get('code');
|
||||
if (!pending || !code || params.get('state') !== pending.state) {
|
||||
throw new Error(
|
||||
'The sign-in response is invalid or expired. Please try again.',
|
||||
);
|
||||
}
|
||||
return {
|
||||
code,
|
||||
codeVerifier: pending.codeVerifier,
|
||||
redirectUri: this.redirectUri(),
|
||||
returnUrl: pending.returnUrl,
|
||||
};
|
||||
}
|
||||
|
||||
private redirectUri(): string {
|
||||
return `${this.document.location.origin}${CALLBACK_PATH}`;
|
||||
}
|
||||
}
|
||||
|
||||
function randomString(length: number): string {
|
||||
const alphabet =
|
||||
'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~';
|
||||
const bytes = crypto.getRandomValues(new Uint8Array(length));
|
||||
return Array.from(bytes, (b) => alphabet[b % alphabet.length]).join('');
|
||||
}
|
||||
|
||||
async function challengeOf(verifier: string): Promise<string> {
|
||||
const digest = await crypto.subtle.digest(
|
||||
'SHA-256',
|
||||
new TextEncoder().encode(verifier),
|
||||
);
|
||||
return btoa(String.fromCharCode(...new Uint8Array(digest)))
|
||||
.replace(/\+/g, '-')
|
||||
.replace(/\//g, '_')
|
||||
.replace(/=+$/, '');
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
import { HttpClient } from '@angular/common/http';
|
||||
import { inject, Injectable } from '@angular/core';
|
||||
import { API_CONFIG } from '@task-stream/web/shared/infrastructure';
|
||||
import { CurrentUser, ProfileGateway } from '@task-stream/web/identity/domain';
|
||||
import { print } from 'graphql';
|
||||
import { map, Observable } from 'rxjs';
|
||||
import { MeDocument, type MeQuery } from '../graphql/generated';
|
||||
|
||||
/**
|
||||
* `me` with an explicit token: used right after signing in, before the
|
||||
* session is stored, so it does not go through the shared Apollo auth link.
|
||||
*/
|
||||
@Injectable()
|
||||
export class GraphqlProfileGateway extends ProfileGateway {
|
||||
private readonly http = inject(HttpClient);
|
||||
private readonly api = inject(API_CONFIG);
|
||||
private readonly query = print(MeDocument);
|
||||
|
||||
me(accessToken: string): Observable<CurrentUser> {
|
||||
return this.http
|
||||
.post<{
|
||||
data: MeQuery | null;
|
||||
errors?: { message: string }[];
|
||||
}>(
|
||||
this.api.graphqlUrl,
|
||||
{ query: this.query },
|
||||
{ headers: { Authorization: `Bearer ${accessToken}` } },
|
||||
)
|
||||
.pipe(
|
||||
map((response) => {
|
||||
if (!response.data)
|
||||
throw new Error(response.errors?.[0]?.message ?? 'Unauthenticated');
|
||||
return response.data.me;
|
||||
}),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
import { HttpClient } from '@angular/common/http';
|
||||
import { inject, Injectable } from '@angular/core';
|
||||
import { API_CONFIG } from '@task-stream/web/shared/infrastructure';
|
||||
import {
|
||||
AuthConfig,
|
||||
AuthGateway,
|
||||
Session,
|
||||
sessionFrom,
|
||||
} from '@task-stream/web/identity/domain';
|
||||
import { map, Observable } from 'rxjs';
|
||||
|
||||
interface TokenResponse {
|
||||
access_token: string;
|
||||
refresh_token: string | null;
|
||||
expires_in: number;
|
||||
}
|
||||
|
||||
/** The API's sign-in proxy to Pireon (/api/auth/*). */
|
||||
@Injectable()
|
||||
export class HttpAuthGateway extends AuthGateway {
|
||||
private readonly http = inject(HttpClient);
|
||||
private readonly api = inject(API_CONFIG);
|
||||
|
||||
config(): Observable<AuthConfig | null> {
|
||||
return this.http.get<AuthConfig | null>(`${this.api.restUrl}/auth/config`);
|
||||
}
|
||||
|
||||
exchangeCode(
|
||||
code: string,
|
||||
codeVerifier: string,
|
||||
redirectUri: string,
|
||||
): Observable<Session> {
|
||||
return this.token({
|
||||
grant_type: 'authorization_code',
|
||||
code,
|
||||
code_verifier: codeVerifier,
|
||||
redirect_uri: redirectUri,
|
||||
});
|
||||
}
|
||||
|
||||
password(username: string, password: string): Observable<Session> {
|
||||
return this.token({ grant_type: 'password', username, password });
|
||||
}
|
||||
|
||||
refresh(refreshToken: string): Observable<Session> {
|
||||
return this.token({
|
||||
grant_type: 'refresh_token',
|
||||
refresh_token: refreshToken,
|
||||
});
|
||||
}
|
||||
|
||||
private token(body: Record<string, string>): Observable<Session> {
|
||||
return this.http
|
||||
.post<TokenResponse>(`${this.api.restUrl}/auth/token`, body)
|
||||
.pipe(
|
||||
map((token) =>
|
||||
sessionFrom({
|
||||
accessToken: token.access_token,
|
||||
refreshToken: token.refresh_token,
|
||||
expiresIn: token.expires_in,
|
||||
}),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
import { Injectable } from '@angular/core';
|
||||
import { Session, SessionStorage } from '@task-stream/web/identity/domain';
|
||||
|
||||
const KEY = 'task-stream.session';
|
||||
|
||||
@Injectable()
|
||||
export class LocalSessionStorage extends SessionStorage {
|
||||
load(): Session | null {
|
||||
try {
|
||||
const raw = localStorage.getItem(KEY);
|
||||
return raw ? (JSON.parse(raw) as Session) : null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
save(session: Session): void {
|
||||
try {
|
||||
localStorage.setItem(KEY, JSON.stringify(session));
|
||||
} catch {
|
||||
// Private browsing / storage disabled: the session lasts this tab only.
|
||||
}
|
||||
}
|
||||
|
||||
clear(): void {
|
||||
try {
|
||||
localStorage.removeItem(KEY);
|
||||
} catch {
|
||||
// Nothing to clear.
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
import { inject, Injectable } from '@angular/core';
|
||||
import { AccessTokenSource } from '@task-stream/web/shared/infrastructure';
|
||||
import { AuthFacade } from '@task-stream/web/identity/application';
|
||||
|
||||
/** Gives the shared GraphQL client the session's token (refreshing it when needed). */
|
||||
@Injectable()
|
||||
export class SessionTokenSource extends AccessTokenSource {
|
||||
private readonly auth = inject(AuthFacade);
|
||||
|
||||
accessToken(): Promise<string | null> {
|
||||
return this.auth.validAccessToken();
|
||||
}
|
||||
|
||||
unauthenticated(): void {
|
||||
this.auth.expire();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
/** Internal type. DO NOT USE DIRECTLY. */
|
||||
type Exact<T extends { [key: string]: unknown }> = { [K in keyof T]: T[K] };
|
||||
/** Internal type. DO NOT USE DIRECTLY. */
|
||||
export type Incremental<T> =
|
||||
| T
|
||||
| {
|
||||
[P in keyof T]?: P extends ' $fragmentName' | '__typename' ? T[P] : never;
|
||||
};
|
||||
import type { TypedDocumentNode as DocumentNode } from '@graphql-typed-document-node/core';
|
||||
export type MeQueryVariables = Exact<{ [key: string]: never }>;
|
||||
|
||||
export type MeQuery = {
|
||||
me: { id: string; name: string; email: string; appRoles: Array<string> };
|
||||
};
|
||||
|
||||
export const MeDocument = {
|
||||
kind: 'Document',
|
||||
definitions: [
|
||||
{
|
||||
kind: 'OperationDefinition',
|
||||
operation: 'query',
|
||||
name: { kind: 'Name', value: 'Me' },
|
||||
selectionSet: {
|
||||
kind: 'SelectionSet',
|
||||
selections: [
|
||||
{
|
||||
kind: 'Field',
|
||||
name: { kind: 'Name', value: 'me' },
|
||||
selectionSet: {
|
||||
kind: 'SelectionSet',
|
||||
selections: [
|
||||
{ kind: 'Field', name: { kind: 'Name', value: 'id' } },
|
||||
{ kind: 'Field', name: { kind: 'Name', value: 'name' } },
|
||||
{ kind: 'Field', name: { kind: 'Name', value: 'email' } },
|
||||
{ kind: 'Field', name: { kind: 'Name', value: 'appRoles' } },
|
||||
],
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
],
|
||||
} as unknown as DocumentNode<MeQuery, MeQueryVariables>;
|
||||
@@ -0,0 +1,8 @@
|
||||
query Me {
|
||||
me {
|
||||
id
|
||||
name
|
||||
email
|
||||
appRoles
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
import {
|
||||
makeEnvironmentProviders,
|
||||
type EnvironmentProviders,
|
||||
} from '@angular/core';
|
||||
import {
|
||||
AuthGateway,
|
||||
AuthorizationFlow,
|
||||
ProfileGateway,
|
||||
SessionStorage,
|
||||
} from '@task-stream/web/identity/domain';
|
||||
import { AccessTokenSource } from '@task-stream/web/shared/infrastructure';
|
||||
import { SessionTokenSource } from './adapters/session.token-source';
|
||||
import { BrowserAuthorizationFlow } from './adapters/browser-authorization.flow';
|
||||
import { GraphqlProfileGateway } from './adapters/graphql-profile.gateway';
|
||||
import { HttpAuthGateway } from './adapters/http-auth.gateway';
|
||||
import { LocalSessionStorage } from './adapters/local-session.storage';
|
||||
|
||||
export function provideIdentityInfrastructure(): EnvironmentProviders {
|
||||
return makeEnvironmentProviders([
|
||||
{ provide: AuthGateway, useClass: HttpAuthGateway },
|
||||
{ provide: ProfileGateway, useClass: GraphqlProfileGateway },
|
||||
{ provide: SessionStorage, useClass: LocalSessionStorage },
|
||||
{ provide: AuthorizationFlow, useClass: BrowserAuthorizationFlow },
|
||||
{ provide: AccessTokenSource, useClass: SessionTokenSource },
|
||||
]);
|
||||
}
|
||||
27
libs/web/identity/infrastructure/tsconfig.json
Normal file
27
libs/web/identity/infrastructure/tsconfig.json
Normal file
@@ -0,0 +1,27 @@
|
||||
{
|
||||
"extends": "../../../../tsconfig.base.json",
|
||||
"compilerOptions": {
|
||||
"isolatedModules": true,
|
||||
"target": "es2022",
|
||||
"strict": true,
|
||||
"noImplicitOverride": true,
|
||||
"noPropertyAccessFromIndexSignature": true,
|
||||
"noImplicitReturns": true,
|
||||
"noFallthroughCasesInSwitch": true,
|
||||
"emitDecoratorMetadata": false,
|
||||
"module": "preserve"
|
||||
},
|
||||
"angularCompilerOptions": {
|
||||
"enableI18nLegacyMessageIdFormat": false,
|
||||
"strictInjectionParameters": true,
|
||||
"strictInputAccessModifiers": true,
|
||||
"strictTemplates": true
|
||||
},
|
||||
"files": [],
|
||||
"include": [],
|
||||
"references": [
|
||||
{
|
||||
"path": "./tsconfig.lib.json"
|
||||
}
|
||||
]
|
||||
}
|
||||
12
libs/web/identity/infrastructure/tsconfig.lib.json
Normal file
12
libs/web/identity/infrastructure/tsconfig.lib.json
Normal file
@@ -0,0 +1,12 @@
|
||||
{
|
||||
"extends": "./tsconfig.json",
|
||||
"compilerOptions": {
|
||||
"outDir": "../../../../dist/out-tsc",
|
||||
"declaration": true,
|
||||
"declarationMap": true,
|
||||
"inlineSources": true,
|
||||
"types": []
|
||||
},
|
||||
"include": ["src/**/*.ts"],
|
||||
"exclude": ["src/**/*.spec.ts", "src/**/*.test.ts"]
|
||||
}
|
||||
19
libs/web/identity/presenters/README.md
Normal file
19
libs/web/identity/presenters/README.md
Normal file
@@ -0,0 +1,19 @@
|
||||
# web-identity-presenters
|
||||
|
||||
Pantallas y guards de identidad.
|
||||
|
||||
- **Import**: `@task-stream/web/identity/presenters`
|
||||
- **Capa**: `presenters` · **Tags**: `scope:web-identity`, `type:presenters`
|
||||
|
||||
## Contenido
|
||||
|
||||
- Rutas `identityRoutes`: `/login` y `/auth/callback`.
|
||||
- `authGuard`, `guestGuard` y `UserMenuComponent`.
|
||||
|
||||
## Comandos
|
||||
|
||||
```sh
|
||||
npx nx lint web-identity-presenters
|
||||
```
|
||||
|
||||
Reglas de dependencia entre capas: [Arquitectura](../../../../docs/02-arquitectura.md#21-capas-hexagonales).
|
||||
34
libs/web/identity/presenters/eslint.config.mjs
Normal file
34
libs/web/identity/presenters/eslint.config.mjs
Normal file
@@ -0,0 +1,34 @@
|
||||
import nx from '@nx/eslint-plugin';
|
||||
import baseConfig from '../../../../eslint.config.mjs';
|
||||
|
||||
export default [
|
||||
...nx.configs['flat/angular'],
|
||||
...nx.configs['flat/angular-template'],
|
||||
...baseConfig,
|
||||
{
|
||||
files: ['**/*.ts'],
|
||||
rules: {
|
||||
'@angular-eslint/directive-selector': [
|
||||
'error',
|
||||
{
|
||||
type: 'attribute',
|
||||
prefix: 'ts',
|
||||
style: 'camelCase',
|
||||
},
|
||||
],
|
||||
'@angular-eslint/component-selector': [
|
||||
'error',
|
||||
{
|
||||
type: 'element',
|
||||
prefix: 'ts',
|
||||
style: 'kebab-case',
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
{
|
||||
files: ['**/*.html'],
|
||||
// Override or add rules here
|
||||
rules: {},
|
||||
},
|
||||
];
|
||||
13
libs/web/identity/presenters/project.json
Normal file
13
libs/web/identity/presenters/project.json
Normal file
@@ -0,0 +1,13 @@
|
||||
{
|
||||
"name": "web-identity-presenters",
|
||||
"$schema": "../../../../node_modules/nx/schemas/project-schema.json",
|
||||
"sourceRoot": "libs/web/identity/presenters/src",
|
||||
"prefix": "ts",
|
||||
"projectType": "library",
|
||||
"tags": ["scope:web-identity", "type:presenters"],
|
||||
"targets": {
|
||||
"lint": {
|
||||
"executor": "@nx/eslint:lint"
|
||||
}
|
||||
}
|
||||
}
|
||||
3
libs/web/identity/presenters/src/index.ts
Normal file
3
libs/web/identity/presenters/src/index.ts
Normal file
@@ -0,0 +1,3 @@
|
||||
export * from './lib/guards';
|
||||
export * from './lib/identity.routes';
|
||||
export * from './lib/components/user-menu';
|
||||
74
libs/web/identity/presenters/src/lib/components/user-menu.ts
Normal file
74
libs/web/identity/presenters/src/lib/components/user-menu.ts
Normal file
@@ -0,0 +1,74 @@
|
||||
import { ChangeDetectionStrategy, Component, inject } from '@angular/core';
|
||||
import { PiIconComponent } from '@pi/ui';
|
||||
import { AuthFacade } from '@task-stream/web/identity/application';
|
||||
|
||||
/** Signed-in user in the header: initials, name, sign out. */
|
||||
@Component({
|
||||
selector: 'ts-user-menu',
|
||||
changeDetection: ChangeDetectionStrategy.OnPush,
|
||||
imports: [PiIconComponent],
|
||||
template: `
|
||||
@if (auth.user(); as user) {
|
||||
<div class="ts-user" [title]="user.email">
|
||||
<span class="ts-user__avatar" aria-hidden="true">{{
|
||||
auth.initials()
|
||||
}}</span>
|
||||
<span class="ts-user__name">{{ user.name }}</span>
|
||||
<button
|
||||
type="button"
|
||||
class="ts-icon-button ts-user__out"
|
||||
aria-label="Cerrar sesión"
|
||||
title="Cerrar sesión"
|
||||
(click)="auth.signOut()"
|
||||
>
|
||||
<pi-icon icon="logout" size="small" />
|
||||
</button>
|
||||
</div>
|
||||
}
|
||||
`,
|
||||
styles: `
|
||||
.ts-user {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.5rem;
|
||||
padding: 0.1875rem;
|
||||
border: 1px solid var(--ts-line);
|
||||
border-radius: 999px;
|
||||
background: var(--ts-surface);
|
||||
}
|
||||
.ts-user__avatar {
|
||||
display: inline-grid;
|
||||
place-items: center;
|
||||
width: 1.875rem;
|
||||
height: 1.875rem;
|
||||
border-radius: 50%;
|
||||
background: linear-gradient(
|
||||
135deg,
|
||||
var(--pi-color-primary),
|
||||
var(--pi-color-accent)
|
||||
);
|
||||
color: #fff;
|
||||
font-size: 0.6875rem;
|
||||
font-weight: 700;
|
||||
}
|
||||
.ts-user__name {
|
||||
font-size: 0.875rem;
|
||||
font-weight: 600;
|
||||
white-space: nowrap;
|
||||
@media (max-width: 640px) {
|
||||
display: none;
|
||||
}
|
||||
}
|
||||
.ts-user__out {
|
||||
--ts-icon-button-size: 1.875rem;
|
||||
color: var(--ts-muted);
|
||||
&:hover {
|
||||
color: var(--ts-ink);
|
||||
background: var(--pi-color-primary-25);
|
||||
}
|
||||
}
|
||||
`,
|
||||
})
|
||||
export class UserMenuComponent {
|
||||
protected readonly auth = inject(AuthFacade);
|
||||
}
|
||||
37
libs/web/identity/presenters/src/lib/guards.ts
Normal file
37
libs/web/identity/presenters/src/lib/guards.ts
Normal file
@@ -0,0 +1,37 @@
|
||||
import { inject } from '@angular/core';
|
||||
import { toObservable } from '@angular/core/rxjs-interop';
|
||||
import { CanActivateFn, Router } from '@angular/router';
|
||||
import { AuthFacade } from '@task-stream/web/identity/application';
|
||||
import { filter, map, take } from 'rxjs';
|
||||
|
||||
/** Waits for the stored session to be restored before deciding. */
|
||||
function whenSettled() {
|
||||
const auth = inject(AuthFacade);
|
||||
return toObservable(auth.settled).pipe(
|
||||
filter(Boolean),
|
||||
take(1),
|
||||
map(() => auth.isAuthenticated()),
|
||||
);
|
||||
}
|
||||
|
||||
export const authGuard: CanActivateFn = (_route, state) => {
|
||||
const router = inject(Router);
|
||||
return whenSettled().pipe(
|
||||
map((authenticated) =>
|
||||
authenticated
|
||||
? true
|
||||
: router.createUrlTree(['/login'], {
|
||||
queryParams: { returnUrl: state.url },
|
||||
}),
|
||||
),
|
||||
);
|
||||
};
|
||||
|
||||
export const guestGuard: CanActivateFn = () => {
|
||||
const router = inject(Router);
|
||||
return whenSettled().pipe(
|
||||
map((authenticated) =>
|
||||
authenticated ? router.createUrlTree(['/']) : true,
|
||||
),
|
||||
);
|
||||
};
|
||||
18
libs/web/identity/presenters/src/lib/identity.routes.ts
Normal file
18
libs/web/identity/presenters/src/lib/identity.routes.ts
Normal file
@@ -0,0 +1,18 @@
|
||||
import { Routes } from '@angular/router';
|
||||
import { guestGuard } from './guards';
|
||||
|
||||
/** /login and /auth/callback (the Pireon redirect URI). */
|
||||
export const identityRoutes: Routes = [
|
||||
{
|
||||
path: 'login',
|
||||
canActivate: [guestGuard],
|
||||
title: 'Entrar · TaskStream',
|
||||
loadComponent: () => import('./pages/login.page').then((m) => m.LoginPage),
|
||||
},
|
||||
{
|
||||
path: 'auth/callback',
|
||||
title: 'Entrando · TaskStream',
|
||||
loadComponent: () =>
|
||||
import('./pages/callback.page').then((m) => m.CallbackPage),
|
||||
},
|
||||
];
|
||||
43
libs/web/identity/presenters/src/lib/pages/callback.page.ts
Normal file
43
libs/web/identity/presenters/src/lib/pages/callback.page.ts
Normal file
@@ -0,0 +1,43 @@
|
||||
import {
|
||||
ChangeDetectionStrategy,
|
||||
Component,
|
||||
inject,
|
||||
OnInit,
|
||||
} from '@angular/core';
|
||||
import { DOCUMENT } from '@angular/common';
|
||||
import { RouterLink } from '@angular/router';
|
||||
import { PiNoteComponent, PiSpinnerComponent } from '@pi/ui';
|
||||
import { AuthFacade } from '@task-stream/web/identity/application';
|
||||
|
||||
/** Where Pireon sends the user back with `?code=…&state=…`. */
|
||||
@Component({
|
||||
selector: 'ts-callback-page',
|
||||
changeDetection: ChangeDetectionStrategy.OnPush,
|
||||
imports: [RouterLink, PiSpinnerComponent, PiNoteComponent],
|
||||
template: `
|
||||
<div style="display:grid;justify-items:center;gap:1rem;padding-top:15vh">
|
||||
@if (auth.error(); as error) {
|
||||
<pi-note
|
||||
gap="xs"
|
||||
status="error"
|
||||
appearance="fill"
|
||||
type="status"
|
||||
title="No se pudo iniciar sesión"
|
||||
[text]="error"
|
||||
/>
|
||||
<a routerLink="/login">Volver a intentarlo</a>
|
||||
} @else {
|
||||
<pi-spinner [isLoading]="true" [diameter]="48" />
|
||||
<p>Completando el inicio de sesión…</p>
|
||||
}
|
||||
</div>
|
||||
`,
|
||||
})
|
||||
export class CallbackPage implements OnInit {
|
||||
protected readonly auth = inject(AuthFacade);
|
||||
private readonly document = inject(DOCUMENT);
|
||||
|
||||
ngOnInit(): void {
|
||||
this.auth.completeSignIn(this.document.location.search);
|
||||
}
|
||||
}
|
||||
194
libs/web/identity/presenters/src/lib/pages/login.page.scss
Normal file
194
libs/web/identity/presenters/src/lib/pages/login.page.scss
Normal file
@@ -0,0 +1,194 @@
|
||||
// Two columns: the product's pitch over a live-looking event stream, and the
|
||||
// sign-in card. Stacks on small screens (card first).
|
||||
.ts-login {
|
||||
display: grid;
|
||||
grid-template-columns: minmax(0, 1.15fr) minmax(0, 26rem);
|
||||
align-items: center;
|
||||
gap: clamp(2rem, 5vw, 5rem);
|
||||
min-height: calc(100vh - 12rem);
|
||||
max-width: 72rem;
|
||||
margin-inline: auto;
|
||||
|
||||
@media (max-width: 900px) {
|
||||
grid-template-columns: minmax(0, 1fr);
|
||||
min-height: 0;
|
||||
|
||||
.ts-login__card {
|
||||
order: -1;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.ts-login__intro {
|
||||
min-width: 0;
|
||||
|
||||
// Same scale as pireon.dev's hero title.
|
||||
h1 {
|
||||
margin: 0 0 1.25rem;
|
||||
font-size: clamp(2.25rem, 6vw, 3.75rem);
|
||||
font-weight: 700;
|
||||
line-height: 1.08;
|
||||
letter-spacing: -0.02em;
|
||||
}
|
||||
}
|
||||
|
||||
.ts-login__eyebrow {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 0.625rem;
|
||||
margin-bottom: 0.75rem;
|
||||
}
|
||||
|
||||
.ts-login__live {
|
||||
width: 0.5rem;
|
||||
height: 0.5rem;
|
||||
border-radius: 50%;
|
||||
background: var(--ts-s-done);
|
||||
box-shadow: 0 0 0 0 color-mix(in srgb, var(--ts-s-done) 60%, transparent);
|
||||
animation: ts-pulse 2s ease-out infinite;
|
||||
}
|
||||
|
||||
@keyframes ts-pulse {
|
||||
70% {
|
||||
box-shadow: 0 0 0 0.5rem transparent;
|
||||
}
|
||||
100% {
|
||||
box-shadow: 0 0 0 0 transparent;
|
||||
}
|
||||
}
|
||||
|
||||
.ts-login__lead {
|
||||
max-width: 46ch;
|
||||
margin: 0 0 2.25rem;
|
||||
font-size: 1.0625rem;
|
||||
line-height: 1.55;
|
||||
color: var(--ts-muted);
|
||||
}
|
||||
|
||||
// Event stream: a Pireon card scrolling upwards, faded at both ends.
|
||||
.ts-feed {
|
||||
height: 15.5rem;
|
||||
overflow: hidden;
|
||||
mask-image: linear-gradient(transparent, #000 18%, #000 82%, transparent);
|
||||
|
||||
@media (max-width: 900px) {
|
||||
height: 9.5rem;
|
||||
}
|
||||
}
|
||||
|
||||
.ts-feed__track {
|
||||
display: grid;
|
||||
animation: ts-scroll 22s linear infinite;
|
||||
}
|
||||
|
||||
@keyframes ts-scroll {
|
||||
to {
|
||||
transform: translateY(-50%);
|
||||
}
|
||||
}
|
||||
|
||||
.ts-feed__row {
|
||||
display: grid;
|
||||
grid-template-columns: 3rem 4.25rem minmax(0, 1fr) auto;
|
||||
align-items: center;
|
||||
gap: 0.75rem;
|
||||
padding: 0.625rem 1.125rem;
|
||||
border-bottom: 1px dashed var(--ts-line);
|
||||
font-family: var(--ts-font-mono);
|
||||
font-size: 0.8125rem;
|
||||
|
||||
@media (max-width: 520px) {
|
||||
grid-template-columns: 2.75rem 3.75rem minmax(0, 1fr);
|
||||
gap: 0.5rem;
|
||||
padding-inline: 0.875rem;
|
||||
|
||||
.ts-feed__from,
|
||||
.ts-feed__arrow,
|
||||
.ts-feed__who {
|
||||
display: none;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.ts-feed__time,
|
||||
.ts-feed__who {
|
||||
color: var(--ts-muted);
|
||||
}
|
||||
|
||||
.ts-feed__key {
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.ts-feed__move {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.5rem;
|
||||
min-width: 0;
|
||||
white-space: nowrap;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.ts-feed__from {
|
||||
color: var(--ts-muted);
|
||||
}
|
||||
|
||||
.ts-feed__arrow {
|
||||
color: var(--ts-line-strong);
|
||||
}
|
||||
|
||||
.ts-feed__to {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 0.375rem;
|
||||
font-weight: 600;
|
||||
color: color-mix(in srgb, var(--tone) 85%, var(--ts-ink));
|
||||
|
||||
&::before {
|
||||
content: '';
|
||||
width: 0.4375rem;
|
||||
height: 0.4375rem;
|
||||
border-radius: 50%;
|
||||
background: var(--tone);
|
||||
}
|
||||
}
|
||||
|
||||
// Sign-in card (a Pireon card)
|
||||
.ts-login__card {
|
||||
padding: 2rem;
|
||||
box-shadow: var(--ts-lift);
|
||||
|
||||
@media (max-width: 480px) {
|
||||
padding: 1.5rem 1.25rem;
|
||||
}
|
||||
}
|
||||
|
||||
.ts-login__card-head {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.875rem;
|
||||
margin-bottom: 1.75rem;
|
||||
|
||||
h2 {
|
||||
margin: 0;
|
||||
font-size: 1.5rem;
|
||||
font-weight: 700;
|
||||
}
|
||||
|
||||
p {
|
||||
margin: 0.125rem 0 0;
|
||||
color: var(--ts-muted);
|
||||
font-size: 0.875rem;
|
||||
}
|
||||
}
|
||||
|
||||
.ts-login__content,
|
||||
.ts-login__form {
|
||||
display: grid;
|
||||
gap: 1.25rem;
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
// The field's label sits above its outline: leave room after the previous field's error.
|
||||
.ts-login__form {
|
||||
row-gap: 1.75rem;
|
||||
}
|
||||
276
libs/web/identity/presenters/src/lib/pages/login.page.ts
Normal file
276
libs/web/identity/presenters/src/lib/pages/login.page.ts
Normal file
@@ -0,0 +1,276 @@
|
||||
import {
|
||||
ChangeDetectionStrategy,
|
||||
Component,
|
||||
computed,
|
||||
inject,
|
||||
input,
|
||||
OnInit,
|
||||
signal,
|
||||
} from '@angular/core';
|
||||
import { emailError, requiredError } from '@angular/forms/signals';
|
||||
import {
|
||||
PiActionButtonComponent,
|
||||
PiDividerComponent,
|
||||
PiEmailFieldComponent,
|
||||
PiLabelDirective,
|
||||
PiNoteComponent,
|
||||
PiPasswordFieldComponent,
|
||||
} from '@pi/ui';
|
||||
import { AuthFacade } from '@task-stream/web/identity/application';
|
||||
import { LogoComponent } from '@task-stream/web/shared/ui';
|
||||
|
||||
const EMAIL = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
|
||||
|
||||
/** Illustrative events for the welcome panel (decorative, not real data). */
|
||||
const SAMPLE_FEED = [
|
||||
{
|
||||
time: '09:41',
|
||||
key: 'WEB-12',
|
||||
from: 'En QA',
|
||||
to: 'Hecho',
|
||||
tone: 'done',
|
||||
who: 'Quinn',
|
||||
},
|
||||
{
|
||||
time: '09:38',
|
||||
key: 'API-7',
|
||||
from: 'En curso',
|
||||
to: 'En revisión',
|
||||
tone: 'review',
|
||||
who: 'Dan',
|
||||
},
|
||||
{
|
||||
time: '09:35',
|
||||
key: 'WEB-14',
|
||||
from: 'En QA',
|
||||
to: 'QA fallido',
|
||||
tone: 'failed',
|
||||
who: 'Quinn',
|
||||
},
|
||||
{
|
||||
time: '09:31',
|
||||
key: 'MOB-3',
|
||||
from: 'Por hacer',
|
||||
to: 'En curso',
|
||||
tone: 'progress',
|
||||
who: 'Bob',
|
||||
},
|
||||
{
|
||||
time: '09:27',
|
||||
key: 'WEB-9',
|
||||
from: 'En revisión',
|
||||
to: 'Listo para QA',
|
||||
tone: 'ready',
|
||||
who: 'Ana',
|
||||
},
|
||||
{
|
||||
time: '09:22',
|
||||
key: 'API-4',
|
||||
from: 'Listo para QA',
|
||||
to: 'En QA',
|
||||
tone: 'qa',
|
||||
who: 'Quinn',
|
||||
},
|
||||
{
|
||||
time: '09:18',
|
||||
key: 'WEB-3',
|
||||
from: 'Backlog',
|
||||
to: 'Por hacer',
|
||||
tone: 'todo',
|
||||
who: 'Ana',
|
||||
},
|
||||
];
|
||||
|
||||
@Component({
|
||||
selector: 'ts-login-page',
|
||||
changeDetection: ChangeDetectionStrategy.OnPush,
|
||||
imports: [
|
||||
LogoComponent,
|
||||
PiActionButtonComponent,
|
||||
PiDividerComponent,
|
||||
PiEmailFieldComponent,
|
||||
PiPasswordFieldComponent,
|
||||
PiLabelDirective,
|
||||
PiNoteComponent,
|
||||
],
|
||||
styleUrl: './login.page.scss',
|
||||
template: `
|
||||
<section class="ts-login">
|
||||
<div class="ts-login__intro">
|
||||
<p class="ts-eyebrow ts-login__eyebrow">
|
||||
<span class="ts-login__live"></span> Pireon · TaskStream
|
||||
</p>
|
||||
<h1>
|
||||
Cada cambio,<br /><span class="ts-gradient-text"
|
||||
>en cuanto pasa.</span
|
||||
>
|
||||
</h1>
|
||||
<p class="ts-login__lead">
|
||||
Bugs, cambios de UI, features y QA de tu equipo en un tablero que se
|
||||
mueve solo. Front, back y QA, enlazados de punta a punta.
|
||||
</p>
|
||||
<div class="ts-feed ts-panel" aria-hidden="true">
|
||||
<div class="ts-feed__track">
|
||||
@for (event of feed; track $index) {
|
||||
<div
|
||||
class="ts-feed__row"
|
||||
[style.--tone]="'var(--ts-s-' + event.tone + ')'"
|
||||
>
|
||||
<span class="ts-feed__time">{{ event.time }}</span>
|
||||
<span class="ts-feed__key">{{ event.key }}</span>
|
||||
<span class="ts-feed__move">
|
||||
<span class="ts-feed__from">{{ event.from }}</span>
|
||||
<span class="ts-feed__arrow">→</span>
|
||||
<span class="ts-feed__to">{{ event.to }}</span>
|
||||
</span>
|
||||
<span class="ts-feed__who">{{ event.who }}</span>
|
||||
</div>
|
||||
}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="ts-login__card ts-panel">
|
||||
<div class="ts-login__card-head">
|
||||
<ts-logo [size]="40" />
|
||||
<div>
|
||||
<h2>Entrar</h2>
|
||||
<p>Con tu cuenta de Pireon.</p>
|
||||
</div>
|
||||
</div>
|
||||
<div class="ts-login__content">
|
||||
@if (!configured()) {
|
||||
<pi-note
|
||||
gap="xs"
|
||||
flexDirection="column"
|
||||
alignment="flex-start"
|
||||
status="info"
|
||||
appearance="fill"
|
||||
type="status"
|
||||
title="Inicio de sesión no configurado"
|
||||
text="La API necesita un cliente OAuth de Pireon: PIREON_CLIENT_ID y PIREON_CLIENT_SECRET en .env."
|
||||
/>
|
||||
} @else if (auth.error(); as error) {
|
||||
<pi-note
|
||||
gap="xs"
|
||||
flexDirection="column"
|
||||
alignment="flex-start"
|
||||
status="error"
|
||||
appearance="fill"
|
||||
type="status"
|
||||
title="No se pudo iniciar sesión"
|
||||
[text]="error"
|
||||
/>
|
||||
}
|
||||
|
||||
@if (auth.config(); as config) {
|
||||
<pi-action-button
|
||||
size="w100"
|
||||
color="primary"
|
||||
text="Entrar con Pireon"
|
||||
[hasIcon]="true"
|
||||
[disabled]="busy()"
|
||||
(execute)="auth.signInWithPireon(returnUrl())"
|
||||
/>
|
||||
@if (config.passwordGrant) {
|
||||
<pi-divider color="grey" label="o" gap="m" />
|
||||
}
|
||||
}
|
||||
|
||||
@if (passwordEnabled()) {
|
||||
<form
|
||||
class="ts-login__form"
|
||||
(submit)="$event.preventDefault(); signIn()"
|
||||
novalidate
|
||||
>
|
||||
<pi-email-field
|
||||
name="email"
|
||||
placeholder="tu@email.com"
|
||||
[required]="true"
|
||||
[disabled]="busy()"
|
||||
[errors]="emailErrors()"
|
||||
[(value)]="email"
|
||||
(touch)="emailTouched.set(true)"
|
||||
>
|
||||
<pi-label [isRequired]="true">Email de Pireon</pi-label>
|
||||
</pi-email-field>
|
||||
<pi-password-field
|
||||
name="password"
|
||||
placeholder="Contraseña"
|
||||
[required]="true"
|
||||
[disabled]="busy()"
|
||||
[errors]="passwordErrors()"
|
||||
[(value)]="password"
|
||||
(touch)="passwordTouched.set(true)"
|
||||
>
|
||||
<pi-label [isRequired]="true">Contraseña</pi-label>
|
||||
</pi-password-field>
|
||||
<pi-action-button
|
||||
size="w100"
|
||||
color="primary"
|
||||
[text]="busy() ? 'Entrando…' : 'Entrar'"
|
||||
[hasIcon]="!busy()"
|
||||
[disabled]="busy() || !configured()"
|
||||
(execute)="signIn()"
|
||||
/>
|
||||
</form>
|
||||
}
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
`,
|
||||
})
|
||||
export class LoginPage implements OnInit {
|
||||
/** Bound from the query string by the router (withComponentInputBinding). */
|
||||
readonly returnUrl = input<string>('/');
|
||||
|
||||
protected readonly auth = inject(AuthFacade);
|
||||
/** Twice, so the vertical marquee loops without a jump. */
|
||||
protected readonly feed = [...SAMPLE_FEED, ...SAMPLE_FEED];
|
||||
protected readonly busy = this.auth.signingIn;
|
||||
/** Email and password go to Pireon through the API (password grant). */
|
||||
/** null = the API has no Pireon client: nobody can sign in yet. */
|
||||
protected readonly configured = computed(() => this.auth.config() !== null);
|
||||
protected readonly passwordEnabled = computed(
|
||||
() => this.auth.config()?.passwordGrant !== false,
|
||||
);
|
||||
|
||||
protected readonly email = signal('');
|
||||
protected readonly password = signal('');
|
||||
// Errors show once the user leaves a field or tries to sign in, not on load
|
||||
// (`@pi/ui` fields paint any error they receive, touched or not).
|
||||
protected readonly emailTouched = signal(false);
|
||||
protected readonly passwordTouched = signal(false);
|
||||
|
||||
private readonly emailProblems = computed(() => {
|
||||
const value = this.email().trim();
|
||||
if (!value) return [requiredError()];
|
||||
return EMAIL.test(value) ? [] : [emailError()];
|
||||
});
|
||||
private readonly passwordProblems = computed(() =>
|
||||
this.password() ? [] : [requiredError()],
|
||||
);
|
||||
protected readonly emailErrors = computed(() =>
|
||||
this.emailTouched() ? this.emailProblems() : [],
|
||||
);
|
||||
protected readonly passwordErrors = computed(() =>
|
||||
this.passwordTouched() ? this.passwordProblems() : [],
|
||||
);
|
||||
|
||||
ngOnInit(): void {
|
||||
this.auth.openSignIn();
|
||||
}
|
||||
|
||||
protected signIn(): void {
|
||||
this.emailTouched.set(true);
|
||||
this.passwordTouched.set(true);
|
||||
const invalid =
|
||||
this.emailProblems().length > 0 || this.passwordProblems().length > 0;
|
||||
if (invalid || this.busy() || !this.configured()) return;
|
||||
this.auth.signInWithPassword(
|
||||
this.email().trim(),
|
||||
this.password(),
|
||||
this.returnUrl(),
|
||||
);
|
||||
}
|
||||
}
|
||||
27
libs/web/identity/presenters/tsconfig.json
Normal file
27
libs/web/identity/presenters/tsconfig.json
Normal file
@@ -0,0 +1,27 @@
|
||||
{
|
||||
"extends": "../../../../tsconfig.base.json",
|
||||
"compilerOptions": {
|
||||
"isolatedModules": true,
|
||||
"target": "es2022",
|
||||
"strict": true,
|
||||
"noImplicitOverride": true,
|
||||
"noPropertyAccessFromIndexSignature": true,
|
||||
"noImplicitReturns": true,
|
||||
"noFallthroughCasesInSwitch": true,
|
||||
"emitDecoratorMetadata": false,
|
||||
"module": "preserve"
|
||||
},
|
||||
"angularCompilerOptions": {
|
||||
"enableI18nLegacyMessageIdFormat": false,
|
||||
"strictInjectionParameters": true,
|
||||
"strictInputAccessModifiers": true,
|
||||
"strictTemplates": true
|
||||
},
|
||||
"files": [],
|
||||
"include": [],
|
||||
"references": [
|
||||
{
|
||||
"path": "./tsconfig.lib.json"
|
||||
}
|
||||
]
|
||||
}
|
||||
12
libs/web/identity/presenters/tsconfig.lib.json
Normal file
12
libs/web/identity/presenters/tsconfig.lib.json
Normal file
@@ -0,0 +1,12 @@
|
||||
{
|
||||
"extends": "./tsconfig.json",
|
||||
"compilerOptions": {
|
||||
"outDir": "../../../../dist/out-tsc",
|
||||
"declaration": true,
|
||||
"declarationMap": true,
|
||||
"inlineSources": true,
|
||||
"types": []
|
||||
},
|
||||
"include": ["src/**/*.ts"],
|
||||
"exclude": ["src/**/*.spec.ts", "src/**/*.test.ts"]
|
||||
}
|
||||
Reference in New Issue
Block a user