From fc71fccd6d8c9685013c49a72d4e3b2910b5a0c5 Mon Sep 17 00:00:00 2001 From: Meveliq Date: Thu, 22 Oct 2026 01:04:12 +0300 Subject: [PATCH] =?UTF-8?q?Self=E2=80=91registration=20has=20been=20added?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .gitignore | 6 + Dockerfile | 4 +- .../config/security/SecurityConfig.java | 1 + .../controller/AuthenticationController.java | 15 +- .../service/user/UserProvisioningService.java | 2 +- docker-compose.yml | 63 ++++++++ frontend/src/app/app.routes.ts | 7 + .../components/login/login.component.html | 9 ++ .../components/login/login.component.ts | 5 +- .../register/register.component.html | 152 ++++++++++++++++++ .../register/register.component.scss | 107 ++++++++++++ .../register/register.component.spec.ts | 121 ++++++++++++++ .../components/register/register.component.ts | 73 +++++++++ .../src/app/shared/service/auth.service.ts | 14 +- frontend/src/i18n/en.json | 18 +++ frontend/src/i18n/ru.json | 18 +++ 16 files changed, 600 insertions(+), 15 deletions(-) create mode 100644 docker-compose.yml create mode 100644 frontend/src/app/shared/components/register/register.component.html create mode 100644 frontend/src/app/shared/components/register/register.component.scss create mode 100644 frontend/src/app/shared/components/register/register.component.spec.ts create mode 100644 frontend/src/app/shared/components/register/register.component.ts diff --git a/.gitignore b/.gitignore index 9275bff9f..fbc87c5bb 100644 --- a/.gitignore +++ b/.gitignore @@ -57,3 +57,9 @@ backend/src/main/resources/application-local.yaml /.pnpm-store/ /.angular/ .worktrees/ +docker-data/ +mariadb/ +data/ +books/ +bookdrop/ +.env diff --git a/Dockerfile b/Dockerfile index c14d6bee0..087a8482d 100644 --- a/Dockerfile +++ b/Dockerfile @@ -6,11 +6,13 @@ ENV PATH="${PNPM_HOME}/bin:${PATH}" WORKDIR /workspace COPY package.json ./ -RUN PNPM_VERSION="$(node -p "require('./package.json').packageManager.split('@')[1]")" && \ +RUN npm config set registry https://registry.npmmirror.com && \ + PNPM_VERSION="$(node -p "require('./package.json').packageManager.split('@')[1]")" && \ ENV="/root/.shrc" SHELL="/bin/sh" npx --yes get-pnpm "$PNPM_VERSION" COPY pnpm-lock.yaml pnpm-workspace.yaml ./ RUN --mount=type=cache,target=/pnpm/store \ + pnpm config set registry https://registry.npmmirror.com && \ pnpm fetch COPY frontend/package.json ./frontend/ diff --git a/backend/src/main/java/org/booklore/config/security/SecurityConfig.java b/backend/src/main/java/org/booklore/config/security/SecurityConfig.java index c99e1decb..300add749 100644 --- a/backend/src/main/java/org/booklore/config/security/SecurityConfig.java +++ b/backend/src/main/java/org/booklore/config/security/SecurityConfig.java @@ -58,6 +58,7 @@ public class SecurityConfig { "/api/docs", // API documentation UI "/api/openapi.json", // OpenAPI spec (used by API documentation UI) "/api/v1/auth/login", // Login endpoint (must remain public) + "/api/v1/auth/register", // <--- ДОБАВЛЕНО: Registration endpoint "/api/v1/auth/refresh", // Token refresh endpoint (must remain public) "/api/v1/auth/remote", // Remote auth endpoint (must remain public) "/api/v1/auth/oidc/**", // OIDC authentication endpoints diff --git a/backend/src/main/java/org/booklore/controller/AuthenticationController.java b/backend/src/main/java/org/booklore/controller/AuthenticationController.java index b977b9bab..9154d14f0 100644 --- a/backend/src/main/java/org/booklore/controller/AuthenticationController.java +++ b/backend/src/main/java/org/booklore/controller/AuthenticationController.java @@ -20,7 +20,6 @@ import lombok.AllArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.springframework.http.HttpHeaders; import org.springframework.http.ResponseEntity; -import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.web.bind.annotation.*; import java.util.Optional; @@ -37,15 +36,23 @@ public class AuthenticationController { private final AuthenticationService authenticationService; private final UserRepository userRepository; - @Operation(summary = "Register a new user", description = "Register a new user. Only admins can register users.") + @Operation(summary = "Register a new user", description = "Register a new user. Now open to the public.") @ApiResponses({ @ApiResponse(responseCode = "204", description = "User registered successfully"), - @ApiResponse(responseCode = "403", description = "Forbidden") + @ApiResponse(responseCode = "400", description = "Username already exists"), + @ApiResponse(responseCode = "403", description = "Forbidden") // Оставляем на случай, если логика внутри сервиса выкинет ошибку }) @PostMapping("/register") - @PreAuthorize("@securityUtil.isAdmin()") + // УДАЛЕНО: @PreAuthorize("@securityUtil.isAdmin()") - теперь регистрация открыта для всех public ResponseEntity registerUser( @Parameter(description = "User registration request") @RequestBody @Valid UserCreateRequest userCreateRequest) { + + // Дополнительная проверка: не занято ли имя пользователя + // (UserProvisioningService может делать это сам, но лучше перестраховаться) + if (userRepository.findByUsername(userCreateRequest.getUsername()).isPresent()) { + return ResponseEntity.badRequest().body("Username already exists"); + } + userProvisioningService.provisionInternalUser(userCreateRequest); return ResponseEntity.noContent().build(); } diff --git a/backend/src/main/java/org/booklore/service/user/UserProvisioningService.java b/backend/src/main/java/org/booklore/service/user/UserProvisioningService.java index a4faafef8..544f6f6b6 100644 --- a/backend/src/main/java/org/booklore/service/user/UserProvisioningService.java +++ b/backend/src/main/java/org/booklore/service/user/UserProvisioningService.java @@ -94,7 +94,7 @@ public class UserProvisioningService { BookLoreUserEntity user = new BookLoreUserEntity(); user.setUsername(request.getUsername()); - user.setDefaultPassword(true); + user.setDefaultPassword(false); user.setPasswordHash(passwordEncoder.encode(request.getPassword())); user.setName(request.getName()); user.setEmail(request.getEmail()); diff --git a/docker-compose.yml b/docker-compose.yml new file mode 100644 index 000000000..846e7e558 --- /dev/null +++ b/docker-compose.yml @@ -0,0 +1,63 @@ +services: + grimmory: + build: . + container_name: grimmory + environment: + - USER_ID=${APP_USER_ID} + - GROUP_ID=${APP_GROUP_ID} + - TZ=${TZ} + - DATABASE_URL=${DATABASE_URL} + - DATABASE_USERNAME=${DB_USER} + - DATABASE_PASSWORD=${DB_PASSWORD} + - API_DOCS_ENABLED=${API_DOCS_ENABLED} + - DISK_TYPE=${DISK_TYPE} + depends_on: + mariadb: + condition: service_healthy + ports: + - "6060:6060" + volumes: + - ./data:/app/data + - ./books:/books + - ./bookdrop:/bookdrop + healthcheck: + test: wget -q -O - http://localhost:6060/api/v1/healthcheck + interval: 60s + retries: 5 + start_period: 60s + timeout: 10s + restart: unless-stopped + + mariadb: + image: ghcr.io/linuxserver/mariadb:11.4.5 + container_name: mariadb + environment: + - PUID=${DB_USER_ID} + - PGID=${DB_GROUP_ID} + - TZ=${TZ} + - MYSQL_ROOT_PASSWORD=${MYSQL_ROOT_PASSWORD} + - MYSQL_DATABASE=${MYSQL_DATABASE} + - MYSQL_USER=${DB_USER} + - MYSQL_PASSWORD=${DB_PASSWORD} + volumes: + - ./mariadb/config:/config + restart: unless-stopped + healthcheck: + test: ["CMD", "mariadb-admin", "ping", "-h", "localhost"] + interval: 5s + timeout: 5s + retries: 10 + + mailserver: + image: ghcr.io/docker-mailserver/docker-mailserver:latest + container_name: mailserver + hostname: mail.local # Можно любое локальное имя + environment: + - ENABLE_CLAMAV=0 + - ENABLE_SPAMASSASSIN=0 + - PERMIT_DOCKER=connected-networks # Разрешает отправку из этой Docker-сети + volumes: + - ./docker-data/dms/mail-data/:/var/mail/ + - ./docker-data/dms/mail-state/:/var/mail-state/ + - ./docker-data/dms/config/:/tmp/docker-mailserver/ + restart: unless-stopped diff --git a/frontend/src/app/app.routes.ts b/frontend/src/app/app.routes.ts index 029d2b9f7..8f4939f67 100644 --- a/frontend/src/app/app.routes.ts +++ b/frontend/src/app/app.routes.ts @@ -1,6 +1,7 @@ import {Routes} from '@angular/router'; import {AppLayoutComponent} from './shared/layout/layout-main/app.layout.component'; import {LoginComponent} from './shared/components/login/login.component'; +import {RegisterComponent} from './shared/components/register/register.component'; // <-- ДОБАВЛЕНО import {AuthChildGuard, AuthGuard} from './core/security/auth.guard'; import {ChangePasswordComponent} from './shared/components/change-password/change-password.component'; import {SetupComponent} from './shared/components/setup/setup.component'; @@ -92,6 +93,12 @@ export const routes: Routes = [ component: LoginComponent, canActivate: [LoginGuard] }, + // --- ДОБАВЛЕНО: маршрут регистрации --- + { + path: 'register', + component: RegisterComponent + }, + // --- КОНЕЦ ДОБАВЛЕНИЯ --- { path: 'change-password', component: ChangePasswordComponent diff --git a/frontend/src/app/shared/components/login/login.component.html b/frontend/src/app/shared/components/login/login.component.html index 7405f480b..6235a494f 100644 --- a/frontend/src/app/shared/components/login/login.component.html +++ b/frontend/src/app/shared/components/login/login.component.html @@ -82,6 +82,15 @@ [disabled]="!loginForm.valid || !username || !password" class="login-button" /> + +
+ Нет аккаунта? + + Зарегистрироваться + +
+ + @if (oidcEnabled) {
{{ t('orContinueWith') }} diff --git a/frontend/src/app/shared/components/login/login.component.ts b/frontend/src/app/shared/components/login/login.component.ts index e6a92ef0d..6dcc2e3df 100644 --- a/frontend/src/app/shared/components/login/login.component.ts +++ b/frontend/src/app/shared/components/login/login.component.ts @@ -1,6 +1,6 @@ import {Component, effect, inject, OnInit} from '@angular/core'; import {AuthService} from '../../service/auth.service'; -import {ActivatedRoute, Router} from '@angular/router'; +import {ActivatedRoute, Router, RouterLink} from '@angular/router'; import {FormsModule} from '@angular/forms'; import {Password} from '@openng/optimus-ui/password'; import {Button} from '@openng/optimus-ui/button'; @@ -19,7 +19,8 @@ import {OidcService} from '../../../core/security/oidc.service'; Button, Message, InputText, - TranslocoDirective + TranslocoDirective, + RouterLink ], templateUrl: './login.component.html', styleUrls: ['./login.component.scss'] diff --git a/frontend/src/app/shared/components/register/register.component.html b/frontend/src/app/shared/components/register/register.component.html new file mode 100644 index 000000000..eedd04e9e --- /dev/null +++ b/frontend/src/app/shared/components/register/register.component.html @@ -0,0 +1,152 @@ + + + \ No newline at end of file diff --git a/frontend/src/app/shared/components/register/register.component.scss b/frontend/src/app/shared/components/register/register.component.scss new file mode 100644 index 000000000..3709bb086 --- /dev/null +++ b/frontend/src/app/shared/components/register/register.component.scss @@ -0,0 +1,107 @@ +@use '../../styles/auth-shared' as auth; + +.login-container { + @include auth.auth-container; +} + +.login-card-wrapper { + @include auth.auth-card-wrapper(480px, -8rem); +} + +.login-card-border { + @include auth.auth-card-border; +} + +.login-card { + @include auth.auth-card; +} + +.login-header { + @include auth.auth-header; +} + +.logo-wrapper { + @include auth.auth-logo; +} + +.logo-icon { + @include auth.auth-logo-icon; +} + +.login-title { + @include auth.auth-title; +} + +.login-subtitle { + @include auth.auth-subtitle; + font-size: var(--app-text-base); +} + +.login-form { + @include auth.auth-form(1.5rem); +} + +.form-field { + @include auth.form-field; +} + +.form-label { + @include auth.form-label; +} + +.login-button { + @include auth.auth-button; + margin-top: 0.4375rem; +} + +.error-message { + @include auth.error-message; +} + +.error-text { + display: block; + margin-top: 0.25rem; + font-size: 0.75rem; + color: var(--p-error-color, #e74c3c); +} + +.divider { + display: flex; + align-items: center; + text-align: center; + margin: 1.3125rem 0; + + &::before, + &::after { + content: ''; + flex: 1; + border-bottom: 1px solid color-mix(in srgb, var(--color-border) 80%, transparent); + } + + span { + padding: 0 0.875rem; + font-size: var(--app-text-sm); + color: var(--color-text-secondary); + font-weight: 500; + } +} + +.back-button { + ::ng-deep button { + height: 2.4063rem; + background: color-mix(in srgb, var(--color-text) 5%, var(--color-card)); + border: 1px solid color-mix(in srgb, var(--color-border) 85%, var(--color-text) 15%); + color: var(--color-text); + transition: all 0.3s ease; + + &:hover:not(:disabled) { + background: color-mix(in srgb, var(--color-text) 8%, var(--color-card)); + border-color: color-mix(in srgb, var(--color-primary) 45%, var(--color-border)); + transform: translateY(-1px); + } + + &:focus-visible { + box-shadow: 0 0 0 3px color-mix(in srgb, var(--color-primary) 25%, transparent); + } + } +} diff --git a/frontend/src/app/shared/components/register/register.component.spec.ts b/frontend/src/app/shared/components/register/register.component.spec.ts new file mode 100644 index 000000000..49855cb16 --- /dev/null +++ b/frontend/src/app/shared/components/register/register.component.spec.ts @@ -0,0 +1,121 @@ +import { signal } from '@angular/core'; +import { ComponentFixture, TestBed } from '@angular/core/testing'; +import { Router } from '@angular/router'; +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import { of, throwError } from 'rxjs'; + +import { getTranslocoModule } from '../../../core/testing/transloco-testing'; +import { AuthService } from '../../service/auth.service'; +import { RegisterComponent } from '../login/register.component'; + +describe('RegisterComponent', () => { + let fixture: ComponentFixture; + let component: RegisterComponent; + + const authService = { + register: vi.fn(), + }; + + const router = { + navigate: vi.fn(() => Promise.resolve(true)), + }; + + function configureComponent(autoDetectChanges = true): void { + TestBed.configureTestingModule({ + imports: [ + RegisterComponent, + getTranslocoModule(), + ], + providers: [ + { provide: AuthService, useValue: authService }, + { provide: Router, useValue: router }, + ] + }); + + fixture = TestBed.createComponent(RegisterComponent); + component = fixture.componentInstance; + if (autoDetectChanges) { + fixture.detectChanges(); + } + } + + beforeEach(() => { + vi.restoreAllMocks(); + TestBed.resetTestingModule(); + authService.register.mockReset(); + router.navigate.mockClear(); + }); + + afterEach(() => { + TestBed.resetTestingModule(); + }); + + it('should detect password mismatch', () => { + configureComponent(); + component.password = 'password123'; + component.confirmPassword = 'password124'; + expect(component.passwordMismatch).toBe(true); + + component.confirmPassword = 'password123'; + expect(component.passwordMismatch).toBe(false); + }); + + it('should not call register if passwords do not match', () => { + configureComponent(); + component.username = 'testuser'; + component.password = 'password123'; + component.confirmPassword = 'different'; + + component.register(); + + expect(authService.register).not.toHaveBeenCalled(); + }); + + it('should call authService.register and navigate to login on success', () => { + configureComponent(); + authService.register.mockReturnValue(of({})); // Успешный ответ (204) + + component.username = 'newuser'; + component.email = 'new@example.com'; + component.password = 'securePassword123'; + component.confirmPassword = 'securePassword123'; + + component.register(); + + expect(authService.register).toHaveBeenCalledWith({ + username: 'newuser', + password: 'securePassword123', + email: 'new@example.com' + }); + expect(router.navigate).toHaveBeenCalledWith(['/login']); + expect(component.isRegistering()).toBe(false); + }); + + it('should show server error message on 400 (e.g., username exists)', () => { + configureComponent(); + authService.register.mockReturnValue( + throwError(() => ({ status: 400, error: { message: 'Username already exists' } })) + ); + + component.username = 'existinguser'; + component.password = 'password123'; + component.confirmPassword = 'password123'; + component.register(); + + expect(component.errorMessage()).toBe('Username already exists'); + expect(router.navigate).not.toHaveBeenCalled(); + expect(component.isRegistering()).toBe(false); + }); + + it('should show translated network error message on status 0', () => { + configureComponent(); + authService.register.mockReturnValue(throwError(() => ({ status: 0 }))); + + component.username = 'test'; + component.password = 'password123'; + component.confirmPassword = 'password123'; + component.register(); + + expect(component.errorMessage()).toBe('Cannot connect to the server. Please check your connection and try again.'); + }); +}); diff --git a/frontend/src/app/shared/components/register/register.component.ts b/frontend/src/app/shared/components/register/register.component.ts new file mode 100644 index 000000000..228ab4cb7 --- /dev/null +++ b/frontend/src/app/shared/components/register/register.component.ts @@ -0,0 +1,73 @@ +import { Component, inject, signal } from '@angular/core'; +import { CommonModule } from '@angular/common'; +import { FormsModule } from '@angular/forms'; +import { Router, RouterLink } from '@angular/router'; +import { TranslocoModule } from '@jsverse/transloco'; +import { InputText } from '@openng/optimus-ui/inputtext'; +import { Password } from '@openng/optimus-ui/password'; +import { Button } from '@openng/optimus-ui/button'; +import { Message } from '@openng/optimus-ui/message'; +import { AuthService } from '../../service/auth.service'; + +@Component({ + selector: 'app-register', + standalone: true, + imports: [ + CommonModule, + FormsModule, + RouterLink, + TranslocoModule, + InputText, + Password, + Button, + Message + ], + templateUrl: './register.component.html', + styleUrls: ['./register.component.scss'] +}) +export class RegisterComponent { + private readonly authService = inject(AuthService); + private readonly router = inject(Router); + + username = ''; + name = ''; // <-- изменено с fullName + email = ''; + password = ''; + confirmPassword = ''; + + readonly errorMessage = signal(null); + readonly isRegistering = signal(false); + + get passwordMismatch(): boolean { + return !!this.password && this.password !== this.confirmPassword; + } + + register(): void { + if (this.passwordMismatch || this.isRegistering()) return; + + this.errorMessage.set(null); + this.isRegistering.set(true); + + this.authService.register({ + username: this.username, + password: this.password, + email: this.email, + name: this.name // <-- изменено + }).subscribe({ + next: () => { + this.isRegistering.set(false); + this.router.navigate(['/login']); + }, + error: (err) => { + this.isRegistering.set(false); + if (err.status === 0) { + this.errorMessage.set('Cannot connect to the server. Please check your connection and try again.'); + } else if (err.status === 400 && err.error?.message) { + this.errorMessage.set(err.error.message); + } else { + this.errorMessage.set(err.error?.message || 'Registration failed. Please try again.'); + } + } + }); + } +} \ No newline at end of file diff --git a/frontend/src/app/shared/service/auth.service.ts b/frontend/src/app/shared/service/auth.service.ts index 4cb4a422c..9e20c4605 100644 --- a/frontend/src/app/shared/service/auth.service.ts +++ b/frontend/src/app/shared/service/auth.service.ts @@ -39,6 +39,11 @@ export class AuthService { readonly token = signal(this.getInternalAccessToken()); readonly isAuthenticated = computed(() => !!this.token()); + // === ИСПРАВЛЕНО: поле name вместо fullName, регистрация возвращает void === + register(credentials: { username: string; password: string; email?: string; name?: string }): Observable { + return this.http.post(`${this.apiUrl}/register`, credentials); + } + internalLogin(credentials: { username: string; password: string }): Observable { return this.http.post(`${this.apiUrl}/login`, credentials).pipe( tap((response) => { @@ -120,11 +125,10 @@ export class AuthService { } saveInternalTokens(accessToken: string, refreshToken: string, accessTokenExpiry: number = 3600, isDefaultPassword: boolean = false): void { - localStorage.setItem('accessToken_Internal', accessToken); localStorage.setItem('accessToken_Internal_Expiry', (Date.now() + (accessTokenExpiry * 1000)).toString()); localStorage.setItem('refreshToken_Internal', refreshToken); - localStorage.setItem('authenticationIsDefaultPassword_Internal', isDefaultPassword ? 'true' : 'false') + localStorage.setItem('authenticationIsDefaultPassword_Internal', isDefaultPassword ? 'true' : 'false'); this.token.set(accessToken); } @@ -181,7 +185,6 @@ export class AuthService { .subscribe({ next: (response) => { this.clearSession(); - if (response.logoutUrl) { this.redirectTo(response.logoutUrl, true); } else { @@ -190,7 +193,6 @@ export class AuthService { }, error: () => { this.clearSession(); - this.redirectTo('/login', true); } }); @@ -220,7 +222,6 @@ export class AuthService { localStorage.removeItem('accessToken_Internal_Expiry'); localStorage.removeItem('refreshToken_Internal'); localStorage.removeItem('authenticationIsDefaultPassword_Internal'); - this.token.set(null); this._postLoginInitialized.set(false); this.getRxStompService().deactivate(); @@ -233,7 +234,6 @@ export class AuthService { initializeWebSocketConnection(): void { if (!this.hasCurrentAccessToken()) return; - const token = this.getInternalAccessToken(); if (!token) return; @@ -259,4 +259,4 @@ export class AuthService { export function websocketInitializer(authService: AuthService): () => void { return () => authService.initializeWebSocketConnection(); -} +} \ No newline at end of file diff --git a/frontend/src/i18n/en.json b/frontend/src/i18n/en.json index b1e24f456..5a67df147 100644 --- a/frontend/src/i18n/en.json +++ b/frontend/src/i18n/en.json @@ -73,6 +73,24 @@ "invalidToken": "Invalid authentication token received. Please try again.", "unknown": "An unexpected OIDC error occurred. Please try again." } + }, + "register": { + "title": "Create Account", + "subtitle": "Join Grimmory", + "usernameLabel": "Username", + "usernamePlaceholder": "Enter username", + "nameLabel": "Full Name", + "namePlaceholder": "Enter your full name", + "emailLabel": "Email", + "emailPlaceholder": "you@example.com", + "passwordLabel": "Password", + "passwordPlaceholder": "Enter password", + "confirmPasswordLabel": "Confirm Password", + "confirmPasswordPlaceholder": "Repeat password", + "passwordMismatch": "Passwords do not match", + "signUp": "Sign Up", + "or": "or", + "backToLogin": "Back to Login" } }, "nav": { diff --git a/frontend/src/i18n/ru.json b/frontend/src/i18n/ru.json index 397840411..b5ee26e16 100644 --- a/frontend/src/i18n/ru.json +++ b/frontend/src/i18n/ru.json @@ -72,6 +72,24 @@ "invalidToken": "", "unknown": "" } + }, + "register": { + "title": "Создать аккаунт", + "subtitle": "Присоединяйтесь к Grimmory", + "usernameLabel": "Имя пользователя", + "usernamePlaceholder": "Введите имя пользователя", + "nameLabel": "Полное имя", + "namePlaceholder": "Введите полное имя", + "emailLabel": "Email", + "emailPlaceholder": "you@example.com", + "passwordLabel": "Пароль", + "passwordPlaceholder": "Введите пароль", + "confirmPasswordLabel": "Подтвердите пароль", + "confirmPasswordPlaceholder": "Повторите пароль", + "passwordMismatch": "Пароли не совпадают", + "signUp": "Зарегистрироваться", + "or": "или", + "backToLogin": "Назад ко входу" } }, "nav": {