From e676717ffb22e3221753fa7bafc99a732c3bd095 Mon Sep 17 00:00:00 2001 From: Artem Date: Wed, 7 Oct 2026 12:10:12 +0300 Subject: [PATCH] add auth --- Dockerfile | 2 +- angular.json | 23 ++- package-lock.json | 14 ++ package.json | 1 + proxy.conf.json | 7 + src/app/app.config.ts | 6 +- src/app/app.spec.ts | 6 +- src/app/auth/auth-api.service.ts | 32 +++ src/app/auth/auth-error.ts | 49 +++++ src/app/auth/auth-prompt.service.ts | 54 ------ src/app/auth/auth-session.ts | 47 +++++ src/app/auth/auth.models.ts | 11 ++ src/app/auth/auth.service.ts | 111 ----------- src/app/auth/ui/auth-sheet/auth-sheet.html | 31 ++- src/app/auth/ui/auth-sheet/auth-sheet.scss | 8 + src/app/auth/ui/auth-sheet/auth-sheet.ts | 88 ++++++--- .../collections-page/collections-page.ts | 23 +-- src/app/pages/map-item-page/map-item-page.ts | 17 +- src/app/state/auth.effects.ts | 133 +++++++++++++ src/app/state/gorodar.actions.ts | 19 ++ src/app/state/gorodar.models.ts | 45 +++++ src/app/state/gorodar.reducer.ts | 182 +++++++++++++++++- src/app/state/gorodar.selectors.ts | 20 +- src/app/state/index.ts | 1 + src/environments/api.ts | 16 ++ src/environments/environment.prod.ts | 4 + src/environments/environment.test.ts | 4 + src/environments/environment.ts | 4 + 28 files changed, 722 insertions(+), 236 deletions(-) create mode 100644 proxy.conf.json create mode 100644 src/app/auth/auth-api.service.ts create mode 100644 src/app/auth/auth-error.ts delete mode 100644 src/app/auth/auth-prompt.service.ts create mode 100644 src/app/auth/auth-session.ts delete mode 100644 src/app/auth/auth.service.ts create mode 100644 src/app/state/auth.effects.ts create mode 100644 src/environments/api.ts create mode 100644 src/environments/environment.prod.ts create mode 100644 src/environments/environment.test.ts create mode 100644 src/environments/environment.ts diff --git a/Dockerfile b/Dockerfile index 5c1b6e9..144e6ef 100644 --- a/Dockerfile +++ b/Dockerfile @@ -6,7 +6,7 @@ COPY package.json package-lock.json ./ RUN npm i COPY . . -RUN npm run build +RUN npm run build -- --configuration=test FROM nginx:1.27-alpine diff --git a/angular.json b/angular.json index 38320a7..d3d2ea6 100644 --- a/angular.json +++ b/angular.json @@ -47,7 +47,22 @@ } ], "outputHashing": "all", - "serviceWorker": "ngsw-config.json" + "serviceWorker": "ngsw-config.json", + "fileReplacements": [ + { + "replace": "src/environments/environment.ts", + "with": "src/environments/environment.prod.ts" + } + ] + }, + "test": { + "outputHashing": "all", + "fileReplacements": [ + { + "replace": "src/environments/environment.ts", + "with": "src/environments/environment.test.ts" + } + ] }, "development": { "optimization": false, @@ -59,10 +74,16 @@ }, "serve": { "builder": "@angular/build:dev-server", + "options": { + "proxyConfig": "proxy.conf.json" + }, "configurations": { "production": { "buildTarget": "gorodar-front:build:production" }, + "test": { + "buildTarget": "gorodar-front:build:test" + }, "development": { "buildTarget": "gorodar-front:build:development" } diff --git a/package-lock.json b/package-lock.json index 12c7332..60ad85c 100644 --- a/package-lock.json +++ b/package-lock.json @@ -23,6 +23,7 @@ "@capacitor/geolocation": "^8.2.2", "@google/model-viewer": "^4.3.1", "@ionic/pwa-elements": "^3.4.0", + "@ngneat/until-destroy": "^10.0.0", "@ngrx/effects": "^20.1.0", "@ngrx/store": "^20.1.0", "@ngrx/store-devtools": "^20.1.0", @@ -3384,6 +3385,19 @@ "node": ">= 10" } }, + "node_modules/@ngneat/until-destroy": { + "version": "10.0.0", + "resolved": "https://registry.npmjs.org/@ngneat/until-destroy/-/until-destroy-10.0.0.tgz", + "integrity": "sha512-xXFAabQ4YVJ82LYxdgUlaKZyR3dSbxqG3woSyaclzxfCgWMEDweCcM/GGYbNiHJa0WwklI98RXHvca+UyCxpeg==", + "license": "MIT", + "dependencies": { + "tslib": "^2.3.0" + }, + "peerDependencies": { + "@angular/core": ">=13", + "rxjs": "^6.4.0 || ^7.0.0" + } + }, "node_modules/@ngrx/effects": { "version": "20.1.0", "resolved": "https://registry.npmjs.org/@ngrx/effects/-/effects-20.1.0.tgz", diff --git a/package.json b/package.json index c70d01d..7407bf5 100644 --- a/package.json +++ b/package.json @@ -37,6 +37,7 @@ "@capacitor/geolocation": "^8.2.2", "@google/model-viewer": "^4.3.1", "@ionic/pwa-elements": "^3.4.0", + "@ngneat/until-destroy": "^10.0.0", "@ngrx/effects": "^20.1.0", "@ngrx/store": "^20.1.0", "@ngrx/store-devtools": "^20.1.0", diff --git a/proxy.conf.json b/proxy.conf.json new file mode 100644 index 0000000..7741ce7 --- /dev/null +++ b/proxy.conf.json @@ -0,0 +1,7 @@ +{ + "/oauth2": { + "target": "http://gorodar.ru", + "secure": true, + "changeOrigin": true + } +} diff --git a/src/app/app.config.ts b/src/app/app.config.ts index 4474990..d35e8bb 100644 --- a/src/app/app.config.ts +++ b/src/app/app.config.ts @@ -1,4 +1,5 @@ import { ApplicationConfig, isDevMode, provideBrowserGlobalErrorListeners, provideZoneChangeDetection } from '@angular/core'; +import { provideHttpClient } from '@angular/common/http'; import { provideAnimationsAsync } from '@angular/platform-browser/animations/async'; import { provideRouter, withComponentInputBinding } from '@angular/router'; import { provideServiceWorker } from '@angular/service-worker'; @@ -7,17 +8,18 @@ import { provideState, provideStore } from '@ngrx/store'; import { provideStoreDevtools } from '@ngrx/store-devtools'; import { routes } from './app.routes'; -import { GorodarEffects, gorodarFeature } from './state'; +import { AuthEffects, GorodarEffects, gorodarFeature } from './state'; export const appConfig: ApplicationConfig = { providers: [ provideBrowserGlobalErrorListeners(), provideZoneChangeDetection({ eventCoalescing: true }), + provideHttpClient(), provideRouter(routes, withComponentInputBinding()), provideAnimationsAsync(), provideStore(), provideState(gorodarFeature), - provideEffects(GorodarEffects), + provideEffects(GorodarEffects, AuthEffects), provideStoreDevtools({ maxAge: 25, logOnly: !isDevMode() }), provideServiceWorker('ngsw-worker.js', { enabled: !isDevMode(), diff --git a/src/app/app.spec.ts b/src/app/app.spec.ts index e59c7b9..972ba5d 100644 --- a/src/app/app.spec.ts +++ b/src/app/app.spec.ts @@ -1,3 +1,4 @@ +import { provideHttpClient } from '@angular/common/http'; import { TestBed } from '@angular/core/testing'; import { provideRouter } from '@angular/router'; import { provideServiceWorker } from '@angular/service-worker'; @@ -5,17 +6,18 @@ import { provideEffects } from '@ngrx/effects'; import { provideState, provideStore } from '@ngrx/store'; import { App } from './app'; -import { GorodarEffects, gorodarFeature } from './state'; +import { AuthEffects, GorodarEffects, gorodarFeature } from './state'; describe('App', () => { beforeEach(async () => { await TestBed.configureTestingModule({ imports: [App], providers: [ + provideHttpClient(), provideRouter([]), provideStore(), provideState(gorodarFeature), - provideEffects(GorodarEffects), + provideEffects(GorodarEffects, AuthEffects), provideServiceWorker('ngsw-worker.js', { enabled: false }), ], }).compileComponents(); diff --git a/src/app/auth/auth-api.service.ts b/src/app/auth/auth-api.service.ts new file mode 100644 index 0000000..5978f8b --- /dev/null +++ b/src/app/auth/auth-api.service.ts @@ -0,0 +1,32 @@ +import { Injectable, inject } from '@angular/core'; +import { HttpClient, HttpHeaders, HttpParams } from '@angular/common/http'; +import { Observable } from 'rxjs'; + +import { endpoints, grants } from '../../environments/api'; +import type { TokenResponse } from './auth.models'; + +const tokenHeaders = new HttpHeaders({ + Accept: 'application/json, text/plain, */*', + 'Content-Type': 'application/x-www-form-urlencoded', +}); + +@Injectable({ + providedIn: 'root', +}) +export class AuthApiService { + private readonly http = inject(HttpClient); + + requestCode(email: string): Observable { + return this.http.post(endpoints.oauth.authorize, { email }, { responseType: 'text' }); + } + + exchangeCode(email: string, code: string): Observable { + const body = new HttpParams() + .set('grant_type', grants.emailCode) + .set('email', email) + .set('code', code) + .toString(); + + return this.http.post(endpoints.oauth.token, body, { headers: tokenHeaders }); + } +} diff --git a/src/app/auth/auth-error.ts b/src/app/auth/auth-error.ts new file mode 100644 index 0000000..1a0fb49 --- /dev/null +++ b/src/app/auth/auth-error.ts @@ -0,0 +1,49 @@ +import { HttpErrorResponse } from '@angular/common/http'; + +export function authErrorMessage(error: unknown): string { + if (error instanceof Error && !(error instanceof HttpErrorResponse) && error.message) { + return error.message; + } + + if (!(error instanceof HttpErrorResponse)) { + return 'Не удалось выполнить запрос'; + } + + if (error.status === 0) { + return 'Нет соединения с сервером'; + } + + if (error.status === 429) { + return 'Слишком много попыток. Попробуйте чуть позже'; + } + + return readErrorBody(error.error) ?? 'Не удалось выполнить запрос'; +} + +function readErrorBody(body: unknown): string | null { + const parsed = typeof body === 'string' ? parseJson(body) : body; + + if (!parsed || typeof parsed !== 'object') { + return null; + } + + const record = parsed as { error_description?: unknown; message?: unknown }; + + if (typeof record.error_description === 'string' && record.error_description) { + return record.error_description; + } + + if (typeof record.message === 'string' && record.message) { + return record.message; + } + + return null; +} + +function parseJson(value: string): unknown { + try { + return JSON.parse(value) as unknown; + } catch { + return null; + } +} diff --git a/src/app/auth/auth-prompt.service.ts b/src/app/auth/auth-prompt.service.ts deleted file mode 100644 index ab8bf91..0000000 --- a/src/app/auth/auth-prompt.service.ts +++ /dev/null @@ -1,54 +0,0 @@ -import { Injectable, inject, signal } from '@angular/core'; - -import type { AuthIntent, AuthPromptResult } from './auth.models'; -import { AuthService } from './auth.service'; - -@Injectable({ - providedIn: 'root', -}) -export class AuthPromptService { - private readonly auth = inject(AuthService); - - readonly visible = signal(false); - readonly intent = signal('collection'); - - private resolver: ((result: AuthPromptResult) => void) | null = null; - - prompt(intent: AuthIntent): Promise { - if (this.auth.authenticated()) { - return Promise.resolve('authenticated'); - } - - if (this.visible() && this.resolver) { - this.intent.set(intent); - return new Promise((resolve) => { - const previous = this.resolver; - this.resolver = (result) => { - previous?.(result); - resolve(result); - }; - }); - } - - this.intent.set(intent); - this.visible.set(true); - - return new Promise((resolve) => { - this.resolver = resolve; - }); - } - - dismiss(): void { - this.close('dismissed'); - } - - finish(): void { - this.close('authenticated'); - } - - private close(result: AuthPromptResult): void { - this.visible.set(false); - this.resolver?.(result); - this.resolver = null; - } -} diff --git a/src/app/auth/auth-session.ts b/src/app/auth/auth-session.ts new file mode 100644 index 0000000..8c6d471 --- /dev/null +++ b/src/app/auth/auth-session.ts @@ -0,0 +1,47 @@ +import type { AuthSession } from './auth.models'; + +const SESSION_KEY = 'gorodar.session'; + +export function readAuthSession(): AuthSession | null { + const raw = sessionStorage.getItem(SESSION_KEY); + + if (!raw) { + return null; + } + + const session = parseSession(raw); + const expired = !!session && typeof session.expiresAt === 'number' && session.expiresAt <= Date.now(); + + if (!session || !isEmail(session.email) || !session.accessToken || expired) { + sessionStorage.removeItem(SESSION_KEY); + return null; + } + + return session; +} + +export function writeAuthSession(session: AuthSession): void { + sessionStorage.setItem(SESSION_KEY, JSON.stringify(session)); +} + +export function clearAuthSession(): void { + sessionStorage.removeItem(SESSION_KEY); +} + +function parseSession(raw: string): AuthSession | null { + try { + const parsed: unknown = JSON.parse(raw); + + if (!parsed || typeof parsed !== 'object') { + return null; + } + + return parsed as AuthSession; + } catch { + return null; + } +} + +function isEmail(value: string): boolean { + return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(value); +} diff --git a/src/app/auth/auth.models.ts b/src/app/auth/auth.models.ts index eae0857..9bb0631 100644 --- a/src/app/auth/auth.models.ts +++ b/src/app/auth/auth.models.ts @@ -6,4 +6,15 @@ export type AuthStep = 'email' | 'code'; export interface AuthSession { email: string; + accessToken: string; + tokenType: string; + refreshToken?: string; + expiresAt?: number; +} + +export interface TokenResponse { + access_token: string; + token_type?: string; + expires_in?: number; + refresh_token?: string; } diff --git a/src/app/auth/auth.service.ts b/src/app/auth/auth.service.ts deleted file mode 100644 index 60d66e2..0000000 --- a/src/app/auth/auth.service.ts +++ /dev/null @@ -1,111 +0,0 @@ -import { Injectable, signal } from '@angular/core'; - -import type { AuthSession, AuthStep } from './auth.models'; - -const SESSION_KEY = 'gorodar.session'; -const RESEND_SECONDS = 60; - -@Injectable({ - providedIn: 'root', -}) -export class AuthService { - readonly email = signal(''); - readonly authenticated = signal(false); - readonly step = signal('email'); - readonly resendSeconds = signal(0); - - private timerId: ReturnType | null = null; - - constructor() { - const session = this.readSession(); - - if (!session) { - return; - } - - this.email.set(session.email); - this.authenticated.set(true); - } - - requestCode(email: string): boolean { - const normalized = email.trim(); - - if (!this.isEmail(normalized)) { - return false; - } - - this.email.set(normalized); - this.step.set('code'); - this.startTimer(); - return true; - } - - confirmCode(code: string): boolean { - if (!/^\d{6}$/.test(code) || !this.email()) { - return false; - } - - this.authenticated.set(true); - this.step.set('email'); - this.clearTimer(); - this.writeSession({ email: this.email() }); - return true; - } - - changeEmail(): void { - this.clearTimer(); - this.step.set('email'); - } - - logout(): void { - this.authenticated.set(false); - this.step.set('email'); - this.clearTimer(); - sessionStorage.removeItem(SESSION_KEY); - } - - private startTimer(): void { - this.clearTimer(); - this.resendSeconds.set(RESEND_SECONDS); - this.timerId = setInterval(() => { - const next = this.resendSeconds() - 1; - this.resendSeconds.set(Math.max(0, next)); - - if (next <= 0) { - this.clearTimer(); - } - }, 1000); - } - - private clearTimer(): void { - if (this.timerId !== null) { - clearInterval(this.timerId); - this.timerId = null; - } - - this.resendSeconds.set(0); - } - - private isEmail(value: string): boolean { - return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(value); - } - - private readSession(): AuthSession | null { - const raw = sessionStorage.getItem(SESSION_KEY); - - if (!raw) { - return null; - } - - try { - const session = JSON.parse(raw) as AuthSession; - return this.isEmail(session.email) ? session : null; - } catch { - return null; - } - } - - private writeSession(session: AuthSession): void { - sessionStorage.setItem(SESSION_KEY, JSON.stringify(session)); - } -} diff --git a/src/app/auth/ui/auth-sheet/auth-sheet.html b/src/app/auth/ui/auth-sheet/auth-sheet.html index 315ffc3..d95afed 100644 --- a/src/app/auth/ui/auth-sheet/auth-sheet.html +++ b/src/app/auth/ui/auth-sheet/auth-sheet.html @@ -1,4 +1,4 @@ -@if (prompt.visible()) { +@if (sheetVisible()) {
- @if (auth.step() === 'email') { + @if (step() === 'email') { @@ -31,25 +31,29 @@ type="email" inputmode="email" autocomplete="email" - placeholder="" + placeholder="Почта" [value]="emailDraft()" (input)="onEmail($event)" /> + @if (error()) { + + } + } @else {

{{ title() }}

- Отправили 6 цифр на {{ auth.email() }} + Отправили 6 цифр на {{ email() }}

@@ -72,14 +76,23 @@ - } diff --git a/src/app/auth/ui/auth-sheet/auth-sheet.scss b/src/app/auth/ui/auth-sheet/auth-sheet.scss index 94e1264..a6168b6 100644 --- a/src/app/auth/ui/auth-sheet/auth-sheet.scss +++ b/src/app/auth/ui/auth-sheet/auth-sheet.scss @@ -144,6 +144,14 @@ cursor: default; } +.sheet__error { + margin: 14px 0 0; + color: var(--color-danger); + font-size: 14px; + line-height: 1.35; + text-align: center; +} + .sheet__submit { width: 100%; min-height: 52px; diff --git a/src/app/auth/ui/auth-sheet/auth-sheet.ts b/src/app/auth/ui/auth-sheet/auth-sheet.ts index dad359e..3a0f4a6 100644 --- a/src/app/auth/ui/auth-sheet/auth-sheet.ts +++ b/src/app/auth/ui/auth-sheet/auth-sheet.ts @@ -10,10 +10,26 @@ import { untracked, viewChildren, } from '@angular/core'; +import { Store } from '@ngrx/store'; -import { AuthPromptService } from '../../auth-prompt.service'; -import { AuthService } from '../../auth.service'; import { Icon } from '../../../shared/icon/icon'; +import { + GorodarActions, + selectAuthCodeRequestId, + selectAuthEmail, + selectAuthError, + selectAuthIntent, + selectAuthPending, + selectAuthResendSeconds, + selectAuthSheetVisible, + selectAuthStep, +} from '../../../state'; + +const CODE_LENGTH = 6; + +function emptyDigits(): string[] { + return Array.from({ length: CODE_LENGTH }, () => ''); +} @Component({ selector: 'app-auth-sheet', @@ -23,13 +39,20 @@ import { Icon } from '../../../shared/icon/icon'; changeDetection: ChangeDetectionStrategy.OnPush, }) export class AuthSheet { + private readonly store = inject(Store); private readonly digitFields = viewChildren>('digit'); - protected readonly auth = inject(AuthService); - protected readonly prompt = inject(AuthPromptService); - protected readonly emailDraft = signal(''); - protected readonly digits = signal(['', '', '', '', '', '']); + protected readonly digits = signal(emptyDigits()); + + protected readonly sheetVisible = this.store.selectSignal(selectAuthSheetVisible); + protected readonly step = this.store.selectSignal(selectAuthStep); + protected readonly email = this.store.selectSignal(selectAuthEmail); + protected readonly error = this.store.selectSignal(selectAuthError); + protected readonly pending = this.store.selectSignal(selectAuthPending); + protected readonly resendSeconds = this.store.selectSignal(selectAuthResendSeconds); + protected readonly intent = this.store.selectSignal(selectAuthIntent); + private readonly codeRequestId = this.store.selectSignal(selectAuthCodeRequestId); protected readonly emailValid = computed(() => /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(this.emailDraft().trim()), @@ -38,17 +61,17 @@ export class AuthSheet { protected readonly codeReady = computed(() => this.digits().every((digit) => digit.length === 1)); protected readonly title = computed(() => { - if (this.auth.step() === 'code') { + if (this.step() === 'code') { return 'Введите код из письма'; } - return this.prompt.intent() === 'claim' + return this.intent() === 'claim' ? 'Войдите, чтобы забрать объект' : 'Войдите, чтобы открыть коллекцию'; }); protected readonly resendLabel = computed(() => { - const seconds = this.auth.resendSeconds(); + const seconds = this.resendSeconds(); if (seconds <= 0) { return 'Отправить код ещё раз'; @@ -61,18 +84,25 @@ export class AuthSheet { constructor() { effect(() => { - if (!this.prompt.visible()) { + if (!this.sheetVisible()) { return; } - untracked(() => { - this.emailDraft.set(this.auth.email()); - this.digits.set(['', '', '', '', '', '']); - }); + untracked(() => this.emailDraft.set(this.email())); }); effect(() => { - if (this.auth.step() !== 'code' || !this.prompt.visible()) { + const requestId = this.codeRequestId(); + + if (requestId === 0) { + return; + } + + untracked(() => this.digits.set(emptyDigits())); + }); + + effect(() => { + if (this.step() !== 'code' || !this.sheetVisible()) { return; } @@ -83,36 +113,31 @@ export class AuthSheet { protected onEmail(event: Event): void { const input = event.target as HTMLInputElement; this.emailDraft.set(input.value); + this.store.dispatch(GorodarActions.authErrorCleared()); } protected requestCode(): void { - this.digits.set(['', '', '', '', '', '']); - this.auth.requestCode(this.emailDraft()); + this.store.dispatch(GorodarActions.authCodeRequested({ email: this.emailDraft() })); } protected confirm(): void { - if (!this.auth.confirmCode(this.digits().join(''))) { - return; - } - - this.prompt.finish(); + this.store.dispatch(GorodarActions.authCodeConfirmed({ code: this.digits().join('') })); } protected resend(): void { - if (this.auth.resendSeconds() > 0) { + if (this.resendSeconds() > 0 || this.pending()) { return; } - this.digits.set(['', '', '', '', '', '']); - this.auth.requestCode(this.auth.email()); + this.store.dispatch(GorodarActions.authCodeRequested({ email: this.email() })); } protected changeEmail(): void { - this.auth.changeEmail(); + this.store.dispatch(GorodarActions.authEmailChangeRequested()); } protected dismiss(): void { - this.prompt.dismiss(); + this.store.dispatch(GorodarActions.authSheetDismissed()); } protected onDigit(index: number, event: Event): void { @@ -120,6 +145,7 @@ export class AuthSheet { const value = input.value.replace(/\D/g, '').slice(-1); input.value = value; + this.store.dispatch(GorodarActions.authErrorCleared()); this.digits.update((current) => { const next = [...current]; next[index] = value; @@ -153,22 +179,22 @@ export class AuthSheet { protected onPaste(event: ClipboardEvent): void { const text = event.clipboardData?.getData('text') ?? ''; - const parsed = text.replace(/\D/g, '').slice(0, 6).split(''); + const parsed = text.replace(/\D/g, '').slice(0, CODE_LENGTH).split(''); if (parsed.length === 0) { return; } event.preventDefault(); - this.digits.set(Array.from({ length: 6 }, (_, index) => parsed[index] ?? '')); + this.digits.set(Array.from({ length: CODE_LENGTH }, (_, index) => parsed[index] ?? '')); - const focusIndex = Math.min(parsed.length, 5); + const focusIndex = Math.min(parsed.length, CODE_LENGTH - 1); this.digitFields()[focusIndex]?.nativeElement.focus(); } @HostListener('document:keydown.escape') protected onEscape(): void { - if (this.prompt.visible()) { + if (this.sheetVisible()) { this.dismiss(); } } diff --git a/src/app/pages/collections-page/collections-page.ts b/src/app/pages/collections-page/collections-page.ts index 1d2f69a..d89938d 100644 --- a/src/app/pages/collections-page/collections-page.ts +++ b/src/app/pages/collections-page/collections-page.ts @@ -1,18 +1,13 @@ -import { - afterNextRender, - ChangeDetectionStrategy, - Component, - computed, - inject, -} from '@angular/core'; +import { afterNextRender, ChangeDetectionStrategy, Component, computed, inject } from '@angular/core'; import { RouterLink } from '@angular/router'; import { Store } from '@ngrx/store'; -import { AuthPromptService } from '../../auth/auth-prompt.service'; -import { AuthService } from '../../auth/auth.service'; import { CityCatalogService } from '../../root/services/city-catalog.service'; import { Icon } from '../../shared/icon/icon'; import { + GorodarActions, + selectAuthEmail, + selectAuthenticated, selectCollectedIdSet, selectOpenedCount, selectProfile, @@ -29,8 +24,6 @@ import { export class CollectionsPage { private readonly catalog = inject(CityCatalogService); private readonly store = inject(Store); - private readonly auth = inject(AuthService); - private readonly authPrompt = inject(AuthPromptService); protected readonly city = this.catalog.city; protected readonly profile = this.store.selectSignal(selectProfile); @@ -38,8 +31,10 @@ export class CollectionsPage { protected readonly openedCount = this.store.selectSignal(selectOpenedCount); protected readonly totalCount = this.city.objects.length; protected readonly progress = this.store.selectSignal(selectProgress); + private readonly authenticated = this.store.selectSignal(selectAuthenticated); + private readonly authEmail = this.store.selectSignal(selectAuthEmail); protected readonly accountEmail = computed(() => - this.auth.authenticated() ? this.auth.email() : this.profile().email, + this.authenticated() ? this.authEmail() : this.profile().email, ); protected readonly collectedLandmarks = computed(() => this.city.objects.filter((item) => this.collectedIds().has(item.id)), @@ -47,7 +42,7 @@ export class CollectionsPage { constructor() { afterNextRender(() => { - void this.authPrompt.prompt('collection'); + this.store.dispatch(GorodarActions.authSheetOpened({ intent: 'collection' })); }); } @@ -60,7 +55,7 @@ export class CollectionsPage { } protected logout(): void { - this.auth.logout(); + this.store.dispatch(GorodarActions.logout()); } private plural(count: number, forms: [string, string, string]): string { diff --git a/src/app/pages/map-item-page/map-item-page.ts b/src/app/pages/map-item-page/map-item-page.ts index 8855037..fd15c81 100644 --- a/src/app/pages/map-item-page/map-item-page.ts +++ b/src/app/pages/map-item-page/map-item-page.ts @@ -12,13 +12,13 @@ import { MatButton } from '@angular/material/button'; import { Router } from '@angular/router'; import { Store } from '@ngrx/store'; -import { AuthPromptService } from '../../auth/auth-prompt.service'; import { ClaimFlow } from '../../claim/claim-flow/claim-flow'; import { CityCatalogService } from '../../root/services/city-catalog.service'; import { AudioGuide } from '../../shared/audio-guide/audio-guide'; import { Icon } from '../../shared/icon/icon'; import { GorodarActions, + selectAuthenticated, selectClaim, selectCollectedAt, selectCollectedIdSet, @@ -37,7 +37,7 @@ export class MapItemPage { private readonly store = inject(Store); private readonly location = inject(Location); private readonly router = inject(Router); - private readonly authPrompt = inject(AuthPromptService); + private readonly authenticated = this.store.selectSignal(selectAuthenticated); readonly id = input.required(); @@ -95,13 +95,14 @@ export class MapItemPage { } protected claimItem(): void { - void this.authPrompt.prompt('claim').then((result) => { - if (result !== 'authenticated') { - return; - } - + if (this.authenticated()) { this.store.dispatch(GorodarActions.takePhoto({ landmarkId: this.id() })); - }); + return; + } + + this.store.dispatch( + GorodarActions.authSheetOpened({ intent: 'claim', landmarkId: this.id() }), + ); } protected openPhoto(): void { diff --git a/src/app/state/auth.effects.ts b/src/app/state/auth.effects.ts new file mode 100644 index 0000000..53f2af3 --- /dev/null +++ b/src/app/state/auth.effects.ts @@ -0,0 +1,133 @@ +import { Injectable, inject } from '@angular/core'; +import { Actions, createEffect, ofType } from '@ngrx/effects'; +import { Store } from '@ngrx/store'; +import { catchError, exhaustMap, filter, map, of, switchMap, take, takeUntil, tap, timer, withLatestFrom } from 'rxjs'; + +import { AuthApiService } from '../auth/auth-api.service'; +import { authErrorMessage } from '../auth/auth-error'; +import { clearAuthSession, writeAuthSession } from '../auth/auth-session'; +import type { AuthSession } from '../auth/auth.models'; +import { GorodarActions } from './gorodar.actions'; +import { RESEND_SECONDS } from './gorodar.models'; +import { selectAuth, selectAuthenticated } from './gorodar.selectors'; + +@Injectable() +export class AuthEffects { + private readonly actions$ = inject(Actions); + private readonly store = inject(Store); + private readonly api = inject(AuthApiService); + + readonly requestCode$ = createEffect(() => + this.actions$.pipe( + ofType(GorodarActions.authCodeRequested), + exhaustMap(({ email }) => { + const normalized = email.trim(); + + if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(normalized)) { + return of(GorodarActions.authCodeRequestFailed({ error: 'Укажите почту' })); + } + + return this.api.requestCode(normalized).pipe( + map(() => GorodarActions.authCodeRequestSucceeded({ email: normalized })), + catchError((error: unknown) => + of(GorodarActions.authCodeRequestFailed({ error: authErrorMessage(error) })), + ), + ); + }), + ), + ); + + readonly confirmCode$ = createEffect(() => + this.actions$.pipe( + ofType(GorodarActions.authCodeConfirmed), + withLatestFrom(this.store.select(selectAuth)), + exhaustMap(([{ code }, auth]) => { + if (!/^\d{6}$/.test(code) || !auth.email) { + return of(GorodarActions.authCodeConfirmFailed({ error: 'Введите 6 цифр из письма' })); + } + + return this.api.exchangeCode(auth.email, code).pipe( + map((token) => { + if (!token.access_token) { + return GorodarActions.authCodeConfirmFailed({ error: 'Сервер не вернул токен' }); + } + + const session: AuthSession = { + email: auth.email, + accessToken: token.access_token, + tokenType: token.token_type ?? 'Bearer', + refreshToken: token.refresh_token, + expiresAt: token.expires_in ? Date.now() + token.expires_in * 1000 : undefined, + }; + + return GorodarActions.authCodeConfirmSucceeded({ + ...session, + landmarkId: auth.intent === 'claim' ? auth.pendingLandmarkId : null, + }); + }), + catchError((error: unknown) => + of(GorodarActions.authCodeConfirmFailed({ error: authErrorMessage(error) })), + ), + ); + }), + ), + ); + + readonly claimAfterAuth$ = createEffect(() => + this.actions$.pipe( + ofType(GorodarActions.authCodeConfirmSucceeded), + filter(({ landmarkId }) => !!landmarkId), + map(({ landmarkId }) => GorodarActions.takePhoto({ landmarkId: landmarkId as string })), + ), + ); + + readonly openCollectedClaim$ = createEffect(() => + this.actions$.pipe( + ofType(GorodarActions.authSheetOpened), + withLatestFrom(this.store.select(selectAuthenticated)), + filter(([{ landmarkId }, authenticated]) => authenticated && !!landmarkId), + map(([{ landmarkId }]) => GorodarActions.takePhoto({ landmarkId: landmarkId as string })), + ), + ); + + readonly resendTimer$ = createEffect(() => + this.actions$.pipe( + ofType(GorodarActions.authCodeRequestSucceeded), + switchMap(() => + timer(1000, 1000).pipe( + take(RESEND_SECONDS), + map((tick) => GorodarActions.authResendTicked({ seconds: RESEND_SECONDS - tick - 1 })), + takeUntil( + this.actions$.pipe( + ofType( + GorodarActions.authEmailChangeRequested, + GorodarActions.logout, + GorodarActions.authCodeConfirmSucceeded, + ), + ), + ), + ), + ), + ), + ); + + readonly persistSession$ = createEffect( + () => + this.actions$.pipe( + ofType(GorodarActions.authCodeConfirmSucceeded), + tap(({ email, accessToken, tokenType, refreshToken, expiresAt }) => + writeAuthSession({ email, accessToken, tokenType, refreshToken, expiresAt }), + ), + ), + { dispatch: false }, + ); + + readonly clearSession$ = createEffect( + () => + this.actions$.pipe( + ofType(GorodarActions.logout), + tap(() => clearAuthSession()), + ), + { dispatch: false }, + ); +} diff --git a/src/app/state/gorodar.actions.ts b/src/app/state/gorodar.actions.ts index 36d382b..56c47f5 100644 --- a/src/app/state/gorodar.actions.ts +++ b/src/app/state/gorodar.actions.ts @@ -9,5 +9,24 @@ export const GorodarActions = createActionGroup({ 'Claim Step Changed': props<{ step: number }>(), 'Claim Completed': props<{ landmarkId: string; photo: string; collectedAt: string }>(), 'Claim Reset': emptyProps(), + 'Auth Sheet Opened': props<{ intent: 'claim' | 'collection'; landmarkId?: string }>(), + 'Auth Sheet Dismissed': emptyProps(), + 'Auth Error Cleared': emptyProps(), + 'Auth Email Change Requested': emptyProps(), + 'Auth Code Requested': props<{ email: string }>(), + 'Auth Code Request Succeeded': props<{ email: string }>(), + 'Auth Code Request Failed': props<{ error: string }>(), + 'Auth Code Confirmed': props<{ code: string }>(), + 'Auth Code Confirm Succeeded': props<{ + email: string; + accessToken: string; + tokenType: string; + refreshToken?: string; + expiresAt?: number; + landmarkId: string | null; + }>(), + 'Auth Code Confirm Failed': props<{ error: string }>(), + 'Auth Resend Ticked': props<{ seconds: number }>(), + Logout: emptyProps(), }, }); diff --git a/src/app/state/gorodar.models.ts b/src/app/state/gorodar.models.ts index 25da5ba..dca3495 100644 --- a/src/app/state/gorodar.models.ts +++ b/src/app/state/gorodar.models.ts @@ -1,3 +1,5 @@ +import type { AuthIntent, AuthSession, AuthStep } from '../auth/auth.models'; + export type ClaimStage = 'idle' | 'check' | 'success'; export interface ClaimState { @@ -17,10 +19,53 @@ export interface ProfileState { joinedLabel: string; } +export interface AuthState { + email: string; + accessToken: string | null; + tokenType: string; + refreshToken?: string; + expiresAt?: number; + authenticated: boolean; + step: AuthStep; + resendSeconds: number; + pending: boolean; + error: string; + sheetVisible: boolean; + intent: AuthIntent; + pendingLandmarkId: string | null; + codeRequestId: number; +} + export interface GorodarState { collectedIds: string[]; photos: Record; collectedAt: Record; claim: ClaimState; profile: ProfileState; + auth: AuthState; +} + +export const RESEND_SECONDS = 60; + +export function sessionToAuth(session: AuthSession | null): Pick< + AuthState, + 'email' | 'accessToken' | 'tokenType' | 'refreshToken' | 'expiresAt' | 'authenticated' +> { + if (!session) { + return { + email: '', + accessToken: null, + tokenType: 'Bearer', + authenticated: false, + }; + } + + return { + email: session.email, + accessToken: session.accessToken, + tokenType: session.tokenType, + refreshToken: session.refreshToken, + expiresAt: session.expiresAt, + authenticated: true, + }; } diff --git a/src/app/state/gorodar.reducer.ts b/src/app/state/gorodar.reducer.ts index 3eb1778..0e47e7f 100644 --- a/src/app/state/gorodar.reducer.ts +++ b/src/app/state/gorodar.reducer.ts @@ -1,7 +1,8 @@ import { createFeature, createReducer, on } from '@ngrx/store'; +import { readAuthSession } from '../auth/auth-session'; import { GorodarActions } from './gorodar.actions'; -import type { ClaimState, GorodarState } from './gorodar.models'; +import { RESEND_SECONDS, sessionToAuth, type AuthState, type ClaimState, type GorodarState } from './gorodar.models'; const initialClaim: ClaimState = { landmarkId: null, @@ -10,11 +11,32 @@ const initialClaim: ClaimState = { step: 1, }; +const blankAuth: AuthState = { + email: '', + accessToken: null, + tokenType: 'Bearer', + authenticated: false, + step: 'email', + resendSeconds: 0, + pending: false, + error: '', + sheetVisible: false, + intent: 'collection', + pendingLandmarkId: null, + codeRequestId: 0, +}; + +const restoredAuth: AuthState = { + ...blankAuth, + ...sessionToAuth(readAuthSession()), +}; + export const initialState: GorodarState = { collectedIds: [], photos: {}, collectedAt: {}, claim: initialClaim, + auth: restoredAuth, profile: { displayName: 'Иван Иванович', firstName: 'Иван', @@ -80,6 +102,164 @@ const gorodarReducer = createReducer( claim: initialClaim, }), ), + on(GorodarActions.authSheetOpened, (state, { intent, landmarkId }): GorodarState => { + if (state.auth.authenticated) { + return state; + } + + return { + ...state, + auth: { + ...state.auth, + sheetVisible: true, + intent, + pendingLandmarkId: landmarkId ?? null, + error: '', + }, + }; + }), + on( + GorodarActions.authSheetDismissed, + (state): GorodarState => ({ + ...state, + auth: { + ...state.auth, + sheetVisible: false, + error: '', + }, + }), + ), + on( + GorodarActions.authErrorCleared, + (state): GorodarState => ({ + ...state, + auth: { + ...state.auth, + error: '', + }, + }), + ), + on( + GorodarActions.authEmailChangeRequested, + (state): GorodarState => ({ + ...state, + auth: { + ...state.auth, + step: 'email', + error: '', + resendSeconds: 0, + }, + }), + ), + on( + GorodarActions.authCodeRequested, + (state): GorodarState => ({ + ...state, + auth: { + ...state.auth, + pending: true, + error: '', + }, + }), + ), + on( + GorodarActions.authCodeRequestSucceeded, + (state, { email }): GorodarState => ({ + ...state, + auth: { + ...state.auth, + email, + step: 'code', + pending: false, + error: '', + resendSeconds: RESEND_SECONDS, + codeRequestId: state.auth.codeRequestId + 1, + }, + profile: { + ...state.profile, + email, + }, + }), + ), + on( + GorodarActions.authCodeRequestFailed, + (state, { error }): GorodarState => ({ + ...state, + auth: { + ...state.auth, + pending: false, + error, + }, + }), + ), + on( + GorodarActions.authCodeConfirmed, + (state): GorodarState => ({ + ...state, + auth: { + ...state.auth, + pending: true, + error: '', + }, + }), + ), + on( + GorodarActions.authCodeConfirmSucceeded, + (state, { email, accessToken, tokenType, refreshToken, expiresAt }): GorodarState => ({ + ...state, + auth: { + ...state.auth, + email, + accessToken, + tokenType, + refreshToken, + expiresAt, + authenticated: true, + step: 'email', + pending: false, + error: '', + resendSeconds: 0, + sheetVisible: false, + pendingLandmarkId: null, + }, + profile: { + ...state.profile, + email, + }, + }), + ), + on( + GorodarActions.authCodeConfirmFailed, + (state, { error }): GorodarState => ({ + ...state, + auth: { + ...state.auth, + pending: false, + error, + }, + }), + ), + on( + GorodarActions.authResendTicked, + (state, { seconds }): GorodarState => ({ + ...state, + auth: { + ...state.auth, + resendSeconds: seconds, + }, + }), + ), + on( + GorodarActions.logout, + (state): GorodarState => ({ + ...state, + auth: blankAuth, + profile: { + ...state.profile, + email: '', + }, + }), + ), ); export const gorodarFeature = createFeature({ diff --git a/src/app/state/gorodar.selectors.ts b/src/app/state/gorodar.selectors.ts index b48ce5b..545814c 100644 --- a/src/app/state/gorodar.selectors.ts +++ b/src/app/state/gorodar.selectors.ts @@ -3,8 +3,14 @@ import { createSelector } from '@ngrx/store'; import { NIZHNY_NOVGOROD } from '../data/nizhny-novgorod'; import { gorodarFeature } from './gorodar.reducer'; -export const { selectCollectedIds, selectPhotos, selectCollectedAt, selectClaim, selectProfile } = - gorodarFeature; +export const { + selectCollectedIds, + selectPhotos, + selectCollectedAt, + selectClaim, + selectProfile, + selectAuth, +} = gorodarFeature; export const selectCollectedIdSet = createSelector(selectCollectedIds, (ids) => new Set(ids)); @@ -19,6 +25,16 @@ export const selectProgress = createSelector(selectOpenedCount, (opened) => Math.round((opened / selectTotalCount) * 100), ); +export const selectAuthenticated = createSelector(selectAuth, (auth) => auth.authenticated); +export const selectAuthEmail = createSelector(selectAuth, (auth) => auth.email); +export const selectAuthStep = createSelector(selectAuth, (auth) => auth.step); +export const selectAuthError = createSelector(selectAuth, (auth) => auth.error); +export const selectAuthPending = createSelector(selectAuth, (auth) => auth.pending); +export const selectAuthResendSeconds = createSelector(selectAuth, (auth) => auth.resendSeconds); +export const selectAuthSheetVisible = createSelector(selectAuth, (auth) => auth.sheetVisible); +export const selectAuthIntent = createSelector(selectAuth, (auth) => auth.intent); +export const selectAuthCodeRequestId = createSelector(selectAuth, (auth) => auth.codeRequestId); + export const selectClaimPhoto = createSelector(selectClaim, (claim) => claim.photo); export const selectClaimStage = createSelector(selectClaim, (claim) => claim.stage); export const selectClaimStep = createSelector(selectClaim, (claim) => claim.step); diff --git a/src/app/state/index.ts b/src/app/state/index.ts index bce7f27..187843c 100644 --- a/src/app/state/index.ts +++ b/src/app/state/index.ts @@ -1,4 +1,5 @@ export { GorodarActions } from './gorodar.actions'; +export { AuthEffects } from './auth.effects'; export { GorodarEffects } from './gorodar.effects'; export { gorodarFeature, initialState } from './gorodar.reducer'; export * from './gorodar.models'; diff --git a/src/environments/api.ts b/src/environments/api.ts new file mode 100644 index 0000000..2ad881e --- /dev/null +++ b/src/environments/api.ts @@ -0,0 +1,16 @@ +import { environment } from './environment'; + +export { environment }; + +export const API_URL = environment.apiUrl; + +export const endpoints = { + oauth: { + authorize: `${API_URL}/oauth2/authorize`, + token: `${API_URL}/oauth2/token`, + }, +} as const; + +export const grants = { + emailCode: 'urn:gorodar:params:oauth:grant-type:email-code', +} as const; diff --git a/src/environments/environment.prod.ts b/src/environments/environment.prod.ts new file mode 100644 index 0000000..ccc74ef --- /dev/null +++ b/src/environments/environment.prod.ts @@ -0,0 +1,4 @@ +export const environment = { + production: true, + apiUrl: '', +}; diff --git a/src/environments/environment.test.ts b/src/environments/environment.test.ts new file mode 100644 index 0000000..0a491d2 --- /dev/null +++ b/src/environments/environment.test.ts @@ -0,0 +1,4 @@ +export const environment = { + production: false, + apiUrl: 'http://gorodar.ru', +}; diff --git a/src/environments/environment.ts b/src/environments/environment.ts new file mode 100644 index 0000000..cc5d6e9 --- /dev/null +++ b/src/environments/environment.ts @@ -0,0 +1,4 @@ +export const environment = { + production: false, + apiUrl: '', +};