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
+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 {
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">
<button
class="sheet-root__backdrop"
@@ -15,7 +15,7 @@
(click)="dismiss()"
></button>
@if (auth.step() === 'email') {
@if (step() === 'email') {
<div class="sheet__lock" aria-hidden="true">
<app-icon name="lock" [size]="28" />
</div>
@@ -31,25 +31,29 @@
type="email"
inputmode="email"
autocomplete="email"
placeholder=""
placeholder="Почта"
[value]="emailDraft()"
(input)="onEmail($event)"
/>
</label>
@if (error()) {
<p class="sheet__error" role="alert">{{ error() }}</p>
}
<button
class="sheet__submit"
type="button"
[disabled]="!emailValid()"
[disabled]="!emailValid() || pending()"
(click)="requestCode()"
>
Получить код
{{ pending() ? 'Отправляем…' : 'Получить код' }}
</button>
<button class="sheet__ghost" type="button" (click)="dismiss()">Пока просто посмотрю</button>
} @else {
<h2 id="auth-sheet-title">{{ title() }}</h2>
<p class="sheet__lead">
Отправили 6 цифр на <b>{{ auth.email() }}</b>
Отправили 6 цифр на <b>{{ email() }}</b>
</p>
<div class="sheet__digits">
@@ -72,14 +76,23 @@
<button
class="sheet__resend"
type="button"
[disabled]="auth.resendSeconds() > 0"
[disabled]="resendSeconds() > 0 || pending()"
(click)="resend()"
>
{{ resendLabel() }}
</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 class="sheet__ghost" type="button" (click)="changeEmail()">Изменить почту</button>
}
@@ -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;
+57 -31
View File
@@ -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<ElementRef<HTMLInputElement>>('digit');
protected readonly auth = inject(AuthService);
protected readonly prompt = inject(AuthPromptService);
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(() =>
/^[^\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();
}
}