This commit is contained in:
2026-10-07 12:10:12 +03:00
parent e384bc4872
commit e676717ffb
28 changed files with 722 additions and 236 deletions
+1 -1
View File
@@ -6,7 +6,7 @@ COPY package.json package-lock.json ./
RUN npm i RUN npm i
COPY . . COPY . .
RUN npm run build RUN npm run build -- --configuration=test
FROM nginx:1.27-alpine FROM nginx:1.27-alpine
+22 -1
View File
@@ -47,7 +47,22 @@
} }
], ],
"outputHashing": "all", "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": { "development": {
"optimization": false, "optimization": false,
@@ -59,10 +74,16 @@
}, },
"serve": { "serve": {
"builder": "@angular/build:dev-server", "builder": "@angular/build:dev-server",
"options": {
"proxyConfig": "proxy.conf.json"
},
"configurations": { "configurations": {
"production": { "production": {
"buildTarget": "gorodar-front:build:production" "buildTarget": "gorodar-front:build:production"
}, },
"test": {
"buildTarget": "gorodar-front:build:test"
},
"development": { "development": {
"buildTarget": "gorodar-front:build:development" "buildTarget": "gorodar-front:build:development"
} }
+14
View File
@@ -23,6 +23,7 @@
"@capacitor/geolocation": "^8.2.2", "@capacitor/geolocation": "^8.2.2",
"@google/model-viewer": "^4.3.1", "@google/model-viewer": "^4.3.1",
"@ionic/pwa-elements": "^3.4.0", "@ionic/pwa-elements": "^3.4.0",
"@ngneat/until-destroy": "^10.0.0",
"@ngrx/effects": "^20.1.0", "@ngrx/effects": "^20.1.0",
"@ngrx/store": "^20.1.0", "@ngrx/store": "^20.1.0",
"@ngrx/store-devtools": "^20.1.0", "@ngrx/store-devtools": "^20.1.0",
@@ -3384,6 +3385,19 @@
"node": ">= 10" "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": { "node_modules/@ngrx/effects": {
"version": "20.1.0", "version": "20.1.0",
"resolved": "https://registry.npmjs.org/@ngrx/effects/-/effects-20.1.0.tgz", "resolved": "https://registry.npmjs.org/@ngrx/effects/-/effects-20.1.0.tgz",
+1
View File
@@ -37,6 +37,7 @@
"@capacitor/geolocation": "^8.2.2", "@capacitor/geolocation": "^8.2.2",
"@google/model-viewer": "^4.3.1", "@google/model-viewer": "^4.3.1",
"@ionic/pwa-elements": "^3.4.0", "@ionic/pwa-elements": "^3.4.0",
"@ngneat/until-destroy": "^10.0.0",
"@ngrx/effects": "^20.1.0", "@ngrx/effects": "^20.1.0",
"@ngrx/store": "^20.1.0", "@ngrx/store": "^20.1.0",
"@ngrx/store-devtools": "^20.1.0", "@ngrx/store-devtools": "^20.1.0",
+7
View File
@@ -0,0 +1,7 @@
{
"/oauth2": {
"target": "http://gorodar.ru",
"secure": true,
"changeOrigin": true
}
}
+4 -2
View File
@@ -1,4 +1,5 @@
import { ApplicationConfig, isDevMode, provideBrowserGlobalErrorListeners, provideZoneChangeDetection } from '@angular/core'; import { ApplicationConfig, isDevMode, provideBrowserGlobalErrorListeners, provideZoneChangeDetection } from '@angular/core';
import { provideHttpClient } from '@angular/common/http';
import { provideAnimationsAsync } from '@angular/platform-browser/animations/async'; import { provideAnimationsAsync } from '@angular/platform-browser/animations/async';
import { provideRouter, withComponentInputBinding } from '@angular/router'; import { provideRouter, withComponentInputBinding } from '@angular/router';
import { provideServiceWorker } from '@angular/service-worker'; import { provideServiceWorker } from '@angular/service-worker';
@@ -7,17 +8,18 @@ import { provideState, provideStore } from '@ngrx/store';
import { provideStoreDevtools } from '@ngrx/store-devtools'; import { provideStoreDevtools } from '@ngrx/store-devtools';
import { routes } from './app.routes'; import { routes } from './app.routes';
import { GorodarEffects, gorodarFeature } from './state'; import { AuthEffects, GorodarEffects, gorodarFeature } from './state';
export const appConfig: ApplicationConfig = { export const appConfig: ApplicationConfig = {
providers: [ providers: [
provideBrowserGlobalErrorListeners(), provideBrowserGlobalErrorListeners(),
provideZoneChangeDetection({ eventCoalescing: true }), provideZoneChangeDetection({ eventCoalescing: true }),
provideHttpClient(),
provideRouter(routes, withComponentInputBinding()), provideRouter(routes, withComponentInputBinding()),
provideAnimationsAsync(), provideAnimationsAsync(),
provideStore(), provideStore(),
provideState(gorodarFeature), provideState(gorodarFeature),
provideEffects(GorodarEffects), provideEffects(GorodarEffects, AuthEffects),
provideStoreDevtools({ maxAge: 25, logOnly: !isDevMode() }), provideStoreDevtools({ maxAge: 25, logOnly: !isDevMode() }),
provideServiceWorker('ngsw-worker.js', { provideServiceWorker('ngsw-worker.js', {
enabled: !isDevMode(), enabled: !isDevMode(),
+4 -2
View File
@@ -1,3 +1,4 @@
import { provideHttpClient } from '@angular/common/http';
import { TestBed } from '@angular/core/testing'; import { TestBed } from '@angular/core/testing';
import { provideRouter } from '@angular/router'; import { provideRouter } from '@angular/router';
import { provideServiceWorker } from '@angular/service-worker'; import { provideServiceWorker } from '@angular/service-worker';
@@ -5,17 +6,18 @@ import { provideEffects } from '@ngrx/effects';
import { provideState, provideStore } from '@ngrx/store'; import { provideState, provideStore } from '@ngrx/store';
import { App } from './app'; import { App } from './app';
import { GorodarEffects, gorodarFeature } from './state'; import { AuthEffects, GorodarEffects, gorodarFeature } from './state';
describe('App', () => { describe('App', () => {
beforeEach(async () => { beforeEach(async () => {
await TestBed.configureTestingModule({ await TestBed.configureTestingModule({
imports: [App], imports: [App],
providers: [ providers: [
provideHttpClient(),
provideRouter([]), provideRouter([]),
provideStore(), provideStore(),
provideState(gorodarFeature), provideState(gorodarFeature),
provideEffects(GorodarEffects), provideEffects(GorodarEffects, AuthEffects),
provideServiceWorker('ngsw-worker.js', { enabled: false }), provideServiceWorker('ngsw-worker.js', { enabled: false }),
], ],
}).compileComponents(); }).compileComponents();
+32
View File
@@ -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<string> {
return this.http.post(endpoints.oauth.authorize, { email }, { responseType: 'text' });
}
exchangeCode(email: string, code: string): Observable<TokenResponse> {
const body = new HttpParams()
.set('grant_type', grants.emailCode)
.set('email', email)
.set('code', code)
.toString();
return this.http.post<TokenResponse>(endpoints.oauth.token, body, { headers: tokenHeaders });
}
}
+49
View File
@@ -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;
}
}
-54
View File
@@ -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<AuthIntent>('collection');
private resolver: ((result: AuthPromptResult) => void) | null = null;
prompt(intent: AuthIntent): Promise<AuthPromptResult> {
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;
}
}
+47
View File
@@ -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);
}
+11
View File
@@ -6,4 +6,15 @@ export type AuthStep = 'email' | 'code';
export interface AuthSession { export interface AuthSession {
email: string; 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;
} }
-111
View File
@@ -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<AuthStep>('email');
readonly resendSeconds = signal(0);
private timerId: ReturnType<typeof setInterval> | 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));
}
}
+22 -9
View File
@@ -1,4 +1,4 @@
@if (prompt.visible()) { @if (sheetVisible()) {
<div class="sheet-root"> <div class="sheet-root">
<button <button
class="sheet-root__backdrop" class="sheet-root__backdrop"
@@ -15,7 +15,7 @@
(click)="dismiss()" (click)="dismiss()"
></button> ></button>
@if (auth.step() === 'email') { @if (step() === 'email') {
<div class="sheet__lock" aria-hidden="true"> <div class="sheet__lock" aria-hidden="true">
<app-icon name="lock" [size]="28" /> <app-icon name="lock" [size]="28" />
</div> </div>
@@ -31,25 +31,29 @@
type="email" type="email"
inputmode="email" inputmode="email"
autocomplete="email" autocomplete="email"
placeholder="" placeholder="Почта"
[value]="emailDraft()" [value]="emailDraft()"
(input)="onEmail($event)" (input)="onEmail($event)"
/> />
</label> </label>
@if (error()) {
<p class="sheet__error" role="alert">{{ error() }}</p>
}
<button <button
class="sheet__submit" class="sheet__submit"
type="button" type="button"
[disabled]="!emailValid()" [disabled]="!emailValid() || pending()"
(click)="requestCode()" (click)="requestCode()"
> >
Получить код {{ pending() ? 'Отправляем…' : 'Получить код' }}
</button> </button>
<button class="sheet__ghost" type="button" (click)="dismiss()">Пока просто посмотрю</button> <button class="sheet__ghost" type="button" (click)="dismiss()">Пока просто посмотрю</button>
} @else { } @else {
<h2 id="auth-sheet-title">{{ title() }}</h2> <h2 id="auth-sheet-title">{{ title() }}</h2>
<p class="sheet__lead"> <p class="sheet__lead">
Отправили 6 цифр на <b>{{ auth.email() }}</b> Отправили 6 цифр на <b>{{ email() }}</b>
</p> </p>
<div class="sheet__digits"> <div class="sheet__digits">
@@ -72,14 +76,23 @@
<button <button
class="sheet__resend" class="sheet__resend"
type="button" type="button"
[disabled]="auth.resendSeconds() > 0" [disabled]="resendSeconds() > 0 || pending()"
(click)="resend()" (click)="resend()"
> >
{{ resendLabel() }} {{ resendLabel() }}
</button> </button>
<button class="sheet__submit" type="button" [disabled]="!codeReady()" (click)="confirm()"> @if (error()) {
Подтвердить <p class="sheet__error" role="alert">{{ error() }}</p>
}
<button
class="sheet__submit"
type="button"
[disabled]="!codeReady() || pending()"
(click)="confirm()"
>
{{ pending() ? 'Проверяем…' : 'Подтвердить' }}
</button> </button>
<button class="sheet__ghost" type="button" (click)="changeEmail()">Изменить почту</button> <button class="sheet__ghost" type="button" (click)="changeEmail()">Изменить почту</button>
} }
@@ -144,6 +144,14 @@
cursor: default; cursor: default;
} }
.sheet__error {
margin: 14px 0 0;
color: var(--color-danger);
font-size: 14px;
line-height: 1.35;
text-align: center;
}
.sheet__submit { .sheet__submit {
width: 100%; width: 100%;
min-height: 52px; min-height: 52px;
+57 -31
View File
@@ -10,10 +10,26 @@ import {
untracked, untracked,
viewChildren, viewChildren,
} from '@angular/core'; } 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 { 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({ @Component({
selector: 'app-auth-sheet', selector: 'app-auth-sheet',
@@ -23,13 +39,20 @@ import { Icon } from '../../../shared/icon/icon';
changeDetection: ChangeDetectionStrategy.OnPush, changeDetection: ChangeDetectionStrategy.OnPush,
}) })
export class AuthSheet { export class AuthSheet {
private readonly store = inject(Store);
private readonly digitFields = viewChildren<ElementRef<HTMLInputElement>>('digit'); private readonly digitFields = viewChildren<ElementRef<HTMLInputElement>>('digit');
protected readonly auth = inject(AuthService);
protected readonly prompt = inject(AuthPromptService);
protected readonly emailDraft = signal(''); protected readonly emailDraft = signal('');
protected readonly digits = signal<string[]>(['', '', '', '', '', '']); protected readonly digits = signal<string[]>(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(() => protected readonly emailValid = computed(() =>
/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(this.emailDraft().trim()), /^[^\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 codeReady = computed(() => this.digits().every((digit) => digit.length === 1));
protected readonly title = computed(() => { protected readonly title = computed(() => {
if (this.auth.step() === 'code') { if (this.step() === 'code') {
return 'Введите код из письма'; return 'Введите код из письма';
} }
return this.prompt.intent() === 'claim' return this.intent() === 'claim'
? 'Войдите, чтобы забрать объект' ? 'Войдите, чтобы забрать объект'
: 'Войдите, чтобы открыть коллекцию'; : 'Войдите, чтобы открыть коллекцию';
}); });
protected readonly resendLabel = computed(() => { protected readonly resendLabel = computed(() => {
const seconds = this.auth.resendSeconds(); const seconds = this.resendSeconds();
if (seconds <= 0) { if (seconds <= 0) {
return 'Отправить код ещё раз'; return 'Отправить код ещё раз';
@@ -61,18 +84,25 @@ export class AuthSheet {
constructor() { constructor() {
effect(() => { effect(() => {
if (!this.prompt.visible()) { if (!this.sheetVisible()) {
return; return;
} }
untracked(() => { untracked(() => this.emailDraft.set(this.email()));
this.emailDraft.set(this.auth.email());
this.digits.set(['', '', '', '', '', '']);
});
}); });
effect(() => { 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; return;
} }
@@ -83,36 +113,31 @@ export class AuthSheet {
protected onEmail(event: Event): void { protected onEmail(event: Event): void {
const input = event.target as HTMLInputElement; const input = event.target as HTMLInputElement;
this.emailDraft.set(input.value); this.emailDraft.set(input.value);
this.store.dispatch(GorodarActions.authErrorCleared());
} }
protected requestCode(): void { protected requestCode(): void {
this.digits.set(['', '', '', '', '', '']); this.store.dispatch(GorodarActions.authCodeRequested({ email: this.emailDraft() }));
this.auth.requestCode(this.emailDraft());
} }
protected confirm(): void { protected confirm(): void {
if (!this.auth.confirmCode(this.digits().join(''))) { this.store.dispatch(GorodarActions.authCodeConfirmed({ code: this.digits().join('') }));
return;
}
this.prompt.finish();
} }
protected resend(): void { protected resend(): void {
if (this.auth.resendSeconds() > 0) { if (this.resendSeconds() > 0 || this.pending()) {
return; return;
} }
this.digits.set(['', '', '', '', '', '']); this.store.dispatch(GorodarActions.authCodeRequested({ email: this.email() }));
this.auth.requestCode(this.auth.email());
} }
protected changeEmail(): void { protected changeEmail(): void {
this.auth.changeEmail(); this.store.dispatch(GorodarActions.authEmailChangeRequested());
} }
protected dismiss(): void { protected dismiss(): void {
this.prompt.dismiss(); this.store.dispatch(GorodarActions.authSheetDismissed());
} }
protected onDigit(index: number, event: Event): void { protected onDigit(index: number, event: Event): void {
@@ -120,6 +145,7 @@ export class AuthSheet {
const value = input.value.replace(/\D/g, '').slice(-1); const value = input.value.replace(/\D/g, '').slice(-1);
input.value = value; input.value = value;
this.store.dispatch(GorodarActions.authErrorCleared());
this.digits.update((current) => { this.digits.update((current) => {
const next = [...current]; const next = [...current];
next[index] = value; next[index] = value;
@@ -153,22 +179,22 @@ export class AuthSheet {
protected onPaste(event: ClipboardEvent): void { protected onPaste(event: ClipboardEvent): void {
const text = event.clipboardData?.getData('text') ?? ''; 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) { if (parsed.length === 0) {
return; return;
} }
event.preventDefault(); 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(); this.digitFields()[focusIndex]?.nativeElement.focus();
} }
@HostListener('document:keydown.escape') @HostListener('document:keydown.escape')
protected onEscape(): void { protected onEscape(): void {
if (this.prompt.visible()) { if (this.sheetVisible()) {
this.dismiss(); this.dismiss();
} }
} }
@@ -1,18 +1,13 @@
import { import { afterNextRender, ChangeDetectionStrategy, Component, computed, inject } from '@angular/core';
afterNextRender,
ChangeDetectionStrategy,
Component,
computed,
inject,
} from '@angular/core';
import { RouterLink } from '@angular/router'; import { RouterLink } from '@angular/router';
import { Store } from '@ngrx/store'; 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 { CityCatalogService } from '../../root/services/city-catalog.service';
import { Icon } from '../../shared/icon/icon'; import { Icon } from '../../shared/icon/icon';
import { import {
GorodarActions,
selectAuthEmail,
selectAuthenticated,
selectCollectedIdSet, selectCollectedIdSet,
selectOpenedCount, selectOpenedCount,
selectProfile, selectProfile,
@@ -29,8 +24,6 @@ import {
export class CollectionsPage { export class CollectionsPage {
private readonly catalog = inject(CityCatalogService); private readonly catalog = inject(CityCatalogService);
private readonly store = inject(Store); private readonly store = inject(Store);
private readonly auth = inject(AuthService);
private readonly authPrompt = inject(AuthPromptService);
protected readonly city = this.catalog.city; protected readonly city = this.catalog.city;
protected readonly profile = this.store.selectSignal(selectProfile); protected readonly profile = this.store.selectSignal(selectProfile);
@@ -38,8 +31,10 @@ export class CollectionsPage {
protected readonly openedCount = this.store.selectSignal(selectOpenedCount); protected readonly openedCount = this.store.selectSignal(selectOpenedCount);
protected readonly totalCount = this.city.objects.length; protected readonly totalCount = this.city.objects.length;
protected readonly progress = this.store.selectSignal(selectProgress); 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(() => protected readonly accountEmail = computed(() =>
this.auth.authenticated() ? this.auth.email() : this.profile().email, this.authenticated() ? this.authEmail() : this.profile().email,
); );
protected readonly collectedLandmarks = computed(() => protected readonly collectedLandmarks = computed(() =>
this.city.objects.filter((item) => this.collectedIds().has(item.id)), this.city.objects.filter((item) => this.collectedIds().has(item.id)),
@@ -47,7 +42,7 @@ export class CollectionsPage {
constructor() { constructor() {
afterNextRender(() => { afterNextRender(() => {
void this.authPrompt.prompt('collection'); this.store.dispatch(GorodarActions.authSheetOpened({ intent: 'collection' }));
}); });
} }
@@ -60,7 +55,7 @@ export class CollectionsPage {
} }
protected logout(): void { protected logout(): void {
this.auth.logout(); this.store.dispatch(GorodarActions.logout());
} }
private plural(count: number, forms: [string, string, string]): string { private plural(count: number, forms: [string, string, string]): string {
+9 -8
View File
@@ -12,13 +12,13 @@ import { MatButton } from '@angular/material/button';
import { Router } from '@angular/router'; import { Router } from '@angular/router';
import { Store } from '@ngrx/store'; import { Store } from '@ngrx/store';
import { AuthPromptService } from '../../auth/auth-prompt.service';
import { ClaimFlow } from '../../claim/claim-flow/claim-flow'; import { ClaimFlow } from '../../claim/claim-flow/claim-flow';
import { CityCatalogService } from '../../root/services/city-catalog.service'; import { CityCatalogService } from '../../root/services/city-catalog.service';
import { AudioGuide } from '../../shared/audio-guide/audio-guide'; import { AudioGuide } from '../../shared/audio-guide/audio-guide';
import { Icon } from '../../shared/icon/icon'; import { Icon } from '../../shared/icon/icon';
import { import {
GorodarActions, GorodarActions,
selectAuthenticated,
selectClaim, selectClaim,
selectCollectedAt, selectCollectedAt,
selectCollectedIdSet, selectCollectedIdSet,
@@ -37,7 +37,7 @@ export class MapItemPage {
private readonly store = inject(Store); private readonly store = inject(Store);
private readonly location = inject(Location); private readonly location = inject(Location);
private readonly router = inject(Router); private readonly router = inject(Router);
private readonly authPrompt = inject(AuthPromptService); private readonly authenticated = this.store.selectSignal(selectAuthenticated);
readonly id = input.required<string>(); readonly id = input.required<string>();
@@ -95,13 +95,14 @@ export class MapItemPage {
} }
protected claimItem(): void { protected claimItem(): void {
void this.authPrompt.prompt('claim').then((result) => { if (this.authenticated()) {
if (result !== 'authenticated') {
return;
}
this.store.dispatch(GorodarActions.takePhoto({ landmarkId: this.id() })); this.store.dispatch(GorodarActions.takePhoto({ landmarkId: this.id() }));
}); return;
}
this.store.dispatch(
GorodarActions.authSheetOpened({ intent: 'claim', landmarkId: this.id() }),
);
} }
protected openPhoto(): void { protected openPhoto(): void {
+133
View File
@@ -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 },
);
}
+19
View File
@@ -9,5 +9,24 @@ export const GorodarActions = createActionGroup({
'Claim Step Changed': props<{ step: number }>(), 'Claim Step Changed': props<{ step: number }>(),
'Claim Completed': props<{ landmarkId: string; photo: string; collectedAt: string }>(), 'Claim Completed': props<{ landmarkId: string; photo: string; collectedAt: string }>(),
'Claim Reset': emptyProps(), '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(),
}, },
}); });
+45
View File
@@ -1,3 +1,5 @@
import type { AuthIntent, AuthSession, AuthStep } from '../auth/auth.models';
export type ClaimStage = 'idle' | 'check' | 'success'; export type ClaimStage = 'idle' | 'check' | 'success';
export interface ClaimState { export interface ClaimState {
@@ -17,10 +19,53 @@ export interface ProfileState {
joinedLabel: string; 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 { export interface GorodarState {
collectedIds: string[]; collectedIds: string[];
photos: Record<string, string>; photos: Record<string, string>;
collectedAt: Record<string, string>; collectedAt: Record<string, string>;
claim: ClaimState; claim: ClaimState;
profile: ProfileState; 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,
};
} }
+181 -1
View File
@@ -1,7 +1,8 @@
import { createFeature, createReducer, on } from '@ngrx/store'; import { createFeature, createReducer, on } from '@ngrx/store';
import { readAuthSession } from '../auth/auth-session';
import { GorodarActions } from './gorodar.actions'; 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 = { const initialClaim: ClaimState = {
landmarkId: null, landmarkId: null,
@@ -10,11 +11,32 @@ const initialClaim: ClaimState = {
step: 1, 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 = { export const initialState: GorodarState = {
collectedIds: [], collectedIds: [],
photos: {}, photos: {},
collectedAt: {}, collectedAt: {},
claim: initialClaim, claim: initialClaim,
auth: restoredAuth,
profile: { profile: {
displayName: 'Иван Иванович', displayName: 'Иван Иванович',
firstName: 'Иван', firstName: 'Иван',
@@ -80,6 +102,164 @@ const gorodarReducer = createReducer(
claim: initialClaim, 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({ export const gorodarFeature = createFeature({
+18 -2
View File
@@ -3,8 +3,14 @@ import { createSelector } from '@ngrx/store';
import { NIZHNY_NOVGOROD } from '../data/nizhny-novgorod'; import { NIZHNY_NOVGOROD } from '../data/nizhny-novgorod';
import { gorodarFeature } from './gorodar.reducer'; import { gorodarFeature } from './gorodar.reducer';
export const { selectCollectedIds, selectPhotos, selectCollectedAt, selectClaim, selectProfile } = export const {
gorodarFeature; selectCollectedIds,
selectPhotos,
selectCollectedAt,
selectClaim,
selectProfile,
selectAuth,
} = gorodarFeature;
export const selectCollectedIdSet = createSelector(selectCollectedIds, (ids) => new Set(ids)); export const selectCollectedIdSet = createSelector(selectCollectedIds, (ids) => new Set(ids));
@@ -19,6 +25,16 @@ export const selectProgress = createSelector(selectOpenedCount, (opened) =>
Math.round((opened / selectTotalCount) * 100), 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 selectClaimPhoto = createSelector(selectClaim, (claim) => claim.photo);
export const selectClaimStage = createSelector(selectClaim, (claim) => claim.stage); export const selectClaimStage = createSelector(selectClaim, (claim) => claim.stage);
export const selectClaimStep = createSelector(selectClaim, (claim) => claim.step); export const selectClaimStep = createSelector(selectClaim, (claim) => claim.step);
+1
View File
@@ -1,4 +1,5 @@
export { GorodarActions } from './gorodar.actions'; export { GorodarActions } from './gorodar.actions';
export { AuthEffects } from './auth.effects';
export { GorodarEffects } from './gorodar.effects'; export { GorodarEffects } from './gorodar.effects';
export { gorodarFeature, initialState } from './gorodar.reducer'; export { gorodarFeature, initialState } from './gorodar.reducer';
export * from './gorodar.models'; export * from './gorodar.models';
+16
View File
@@ -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;
+4
View File
@@ -0,0 +1,4 @@
export const environment = {
production: true,
apiUrl: '',
};
+4
View File
@@ -0,0 +1,4 @@
export const environment = {
production: false,
apiUrl: 'http://gorodar.ru',
};
+4
View File
@@ -0,0 +1,4 @@
export const environment = {
production: false,
apiUrl: '',
};