Self‑registration has been added
CI - Frontend Quality Thresholds / Frontend Lint Threshold Check (push) Canceled after 0s
Reusable - Flyway Migration Check / Flyway DB Migration Preview (push) Canceled after 0s
Reusable - Flyway Migration Check / Check for DB Migrations (push) Canceled after 0s
Release - Semantic Stable / Flyway Migration Check (push) Canceled after 0s
Release - Semantic Stable / Resolve release ref (push) Canceled after 0s
Release - Semantic Stable / Test Suite (push) Canceled after 0s
Release - Semantic Stable / Generate Notes (push) Canceled after 0s
Release - Semantic Stable / Build frontend (push) Canceled after 0s
Release - Semantic Stable / Build backend (push) Canceled after 0s
Release - Semantic Stable / Build OpenAPI document (push) Canceled after 0s
Release - Semantic Stable / Create Draft Release (push) Canceled after 0s
CI - Frontend Quality Thresholds / Frontend Lint Threshold Check (push) Canceled after 0s
Reusable - Flyway Migration Check / Flyway DB Migration Preview (push) Canceled after 0s
Reusable - Flyway Migration Check / Check for DB Migrations (push) Canceled after 0s
Release - Semantic Stable / Flyway Migration Check (push) Canceled after 0s
Release - Semantic Stable / Resolve release ref (push) Canceled after 0s
Release - Semantic Stable / Test Suite (push) Canceled after 0s
Release - Semantic Stable / Generate Notes (push) Canceled after 0s
Release - Semantic Stable / Build frontend (push) Canceled after 0s
Release - Semantic Stable / Build backend (push) Canceled after 0s
Release - Semantic Stable / Build OpenAPI document (push) Canceled after 0s
Release - Semantic Stable / Create Draft Release (push) Canceled after 0s
This commit is contained in:
@@ -57,3 +57,9 @@ backend/src/main/resources/application-local.yaml
|
||||
/.pnpm-store/
|
||||
/.angular/
|
||||
.worktrees/
|
||||
docker-data/
|
||||
mariadb/
|
||||
data/
|
||||
books/
|
||||
bookdrop/
|
||||
.env
|
||||
|
||||
+3
-1
@@ -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/
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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();
|
||||
}
|
||||
|
||||
@@ -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());
|
||||
|
||||
@@ -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
|
||||
@@ -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
|
||||
|
||||
@@ -82,6 +82,15 @@
|
||||
[disabled]="!loginForm.valid || !username || !password"
|
||||
class="login-button" />
|
||||
|
||||
<!-- НАЧАЛО: Ссылка на регистрацию -->
|
||||
<div style="text-align: center; margin-top: 1rem; font-size: 0.875rem;">
|
||||
<span>Нет аккаунта?</span>
|
||||
<a routerLink="/register" style="color: var(--primary-color); margin-left: 0.25rem; text-decoration: none; font-weight: 600;">
|
||||
Зарегистрироваться
|
||||
</a>
|
||||
</div>
|
||||
<!-- КОНЕЦ: Ссылка на регистрацию -->
|
||||
|
||||
@if (oidcEnabled) {
|
||||
<div class="divider">
|
||||
<span>{{ t('orContinueWith') }}</span>
|
||||
|
||||
@@ -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']
|
||||
|
||||
@@ -0,0 +1,152 @@
|
||||
<ng-container *transloco="let t; prefix: 'auth.register'">
|
||||
<div class="login-container">
|
||||
<div class="login-card-wrapper">
|
||||
<div class="login-card-border">
|
||||
<div class="login-card">
|
||||
<div class="login-header">
|
||||
<div class="logo-wrapper">
|
||||
<svg class="logo-icon" viewBox="0 0 100 126" fill="none" xmlns="http://www.w3.org/2000/svg">
|
||||
<path d="M25.8062 106.614V113.077V119.537V126L32.2559 119.537L38.7093 126V119.537V113.077V106.614H25.8062Z" fill="var(--color-logo-bookmark)"/>
|
||||
<path d="M38.7093 29.0758H96.7715C98.5535 29.0758 99.9964 27.6307 99.9964 25.846V3.22984C99.9964 1.44512 98.5535 0 96.7715 0H12.9031C10.5512 0 8.35077 0.63224 6.44975 1.73414C4.49102 2.86856 2.86054 4.50155 1.72787 6.4633C0.631268 8.36363 0 10.5674 0 12.923V106.614C0 113.753 5.7752 119.537 12.9031 119.537H21.1529V113.077H12.9031C9.33915 113.077 6.44975 110.183 6.44975 106.614C6.44975 103.044 9.33915 100.15 12.9031 100.15H93.5466C97.1106 100.15 100 97.2566 100 93.6871V41.9988C100 38.4293 97.1106 35.5355 93.5466 35.5355H38.7093C36.9273 35.5355 35.4845 36.9806 35.4845 38.7653V61.3815C35.4845 63.1662 36.9273 64.6113 38.7093 64.6113H67.7404C69.5224 64.6113 70.9653 66.0564 70.9653 67.8412C70.9653 69.6259 69.5224 71.071 67.7404 71.071H38.7093C33.3634 71.071 29.0311 66.732 29.0311 61.3779V38.7617C29.0311 33.4076 33.3634 29.0686 38.7093 29.0686V29.0758Z" fill="url(#register-logo-gradient)"/>
|
||||
<path d="M96.7715 113.077H43.5539V119.537H96.7715C98.5535 119.537 99.9964 118.092 99.9964 116.307C99.9964 114.522 98.5535 113.077 96.7715 113.077Z" fill="url(#register-logo-gradient-secondary)"/>
|
||||
<defs>
|
||||
<linearGradient id="register-logo-gradient" x1="50" y1="0" x2="50" y2="119.537" gradientUnits="userSpaceOnUse">
|
||||
<stop offset="0" style="stop-color: var(--color-logo-start)"/>
|
||||
<stop offset="1" style="stop-color: var(--color-logo-end)"/>
|
||||
</linearGradient>
|
||||
<linearGradient id="register-logo-gradient-secondary" x1="50" y1="0" x2="50" y2="119.537" gradientUnits="userSpaceOnUse">
|
||||
<stop offset="0" style="stop-color: var(--color-logo-start)"/>
|
||||
<stop offset="1" style="stop-color: var(--color-logo-end)"/>
|
||||
</linearGradient>
|
||||
</defs>
|
||||
</svg>
|
||||
</div>
|
||||
<h1 class="login-title">{{ t('title') }}</h1>
|
||||
<p class="login-subtitle">{{ t('subtitle') }}</p>
|
||||
</div>
|
||||
|
||||
@if (errorMessage()) {
|
||||
<div class="error-message" style="margin-bottom: 0.875rem;">
|
||||
<p-message severity="error">{{ errorMessage() }}</p-message>
|
||||
</div>
|
||||
}
|
||||
|
||||
<form class="login-form" #registerForm="ngForm" (ngSubmit)="register()">
|
||||
<div class="form-field">
|
||||
<label for="username" class="form-label">
|
||||
<i class="pi pi-user"></i>
|
||||
<span>{{ t('usernameLabel') }}</span>
|
||||
</label>
|
||||
<input
|
||||
fluid
|
||||
pInputText
|
||||
id="username"
|
||||
name="username"
|
||||
required
|
||||
[(ngModel)]="username"
|
||||
[placeholder]="t('usernamePlaceholder')"
|
||||
autocomplete="username"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<!-- ИСПРАВЛЕНО: name вместо fullName -->
|
||||
<div class="form-field">
|
||||
<label for="name" class="form-label">
|
||||
<i class="pi pi-id-card"></i>
|
||||
<span>{{ t('nameLabel') }}</span>
|
||||
</label>
|
||||
<input
|
||||
fluid
|
||||
pInputText
|
||||
id="name"
|
||||
name="name"
|
||||
required
|
||||
[(ngModel)]="name"
|
||||
[placeholder]="t('namePlaceholder')"
|
||||
autocomplete="name"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div class="form-field">
|
||||
<label for="email" class="form-label">
|
||||
<i class="pi pi-envelope"></i>
|
||||
<span>{{ t('emailLabel') }}</span>
|
||||
</label>
|
||||
<input
|
||||
fluid
|
||||
pInputText
|
||||
id="email"
|
||||
name="email"
|
||||
type="email"
|
||||
required
|
||||
[(ngModel)]="email"
|
||||
[placeholder]="t('emailPlaceholder')"
|
||||
autocomplete="email"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div class="form-field">
|
||||
<label for="password" class="form-label">
|
||||
<i class="pi pi-lock"></i>
|
||||
<span>{{ t('passwordLabel') }}</span>
|
||||
</label>
|
||||
<p-password
|
||||
id="password"
|
||||
name="password"
|
||||
required
|
||||
[(ngModel)]="password"
|
||||
[feedback]="false"
|
||||
[placeholder]="t('passwordPlaceholder')"
|
||||
[toggleMask]="true"
|
||||
[fluid]="true"
|
||||
autocomplete="new-password"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div class="form-field">
|
||||
<label for="confirmPassword" class="form-label">
|
||||
<i class="pi pi-lock"></i>
|
||||
<span>{{ t('confirmPasswordLabel') }}</span>
|
||||
</label>
|
||||
<p-password
|
||||
id="confirmPassword"
|
||||
name="confirmPassword"
|
||||
required
|
||||
[(ngModel)]="confirmPassword"
|
||||
[feedback]="false"
|
||||
[placeholder]="t('confirmPasswordPlaceholder')"
|
||||
[toggleMask]="true"
|
||||
[fluid]="true"
|
||||
autocomplete="new-password"
|
||||
/>
|
||||
@if (passwordMismatch) {
|
||||
<small class="error-text">{{ t('passwordMismatch') }}</small>
|
||||
}
|
||||
</div>
|
||||
|
||||
<p-button
|
||||
fluid
|
||||
type="submit"
|
||||
[label]="t('signUp')"
|
||||
icon="pi pi-user-plus"
|
||||
[disabled]="!registerForm.valid || passwordMismatch || isRegistering()"
|
||||
[loading]="isRegistering()"
|
||||
class="login-button" />
|
||||
</form>
|
||||
|
||||
<div class="divider">
|
||||
<span>{{ t('or') }}</span>
|
||||
</div>
|
||||
|
||||
<p-button
|
||||
fluid
|
||||
severity="secondary"
|
||||
[label]="t('backToLogin')"
|
||||
icon="pi pi-arrow-left"
|
||||
routerLink="/login"
|
||||
class="back-button" />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</ng-container>
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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<RegisterComponent>;
|
||||
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.');
|
||||
});
|
||||
});
|
||||
@@ -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<string | null>(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.');
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -39,6 +39,11 @@ export class AuthService {
|
||||
readonly token = signal<string | null>(this.getInternalAccessToken());
|
||||
readonly isAuthenticated = computed(() => !!this.token());
|
||||
|
||||
// === ИСПРАВЛЕНО: поле name вместо fullName, регистрация возвращает void ===
|
||||
register(credentials: { username: string; password: string; email?: string; name?: string }): Observable<void> {
|
||||
return this.http.post<void>(`${this.apiUrl}/register`, credentials);
|
||||
}
|
||||
|
||||
internalLogin(credentials: { username: string; password: string }): Observable<AccessTokenResponse> {
|
||||
return this.http.post<AccessTokenResponse>(`${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;
|
||||
|
||||
|
||||
@@ -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": {
|
||||
|
||||
@@ -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": {
|
||||
|
||||
Reference in New Issue
Block a user