Implement OIDC authentication
This commit is contained in:
committed by
Aditya Chandel
parent
548e09ae2c
commit
817b572c08
@@ -9,13 +9,26 @@ import {PdfViewerComponent} from './book/components/pdf-viewer/pdf-viewer.compon
|
||||
import {EpubViewerComponent} from './book/components/epub-viewer/component/epub-viewer.component';
|
||||
import {ChangePasswordComponent} from './core/component/change-password/change-password.component';
|
||||
import {BookMetadataCenterComponent} from './metadata/book-metadata-center/book-metadata-center.component';
|
||||
import {SetupComponent} from './setup/setup.component';
|
||||
import {SetupGuard} from './setup/setup.guard';
|
||||
import {SetupRedirectGuard} from './setup/setup-redirect.guard';
|
||||
import {EmptyComponent} from './empty/empty.component';
|
||||
import {LoginGuard} from './setup/ login.guard';
|
||||
import {OidcCallbackComponent} from './oidc-callback/oidc-callback.component';
|
||||
|
||||
export const routes: Routes = [
|
||||
{
|
||||
path: '',
|
||||
redirectTo: 'dashboard',
|
||||
pathMatch: 'full'
|
||||
canActivate: [SetupRedirectGuard],
|
||||
pathMatch: 'full',
|
||||
component: EmptyComponent
|
||||
},
|
||||
{
|
||||
path: 'setup',
|
||||
component: SetupComponent,
|
||||
canActivate: [SetupGuard]
|
||||
},
|
||||
{path: 'oauth2-callback', component: OidcCallbackComponent},
|
||||
{
|
||||
path: '',
|
||||
component: AppLayoutComponent,
|
||||
@@ -38,7 +51,19 @@ export const routes: Routes = [
|
||||
component: EpubViewerComponent,
|
||||
canActivate: [AuthGuard]
|
||||
},
|
||||
{path: 'login', component: LoginComponent},
|
||||
{path: 'change-password', component: ChangePasswordComponent},
|
||||
{path: '**', redirectTo: 'login', pathMatch: 'full'}
|
||||
{
|
||||
path: 'login',
|
||||
component: LoginComponent,
|
||||
canActivate: [LoginGuard]
|
||||
},
|
||||
{
|
||||
path: 'change-password',
|
||||
component: ChangePasswordComponent,
|
||||
canActivate: [SetupGuard]
|
||||
},
|
||||
{
|
||||
path: '**',
|
||||
redirectTo: 'login',
|
||||
pathMatch: 'full'
|
||||
}
|
||||
];
|
||||
|
||||
@@ -0,0 +1,52 @@
|
||||
import {inject} from '@angular/core';
|
||||
import {OAuthEvent, OAuthService} from 'angular-oauth2-oidc';
|
||||
import {AppSettingsService} from './core/service/app-settings.service';
|
||||
import {AuthService, websocketInitializer} from './core/service/auth.service';
|
||||
import {filter} from 'rxjs/operators';
|
||||
|
||||
export function initializeAuthFactory() {
|
||||
return () => {
|
||||
const oauthService = inject(OAuthService);
|
||||
const appSettingsService = inject(AppSettingsService);
|
||||
const authService = inject(AuthService);
|
||||
|
||||
return new Promise<void>((resolve) => {
|
||||
const sub = appSettingsService.appSettings$.subscribe(settings => {
|
||||
if (settings) {
|
||||
if (settings.oidcEnabled && settings.oidcProviderDetails) {
|
||||
const details = settings.oidcProviderDetails;
|
||||
oauthService.configure({
|
||||
issuer: details.issuerUri,
|
||||
clientId: details.clientId,
|
||||
scope: 'openid profile email offline_access',
|
||||
redirectUri: window.location.origin + '/oauth2-callback',
|
||||
responseType: 'code',
|
||||
showDebugInformation: true,
|
||||
requireHttps: false,
|
||||
strictDiscoveryDocumentValidation: false,
|
||||
});
|
||||
|
||||
oauthService.events
|
||||
.pipe(filter((e: OAuthEvent) =>
|
||||
e.type === 'token_received' || e.type === 'token_refreshed'
|
||||
))
|
||||
.subscribe((e: OAuthEvent) => {
|
||||
const accessToken = oauthService.getAccessToken();
|
||||
const refreshToken = oauthService.getRefreshToken();
|
||||
authService.saveOidcTokens(accessToken, refreshToken ?? '');
|
||||
});
|
||||
|
||||
oauthService.loadDiscoveryDocumentAndTryLogin().then(() => {
|
||||
oauthService.setupAutomaticSilentRefresh();
|
||||
websocketInitializer(authService);
|
||||
resolve();
|
||||
});
|
||||
} else {
|
||||
resolve();
|
||||
}
|
||||
sub.unsubscribe();
|
||||
}
|
||||
});
|
||||
});
|
||||
};
|
||||
}
|
||||
@@ -4,23 +4,24 @@ import {Router} from '@angular/router';
|
||||
import {catchError, filter, switchMap, take} from 'rxjs/operators';
|
||||
import {BehaviorSubject, Observable, throwError} from 'rxjs';
|
||||
import {AuthService} from './core/service/auth.service';
|
||||
import {API_CONFIG} from './config/api-config';
|
||||
|
||||
export const AuthInterceptorService: HttpInterceptorFn = (req, next: HttpHandlerFn) => {
|
||||
const authService = inject(AuthService);
|
||||
const router = inject(Router);
|
||||
const token = authService.getToken();
|
||||
let authReq = req;
|
||||
|
||||
if (token) {
|
||||
authReq = req.clone({
|
||||
setHeaders: {Authorization: `Bearer ${token}`}
|
||||
});
|
||||
}
|
||||
const internalToken = authService.getInternalAccessToken();
|
||||
const oidcToken = authService.getOidcAccessToken();
|
||||
const token = internalToken || oidcToken;
|
||||
|
||||
const isApiRequest = req.url.startsWith(`${API_CONFIG.BASE_URL}/api/`);
|
||||
|
||||
const authReq = (token && isApiRequest) ? req.clone({ setHeaders: { Authorization: `Bearer ${token}` } }) : req;
|
||||
|
||||
return next(authReq).pipe(
|
||||
catchError((error: HttpErrorResponse) => {
|
||||
if (error.status === 401 || error.status === 403) {
|
||||
return handle401Error(authService, authReq, next, router);
|
||||
return handle401Error(authService, authReq, next, router, !!internalToken);
|
||||
}
|
||||
return throwError(() => error);
|
||||
})
|
||||
@@ -30,32 +31,49 @@ export const AuthInterceptorService: HttpInterceptorFn = (req, next: HttpHandler
|
||||
let isRefreshing = false;
|
||||
const refreshTokenSubject = new BehaviorSubject<string | null>(null);
|
||||
|
||||
function handle401Error(authService: AuthService, request: HttpRequest<any>, next: HttpHandlerFn, router: Router): Observable<any> {
|
||||
if (!isRefreshing) {
|
||||
function handle401Error(authService: AuthService, request: HttpRequest<any>, next: HttpHandlerFn, router: Router, isInternal: boolean): Observable<any> {
|
||||
if (!isRefreshing && isInternal) {
|
||||
isRefreshing = true;
|
||||
refreshTokenSubject.next(null);
|
||||
|
||||
return authService.refreshToken().pipe(
|
||||
switchMap((response) => {
|
||||
return authService.internalRefreshToken().pipe(
|
||||
switchMap(response => {
|
||||
isRefreshing = false;
|
||||
refreshTokenSubject.next(response.accessToken);
|
||||
if (response.accessToken && response.refreshToken) {
|
||||
authService.saveTokens(response.accessToken, response.refreshToken);
|
||||
const { accessToken, refreshToken } = response;
|
||||
if (accessToken && refreshToken) {
|
||||
authService.saveInternalTokens(accessToken, refreshToken);
|
||||
refreshTokenSubject.next(accessToken);
|
||||
}
|
||||
return next(request.clone({setHeaders: {Authorization: `Bearer ${response.accessToken}`}}));
|
||||
return next(request.clone({
|
||||
setHeaders: { Authorization: `Bearer ${accessToken}` }
|
||||
}));
|
||||
}),
|
||||
catchError((err) => {
|
||||
catchError(err => {
|
||||
isRefreshing = false;
|
||||
authService.logout();
|
||||
router.navigate(['/login']);
|
||||
forceLogout(authService, router);
|
||||
return throwError(() => err);
|
||||
})
|
||||
);
|
||||
} else {
|
||||
}
|
||||
|
||||
if (isRefreshing && isInternal) {
|
||||
return refreshTokenSubject.pipe(
|
||||
filter(token => token !== null),
|
||||
take(1),
|
||||
switchMap((token) => next(request.clone({setHeaders: {Authorization: `Bearer ${token}`}})))
|
||||
switchMap(token =>
|
||||
next(request.clone({
|
||||
setHeaders: { Authorization: `Bearer ${token}` }
|
||||
}))
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
forceLogout(authService, router, isInternal ? 'Session expired, please log in again.' : 'OIDC token expired, please log in again.');
|
||||
return throwError(() => new Error('Authentication failed, please log in.'));
|
||||
}
|
||||
|
||||
function forceLogout(authService: AuthService, router: Router, message?: string): void {
|
||||
authService.logout();
|
||||
router.navigate(['/login']);
|
||||
if (message) console.warn(message);
|
||||
}
|
||||
|
||||
@@ -1,21 +1,35 @@
|
||||
import {inject} from '@angular/core';
|
||||
import {CanActivateFn, Router} from '@angular/router';
|
||||
import { inject } from '@angular/core';
|
||||
import { CanActivateFn } from '@angular/router';
|
||||
import { Router } from '@angular/router';
|
||||
import { OAuthService } from 'angular-oauth2-oidc';
|
||||
|
||||
export const AuthGuard: CanActivateFn = (route, state) => {
|
||||
const router = inject(Router);
|
||||
const token = localStorage.getItem('accessToken');
|
||||
|
||||
if (!token) {
|
||||
router.navigate(['/login']);
|
||||
return false;
|
||||
const legacyToken = localStorage.getItem('accessToken_Internal');
|
||||
|
||||
if (legacyToken) {
|
||||
try {
|
||||
const payload = JSON.parse(atob(legacyToken.split('.')[1]));
|
||||
if (payload.isDefaultPassword) {
|
||||
router.navigate(['/change-password']);
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
} catch (e) {
|
||||
console.error('Invalid legacy token:', e);
|
||||
localStorage.removeItem('accessToken');
|
||||
router.navigate(['/login']);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
const payload = JSON.parse(atob(token.split('.')[1]));
|
||||
const oidcToken = localStorage.getItem('accessToken_OIDC');
|
||||
|
||||
if (payload.isDefaultPassword) {
|
||||
router.navigate(['/change-password']);
|
||||
return false;
|
||||
if (oidcToken) {
|
||||
return true;
|
||||
}
|
||||
|
||||
return true;
|
||||
router.navigate(['/login']);
|
||||
return false;
|
||||
};
|
||||
|
||||
@@ -101,7 +101,7 @@
|
||||
</div>
|
||||
<div class="no-books-container" *ngIf="!bookState?.error && bookState?.loaded && bookState?.books?.length === 0">
|
||||
<p class="no-books-text">
|
||||
{{ entityType === EntityType.LIBRARY ? "This library has no books!" : "This shelf has no books!" }}
|
||||
This collection has no books!
|
||||
</p>
|
||||
</div>
|
||||
|
||||
|
||||
@@ -1,26 +1,35 @@
|
||||
<div class="login-container">
|
||||
<div class="login-container" >
|
||||
<div class="login-wrapper">
|
||||
<h1 class="app-title">BookLore</h1>
|
||||
<p-card class="login-card p-fluid">
|
||||
<ng-template pTemplate="title">Login</ng-template>
|
||||
|
||||
<p-card class="w-96">
|
||||
<ng-template pTemplate="title">
|
||||
<div class="text-center pb-2">Login</div>
|
||||
</ng-template>
|
||||
<ng-template pTemplate="content">
|
||||
<form #loginForm="ngForm" (ngSubmit)="login()">
|
||||
<div class="p-field">
|
||||
<form class="flex flex-col gap-4" #loginForm="ngForm" (ngSubmit)="login()">
|
||||
<div class="flex flex-col gap-2">
|
||||
<label for="username">Username</label>
|
||||
<input pInputText id="username" [(ngModel)]="username" name="username" required fluid/>
|
||||
<input fluid pInputText id="username" [(ngModel)]="username" name="username" required/>
|
||||
</div>
|
||||
|
||||
<div class="p-field">
|
||||
<div class="flex flex-col gap-2">
|
||||
<label for="password">Password</label>
|
||||
<p-password id="password" [(ngModel)]="password" name="password" [feedback]="false" fluid required></p-password>
|
||||
<p-password fluid id="password" [(ngModel)]="password" name="password" [feedback]="false" required></p-password>
|
||||
</div>
|
||||
|
||||
<div class="p-mt-3">
|
||||
<p-button type="submit" label="Login" icon="pi pi-sign-in" class="p-fluid"></p-button>
|
||||
<div class="flex flex-col gap-3 mt-4">
|
||||
<p-button
|
||||
fluid
|
||||
severity="primary"
|
||||
type="submit"
|
||||
label="Login"
|
||||
icon="pi pi-sign-in"
|
||||
[disabled]="!loginForm.valid || !username || !password">
|
||||
</p-button>
|
||||
<p-message *ngIf="errorMessage" severity="error" text="{{ errorMessage }}"></p-message>
|
||||
<div *ngIf="oidcEnabled">
|
||||
<p-divider></p-divider>
|
||||
<p-button fluid severity="info" type="button" label="Login with OIDC" icon="pi pi-id-card" (click)="loginWithOidc()"></p-button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<p-message *ngIf="errorMessage" severity="error" text="{{ errorMessage }}"></p-message>
|
||||
</form>
|
||||
</ng-template>
|
||||
</p-card>
|
||||
|
||||
@@ -1,28 +1,25 @@
|
||||
.login-container {
|
||||
@apply flex items-center justify-center min-h-screen bg-gradient-to-br from-blue-900 via-cyan-600 to-blue-400 relative;
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
align-items: center;
|
||||
min-height: 100vh;
|
||||
background: linear-gradient(to bottom right, #1e3a8a, #06b6d4, #3b82f6);
|
||||
position: relative;
|
||||
}
|
||||
|
||||
.login-wrapper {
|
||||
@apply flex flex-col items-center gap-6 absolute top-1/4 transform -translate-y-1/4;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
gap: 1.5rem;
|
||||
position: absolute;
|
||||
top: 25%;
|
||||
transform: translateY(-25%);
|
||||
}
|
||||
|
||||
.app-title {
|
||||
@apply text-5xl font-extrabold text-white drop-shadow-lg;
|
||||
font-size: 3rem;
|
||||
font-weight: 800;
|
||||
color: white;
|
||||
text-shadow: 0px 4px 6px rgba(0, 0, 0, 0.3);
|
||||
}
|
||||
|
||||
.login-card {
|
||||
@apply w-96 shadow-lg rounded-xl bg-opacity-90 backdrop-blur-lg;
|
||||
}
|
||||
|
||||
form {
|
||||
@apply flex flex-col gap-4;
|
||||
}
|
||||
|
||||
.p-field {
|
||||
@apply flex flex-col gap-2;
|
||||
}
|
||||
|
||||
p-button {
|
||||
@apply mt-4;
|
||||
}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import {Component} from '@angular/core';
|
||||
import {Component, inject, OnInit} from '@angular/core';
|
||||
import {AuthService} from '../../service/auth.service';
|
||||
import {Router} from '@angular/router';
|
||||
import {FormsModule} from '@angular/forms';
|
||||
@@ -9,6 +9,12 @@ import {Button} from 'primeng/button';
|
||||
import {Message} from 'primeng/message';
|
||||
import {PrimeTemplate} from 'primeng/api';
|
||||
import {InputText} from 'primeng/inputtext';
|
||||
import {OAuthService} from 'angular-oauth2-oidc';
|
||||
import {Divider} from 'primeng/divider';
|
||||
import {AppSettingsService} from '../../service/app-settings.service';
|
||||
import {AppSettings} from '../../model/app-settings.model';
|
||||
import {Observable} from 'rxjs';
|
||||
import {filter, take} from 'rxjs/operators';
|
||||
|
||||
@Component({
|
||||
selector: 'app-login',
|
||||
@@ -20,26 +26,38 @@ import {InputText} from 'primeng/inputtext';
|
||||
Button,
|
||||
Message,
|
||||
PrimeTemplate,
|
||||
InputText
|
||||
InputText,
|
||||
Divider
|
||||
],
|
||||
templateUrl: './login.component.html',
|
||||
styleUrl: './login.component.scss'
|
||||
styleUrls: ['./login.component.scss']
|
||||
})
|
||||
export class LoginComponent {
|
||||
export class LoginComponent implements OnInit {
|
||||
username = '';
|
||||
password = '';
|
||||
errorMessage = '';
|
||||
oidcEnabled = false;
|
||||
|
||||
constructor(private authService: AuthService, private router: Router) {
|
||||
this.authService.remoteLogin().subscribe({
|
||||
next: () => {
|
||||
this.router.navigate(['/dashboard']);
|
||||
},
|
||||
});
|
||||
private authService = inject(AuthService);
|
||||
private oAuthService = inject(OAuthService);
|
||||
private appSettingsService = inject(AppSettingsService);
|
||||
private router = inject(Router);
|
||||
|
||||
appSettings$: Observable<AppSettings | null> = this.appSettingsService.appSettings$;
|
||||
|
||||
ngOnInit(): void {
|
||||
this.appSettings$
|
||||
.pipe(
|
||||
filter(settings => settings != null),
|
||||
take(1)
|
||||
)
|
||||
.subscribe(settings => {
|
||||
this.oidcEnabled = settings?.oidcEnabled;
|
||||
});
|
||||
}
|
||||
|
||||
login(): void {
|
||||
this.authService.login({username: this.username, password: this.password}).subscribe({
|
||||
this.authService.internalLogin({username: this.username, password: this.password}).subscribe({
|
||||
next: (response) => {
|
||||
if (response.isDefaultPassword === 'true') {
|
||||
this.router.navigate(['/change-password']);
|
||||
@@ -56,4 +74,8 @@ export class LoginComponent {
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
loginWithOidc(): void {
|
||||
this.oAuthService.initImplicitFlow();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,5 +1,23 @@
|
||||
import {MetadataRefreshOptions} from '../../metadata/model/request/metadata-refresh-options.model';
|
||||
|
||||
export interface OidcProviderDetails {
|
||||
providerName: string;
|
||||
clientId: string;
|
||||
issuerUri: string;
|
||||
jwksUrl: string;
|
||||
claimMapping: {
|
||||
username: string;
|
||||
email: string;
|
||||
name: string;
|
||||
};
|
||||
}
|
||||
|
||||
export interface OidcAutoProvisionDetails {
|
||||
enableAutoProvisioning: boolean;
|
||||
defaultPermissions: string[];
|
||||
defaultLibraryIds: number[];
|
||||
}
|
||||
|
||||
export interface AppSettings {
|
||||
autoBookSearch: boolean;
|
||||
similarBookRecommendation: boolean;
|
||||
@@ -7,4 +25,7 @@ export interface AppSettings {
|
||||
coverResolution: string;
|
||||
uploadPattern: string;
|
||||
opdsServerEnabled: boolean;
|
||||
oidcEnabled: boolean;
|
||||
oidcProviderDetails: OidcProviderDetails;
|
||||
oidcAutoProvisionDetails: OidcAutoProvisionDetails;
|
||||
}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import {Injectable} from '@angular/core';
|
||||
import {HttpClient, HttpParams} from '@angular/common/http';
|
||||
import {HttpClient} from '@angular/common/http';
|
||||
import {BehaviorSubject, Observable, of} from 'rxjs';
|
||||
import {AppSettings} from '../model/app-settings.model';
|
||||
import {API_CONFIG} from '../../config/api-config';
|
||||
|
||||
@@ -3,6 +3,7 @@ import {HttpClient} from '@angular/common/http';
|
||||
import {Observable, tap} from 'rxjs';
|
||||
import {RxStompService} from '../../shared/websocket/rx-stomp.service';
|
||||
import {API_CONFIG} from '../../config/api-config';
|
||||
import {createRxStompConfig} from '../../shared/websocket/rx-stomp.config';
|
||||
|
||||
@Injectable({
|
||||
providedIn: 'root',
|
||||
@@ -15,62 +16,76 @@ export class AuthService {
|
||||
private http = inject(HttpClient);
|
||||
private injector = inject(Injector);
|
||||
|
||||
login(credentials: { username: string; password: string }): Observable<any> {
|
||||
internalLogin(credentials: { username: string; password: string }): Observable<any> {
|
||||
return this.http.post<{ accessToken: string; refreshToken: string }>(`${this.apiUrl}/login`, credentials).pipe(
|
||||
tap((response) => {
|
||||
if (response.accessToken && response.refreshToken) {
|
||||
this.saveTokens(response.accessToken, response.refreshToken);
|
||||
this.getRxStompService().activate();
|
||||
this.saveInternalTokens(response.accessToken, response.refreshToken);
|
||||
this.initializeWebSocketConnection();
|
||||
}
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
remoteLogin(): Observable<any> {
|
||||
return this.http.get<{ accessToken: string; refreshToken: string }>(`${this.apiUrl}/remote`).pipe(
|
||||
tap((response) => {
|
||||
if (response.accessToken && response.refreshToken) {
|
||||
this.saveTokens(response.accessToken, response.refreshToken);
|
||||
this.getRxStompService().activate();
|
||||
}
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
refreshToken(): Observable<{ accessToken: string; refreshToken: string }> {
|
||||
const refreshToken = this.getRefreshToken();
|
||||
internalRefreshToken(): Observable<{ accessToken: string; refreshToken: string }> {
|
||||
const refreshToken = this.getInternalRefreshToken();
|
||||
return this.http.post<{ accessToken: string; refreshToken: string }>(`${this.apiUrl}/refresh`, {refreshToken}).pipe(
|
||||
tap((response) => {
|
||||
if (response.accessToken && response.refreshToken) {
|
||||
this.saveTokens(response.accessToken, response.refreshToken);
|
||||
this.saveInternalTokens(response.accessToken, response.refreshToken);
|
||||
}
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
saveTokens(accessToken: string, refreshToken: string): void {
|
||||
localStorage.setItem('accessToken', accessToken);
|
||||
localStorage.setItem('refreshToken', refreshToken);
|
||||
saveInternalTokens(accessToken: string, refreshToken: string): void {
|
||||
localStorage.setItem('accessToken_Internal', accessToken);
|
||||
localStorage.setItem('refreshToken_Internal', refreshToken);
|
||||
}
|
||||
|
||||
getToken(): string | null {
|
||||
return localStorage.getItem('accessToken');
|
||||
saveOidcTokens(accessToken: string, refreshToken: string): void {
|
||||
localStorage.setItem('accessToken_OIDC', accessToken);
|
||||
localStorage.setItem('refreshToken_OIDC', refreshToken);
|
||||
}
|
||||
|
||||
getRefreshToken(): string | null {
|
||||
return localStorage.getItem('refreshToken');
|
||||
getInternalAccessToken(): string | null {
|
||||
return localStorage.getItem('accessToken_Internal');
|
||||
}
|
||||
|
||||
getOidcAccessToken(): string | null {
|
||||
return localStorage.getItem('accessToken_OIDC');
|
||||
}
|
||||
|
||||
getInternalRefreshToken(): string | null {
|
||||
return localStorage.getItem('refreshToken_Internal');
|
||||
}
|
||||
|
||||
logout(): void {
|
||||
localStorage.removeItem('accessToken');
|
||||
localStorage.removeItem('refreshToken');
|
||||
localStorage.removeItem('accessToken_Internal');
|
||||
localStorage.removeItem('refreshToken_Internal');
|
||||
localStorage.removeItem('accessToken_OIDC');
|
||||
localStorage.removeItem('refreshToken_OIDC');
|
||||
this.getRxStompService().deactivate();
|
||||
}
|
||||
|
||||
private getRxStompService(): RxStompService {
|
||||
getRxStompService(): RxStompService {
|
||||
if (!this.rxStompService) {
|
||||
this.rxStompService = this.injector.get(RxStompService);
|
||||
}
|
||||
return this.rxStompService;
|
||||
}
|
||||
|
||||
initializeWebSocketConnection(): void {
|
||||
const token = this.getOidcAccessToken() || this.getInternalAccessToken();
|
||||
if (!token) return;
|
||||
|
||||
const stompService = this.getRxStompService();
|
||||
const config = createRxStompConfig(this);
|
||||
stompService.updateConfig(config);
|
||||
stompService.activate();
|
||||
}
|
||||
}
|
||||
|
||||
export function websocketInitializer(authService: AuthService): () => void {
|
||||
return () => authService.initializeWebSocketConnection();
|
||||
}
|
||||
|
||||
@@ -0,0 +1 @@
|
||||
<p>empty works!</p>
|
||||
@@ -0,0 +1,11 @@
|
||||
import { Component } from '@angular/core';
|
||||
|
||||
@Component({
|
||||
selector: 'app-empty',
|
||||
imports: [],
|
||||
templateUrl: './empty.component.html',
|
||||
styleUrl: './empty.component.scss'
|
||||
})
|
||||
export class EmptyComponent {
|
||||
|
||||
}
|
||||
@@ -0,0 +1,200 @@
|
||||
<div class="w-full h-[calc(100vh-12.1rem)] overflow-y-auto border rounded-lg enclosing-container">
|
||||
|
||||
<div class="p-4">
|
||||
<p class="text-xl gap-2 pb-4 pt-6">Internal Authentication:</p>
|
||||
<div class="flex items-center gap-4 pl-6">
|
||||
<label class="text-lg">Enabled</label>
|
||||
<p-checkbox
|
||||
[(ngModel)]="internalAuthEnabled"
|
||||
[binary]="true"
|
||||
[disabled]="true">
|
||||
</p-checkbox>
|
||||
<div class="flex items-center gap-2 pl-4 text-sm text-gray-400">
|
||||
<i class="pi pi-info-circle text-blue-500"></i>
|
||||
<span>
|
||||
Internal authentication is always enabled and cannot be disabled. However, OIDC can be used alongside internal authentication if OIDC is enabled.
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<p-divider></p-divider>
|
||||
|
||||
<div class="p-4">
|
||||
<p class="text-xl pb-4 pt-2">OIDC Authentication (Experimental):</p>
|
||||
<div class="flex items-center gap-4">
|
||||
<label class="text-lg pl-6">Enabled</label>
|
||||
<p-toggleswitch
|
||||
[(ngModel)]="oidcEnabled"
|
||||
[disabled]="!isOidcFormComplete()"
|
||||
(onChange)="toggleOidcEnabled()">
|
||||
</p-toggleswitch>
|
||||
<div *ngIf="!isOidcFormComplete()" class="text-sm text-gray-400">
|
||||
(Fill all required fields to enable)
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<p class="text-lg pt-8">OIDC Provider Settings:</p>
|
||||
<div class="pl-6 space-y-6 p-4 m-4 custom-border">
|
||||
<div class="grid grid-cols-1 md:grid-cols-2 gap-4 max-w-4xl">
|
||||
<div>
|
||||
<label for="providerName" class="mb-1">Provider Name</label>
|
||||
<input
|
||||
pInputText
|
||||
id="providerName"
|
||||
[(ngModel)]="oidcProvider.providerName"
|
||||
placeholder="e.g. Authentik"
|
||||
class="w-full"/>
|
||||
</div>
|
||||
<div>
|
||||
<label for="clientId" class="mb-1">Client ID</label>
|
||||
<input
|
||||
pInputText
|
||||
id="clientId"
|
||||
[(ngModel)]="oidcProvider.clientId"
|
||||
placeholder="e.g. my-client-id"
|
||||
class="w-full"/>
|
||||
</div>
|
||||
<div class="md:col-span-2 items-center">
|
||||
<label for="scope" class="mb-1">Scope</label>
|
||||
<input
|
||||
pInputText
|
||||
id="scope"
|
||||
class="w-full"
|
||||
[readonly]="true"
|
||||
disabled="disabled"
|
||||
value="openid profile email offline_access"/>
|
||||
<div class="flex items-center gap-2 text-sm text-gray-400 mt-2 pl-1">
|
||||
<i class="pi pi-info-circle text-blue-500 mt-1"></i>
|
||||
<span>
|
||||
Required scopes for OIDC login and token exchange. Must be supported and advertised in the provider’s discovery metadata.
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
<div class="md:col-span-2">
|
||||
<label for="issuerUri" class="mb-1">Issuer URI</label>
|
||||
<input
|
||||
pInputText
|
||||
id="issuerUri"
|
||||
[(ngModel)]="oidcProvider.issuerUri"
|
||||
placeholder="e.g. https://auth.example.com/realms/myrealm"
|
||||
class="w-full"/>
|
||||
</div>
|
||||
<div class="md:col-span-2">
|
||||
<label for="jwksUrl" class="mb-1">JWKS URL</label>
|
||||
<input
|
||||
pInputText
|
||||
id="jwksUrl"
|
||||
[(ngModel)]="oidcProvider.jwksUrl"
|
||||
placeholder="e.g. https://auth.example.com/realms/myrealm/protocol/openid-connect/certs"
|
||||
class="w-full"/>
|
||||
</div>
|
||||
<div class="md:col-span-2">
|
||||
<div class="grid grid-cols-1 md:grid-cols-3 gap-4">
|
||||
<div>
|
||||
<label for="claimUsername" class="mb-1">Username Claim</label>
|
||||
<input
|
||||
pInputText
|
||||
id="claimUsername"
|
||||
[(ngModel)]="oidcProvider.claimMapping.username"
|
||||
placeholder="e.g. preferred_username"
|
||||
class="w-full"/>
|
||||
</div>
|
||||
<div>
|
||||
<label for="claimEmail" class="mb-1">Email Claim</label>
|
||||
<input
|
||||
pInputText
|
||||
id="claimEmail"
|
||||
[(ngModel)]="oidcProvider.claimMapping.email"
|
||||
placeholder="e.g. email"
|
||||
class="w-full"/>
|
||||
</div>
|
||||
<div>
|
||||
<label for="claimName" class="mb-1">Display Name Claim</label>
|
||||
<input
|
||||
pInputText
|
||||
id="claimName"
|
||||
[(ngModel)]="oidcProvider.claimMapping.name"
|
||||
placeholder="e.g. name or given_name"
|
||||
class="w-full"/>
|
||||
</div>
|
||||
</div>
|
||||
<div class="flex items-start gap-2 text-sm text-gray-400 mt-2 pl-1">
|
||||
<i class="pi pi-info-circle text-blue-500 mt-1"></i>
|
||||
<span>
|
||||
These claims are used by Booklore to provision new OIDC users with their name, username, and email. Ensure they match the claims provided by your OIDC provider.
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
<p-button
|
||||
[outlined]="true"
|
||||
type="button"
|
||||
label="Save Settings"
|
||||
class="p-button-primary w-full sm:w-auto"
|
||||
(click)="saveOidcProvider()"
|
||||
[disabled]="!isOidcFormComplete()">
|
||||
</p-button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div *ngIf="oidcEnabled">
|
||||
<p class="text-lg pt-6">OIDC User Provisioning:</p>
|
||||
<div class="pl-6 space-y-6 p-4 m-4 custom-border">
|
||||
<div>
|
||||
<p class="text-xl pb-3">Automatic user provisioning:</p>
|
||||
<div class="flex items-center gap-4 pl-6">
|
||||
<label class="text-lg">Enabled</label>
|
||||
<p-toggleswitch
|
||||
[(ngModel)]="autoUserProvisioningEnabled"
|
||||
inputId="autoProvision"
|
||||
(onChange)="saveAutoProvision()">
|
||||
</p-toggleswitch>
|
||||
<div class="flex items-center gap-2 text-sm text-gray-400">
|
||||
<i class="pi pi-info-circle text-blue-500"></i>
|
||||
<span>
|
||||
Enabling auto-provisioning ensures that new users are automatically created with the selected default permissions. If turned off, users must be manually created in Booklore before they can log in.
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div *ngIf="autoUserProvisioningEnabled">
|
||||
<p class="text-lg pt-8">Default permissions for auto-provisioned users:</p>
|
||||
<div class="flex items-center gap-2 pl-6 pt-2">
|
||||
<p-checkbox
|
||||
[binary]="true"
|
||||
[disabled]="true"
|
||||
[ngModel]="true"
|
||||
inputId="permissionRead">
|
||||
</p-checkbox>
|
||||
<label class="text-sm">Read Books</label>
|
||||
</div>
|
||||
|
||||
<div *ngFor="let perm of availablePermissions" class="flex items-center gap-2 pl-6">
|
||||
<p-checkbox
|
||||
[(ngModel)]="perm.selected"
|
||||
[binary]="true"
|
||||
[inputId]="perm.value">
|
||||
</p-checkbox>
|
||||
<label [for]="perm.value" class="text-sm">{{ perm.label }}</label>
|
||||
</div>
|
||||
|
||||
<p class="text-lg pb-3 pt-6">Default libraries for auto-provisioned users:</p>
|
||||
<div class="pl-6">
|
||||
<p-multiSelect
|
||||
[options]="allLibraries"
|
||||
optionLabel="name"
|
||||
optionValue="id"
|
||||
[(ngModel)]="editingLibraryIds"
|
||||
placeholder="Select Libraries"
|
||||
appendTo="body">
|
||||
</p-multiSelect>
|
||||
</div>
|
||||
<div class="mt-8">
|
||||
<p-button label="Save Settings" [outlined]="true" (click)="saveAutoProvisioningSettings()"></p-button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
@@ -0,0 +1,8 @@
|
||||
.enclosing-container {
|
||||
border-color: var(--p-content-border-color);
|
||||
}
|
||||
|
||||
.custom-border {
|
||||
border: 1px solid var(--border-color);
|
||||
border-radius: var(--card-border);
|
||||
}
|
||||
@@ -0,0 +1,239 @@
|
||||
import {Component, inject, OnInit} from '@angular/core';
|
||||
import {FormsModule, ReactiveFormsModule} from '@angular/forms';
|
||||
import {InputText} from 'primeng/inputtext';
|
||||
import {Button} from 'primeng/button';
|
||||
import {DropdownModule} from 'primeng/dropdown';
|
||||
import {NgForOf, NgIf} from '@angular/common';
|
||||
import {Checkbox} from 'primeng/checkbox';
|
||||
import {ToggleSwitch} from 'primeng/toggleswitch';
|
||||
import {MessageService} from 'primeng/api';
|
||||
import {AppSettingsService} from '../core/service/app-settings.service';
|
||||
import {Observable} from 'rxjs';
|
||||
import {AppSettings, OidcProviderDetails} from '../core/model/app-settings.model';
|
||||
import {filter, take} from 'rxjs/operators';
|
||||
import {Divider} from 'primeng/divider';
|
||||
import {MultiSelect} from 'primeng/multiselect';
|
||||
import {Library} from '../book/model/library.model';
|
||||
import {LibraryService} from '../book/service/library.service';
|
||||
|
||||
@Component({
|
||||
selector: 'app-authentication-settings',
|
||||
templateUrl: './authentication-settings.component.html',
|
||||
standalone: true,
|
||||
imports: [
|
||||
FormsModule,
|
||||
InputText,
|
||||
DropdownModule,
|
||||
NgIf,
|
||||
NgForOf,
|
||||
Checkbox,
|
||||
ToggleSwitch,
|
||||
Divider,
|
||||
Button,
|
||||
MultiSelect,
|
||||
ReactiveFormsModule
|
||||
],
|
||||
styleUrls: ['./authentication-settings.component.scss']
|
||||
})
|
||||
export class AuthenticationSettingsComponent implements OnInit {
|
||||
availablePermissions = [
|
||||
{label: 'Upload Books', value: 'permissionUpload', selected: false},
|
||||
{label: 'Download Books', value: 'permissionDownload', selected: false},
|
||||
{label: 'Edit Book Metadata', value: 'permissionEditMetadata', selected: false},
|
||||
{label: 'Email Book', value: 'permissionEmailBook', selected: false}
|
||||
];
|
||||
|
||||
internalAuthEnabled = true;
|
||||
autoUserProvisioningEnabled = false;
|
||||
selectedPermissions: string[] = [];
|
||||
oidcEnabled = false;
|
||||
allLibraries: Library[] = [];
|
||||
editingLibraryIds: number[] = [];
|
||||
|
||||
oidcProvider: OidcProviderDetails = {
|
||||
providerName: '',
|
||||
clientId: '',
|
||||
issuerUri: '',
|
||||
jwksUrl: '',
|
||||
claimMapping: {
|
||||
username: '',
|
||||
email: '',
|
||||
name: ''
|
||||
}
|
||||
};
|
||||
|
||||
private appSettingsService = inject(AppSettingsService);
|
||||
private messageService = inject(MessageService);
|
||||
private libraryService = inject(LibraryService);
|
||||
|
||||
appSettings$: Observable<AppSettings | null> = this.appSettingsService.appSettings$;
|
||||
|
||||
ngOnInit(): void {
|
||||
this.appSettings$.pipe(
|
||||
filter((settings): settings is AppSettings => settings != null),
|
||||
take(1)
|
||||
).subscribe(settings => this.loadSettings(settings));
|
||||
|
||||
this.libraryService.getAllLibrariesFromAPI().subscribe({
|
||||
next: (libraries) => {
|
||||
this.allLibraries = libraries;
|
||||
},
|
||||
error: () => {
|
||||
this.messageService.add({severity: 'error', summary: 'Error', detail: 'Failed to load libraries'});
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
loadSettings(settings: AppSettings): void {
|
||||
this.oidcEnabled = settings.oidcEnabled;
|
||||
|
||||
const details = settings.oidcAutoProvisionDetails;
|
||||
|
||||
this.autoUserProvisioningEnabled = details?.enableAutoProvisioning ?? false;
|
||||
this.selectedPermissions = details?.defaultPermissions ?? [];
|
||||
this.editingLibraryIds = details?.defaultLibraryIds ?? [];
|
||||
|
||||
const defaultClaimMapping = {
|
||||
username: 'preferred_username',
|
||||
email: 'email',
|
||||
name: 'given_name'
|
||||
};
|
||||
|
||||
this.oidcProvider = {
|
||||
providerName: settings.oidcProviderDetails?.providerName || '',
|
||||
clientId: settings.oidcProviderDetails?.clientId || '',
|
||||
issuerUri: settings.oidcProviderDetails?.issuerUri || '',
|
||||
jwksUrl: settings.oidcProviderDetails?.jwksUrl || '',
|
||||
claimMapping: settings.oidcProviderDetails?.claimMapping || defaultClaimMapping
|
||||
};
|
||||
|
||||
this.availablePermissions.forEach(perm => {
|
||||
perm.selected = this.selectedPermissions.includes(perm.value);
|
||||
});
|
||||
}
|
||||
|
||||
isOidcFormComplete(): boolean {
|
||||
const p = this.oidcProvider;
|
||||
return !!(p.providerName && p.clientId && p.issuerUri && p.claimMapping.name && p.claimMapping.email && p.claimMapping.username);
|
||||
}
|
||||
|
||||
saveAutoProvision(): void {
|
||||
const payload = [
|
||||
{key: 'auto_provision_oidc_users', newValue: this.autoUserProvisioningEnabled}
|
||||
];
|
||||
this.appSettingsService.saveSettings(payload).subscribe({
|
||||
next: () => this.messageService.add({
|
||||
severity: 'success',
|
||||
summary: 'Saved',
|
||||
detail: 'Auto-provision setting saved.'
|
||||
}),
|
||||
error: () => this.messageService.add({
|
||||
severity: 'error',
|
||||
summary: 'Error',
|
||||
detail: 'Failed to save auto-provision setting.'
|
||||
})
|
||||
});
|
||||
}
|
||||
|
||||
onPermissionToggle(): void {
|
||||
this.selectedPermissions = [
|
||||
'permissionRead',
|
||||
...this.availablePermissions.filter(p => p.selected).map(p => p.value)
|
||||
];
|
||||
|
||||
const payload = [
|
||||
{
|
||||
key: 'default_oidc_user_permissions',
|
||||
newValue: this.selectedPermissions
|
||||
}
|
||||
];
|
||||
|
||||
this.appSettingsService.saveSettings(payload).subscribe({
|
||||
next: () => this.messageService.add({
|
||||
severity: 'success',
|
||||
summary: 'Saved',
|
||||
detail: 'Default permissions updated.'
|
||||
}),
|
||||
error: () => this.messageService.add({
|
||||
severity: 'error',
|
||||
summary: 'Error',
|
||||
detail: 'Failed to update default permissions.'
|
||||
})
|
||||
});
|
||||
}
|
||||
|
||||
toggleOidcEnabled(): void {
|
||||
if (!this.isOidcFormComplete()) return;
|
||||
const payload = [
|
||||
{
|
||||
key: 'oidc_enabled',
|
||||
newValue: this.oidcEnabled
|
||||
}
|
||||
];
|
||||
this.appSettingsService.saveSettings(payload).subscribe({
|
||||
next: () => this.messageService.add({
|
||||
severity: 'success',
|
||||
summary: 'Saved',
|
||||
detail: 'OIDC setting updated.'
|
||||
}),
|
||||
error: () => this.messageService.add({
|
||||
severity: 'error',
|
||||
summary: 'Error',
|
||||
detail: 'Failed to update OIDC setting.'
|
||||
})
|
||||
});
|
||||
}
|
||||
|
||||
saveOidcProvider(): void {
|
||||
const payload = [
|
||||
{
|
||||
key: 'oidc_provider_details',
|
||||
newValue: this.oidcProvider
|
||||
}
|
||||
];
|
||||
this.appSettingsService.saveSettings(payload).subscribe({
|
||||
next: () => this.messageService.add({
|
||||
severity: 'success',
|
||||
summary: 'Saved',
|
||||
detail: 'OIDC provider settings saved.'
|
||||
}),
|
||||
error: () => this.messageService.add({
|
||||
severity: 'error',
|
||||
summary: 'Error',
|
||||
detail: 'Failed to save OIDC provider settings.'
|
||||
})
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
saveAutoProvisioningSettings(): void {
|
||||
const provisionDetails = {
|
||||
enableAutoProvisioning: this.autoUserProvisioningEnabled,
|
||||
defaultPermissions: [
|
||||
'permissionRead',
|
||||
...this.availablePermissions.filter(p => p.selected).map(p => p.value)
|
||||
],
|
||||
defaultLibraryIds: this.editingLibraryIds
|
||||
};
|
||||
|
||||
const payload = [
|
||||
{
|
||||
key: 'oidc_auto_provision_details',
|
||||
newValue: provisionDetails
|
||||
}
|
||||
];
|
||||
|
||||
this.appSettingsService.saveSettings(payload).subscribe({
|
||||
next: () => this.messageService.add({
|
||||
severity: 'success',
|
||||
summary: 'Saved',
|
||||
detail: 'OIDC auto-provisioning settings saved.'
|
||||
}),
|
||||
error: () => this.messageService.add({
|
||||
severity: 'error',
|
||||
summary: 'Error',
|
||||
detail: 'Failed to save OIDC auto-provisioning settings.'
|
||||
})
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
|
||||
@@ -0,0 +1,35 @@
|
||||
import {Component, inject, OnInit} from '@angular/core';
|
||||
import {Router} from '@angular/router';
|
||||
import {OAuthService} from 'angular-oauth2-oidc';
|
||||
import {AuthService} from '../core/service/auth.service';
|
||||
|
||||
@Component({
|
||||
selector: 'app-oidc-callback',
|
||||
templateUrl: './oidc-callback.component.html',
|
||||
styleUrls: ['./oidc-callback.component.scss']
|
||||
})
|
||||
export class OidcCallbackComponent implements OnInit {
|
||||
|
||||
private router = inject(Router);
|
||||
private oAuthService = inject(OAuthService);
|
||||
private authService = inject(AuthService);
|
||||
|
||||
ngOnInit(): void {
|
||||
this.oAuthService.loadDiscoveryDocumentAndTryLogin().then(() => {
|
||||
if (this.oAuthService.hasValidAccessToken()) {
|
||||
this.authService.saveOidcTokens(
|
||||
this.oAuthService.getAccessToken(),
|
||||
this.oAuthService.getRefreshToken()
|
||||
);
|
||||
this.authService.getRxStompService().activate();
|
||||
this.router.navigate(['/dashboard']);
|
||||
} else {
|
||||
console.error('Login failed or no valid tokens');
|
||||
this.router.navigate(['/login']);
|
||||
}
|
||||
}).catch(err => {
|
||||
console.error('OIDC error during login:', err);
|
||||
this.router.navigate(['/login']);
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -25,7 +25,7 @@
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<p class="text-lg py-1">Epub:</p>
|
||||
<p class="text-lg py-1">Epub:</p>
|
||||
<div class="flex gap-4 justify-start">
|
||||
<div *ngFor="let item of individualOrGlobal" class="flex items-center gap-2">
|
||||
<p-radiobutton
|
||||
@@ -120,9 +120,9 @@
|
||||
|
||||
<p class="text-lg py-1">Font Size:</p>
|
||||
<div class="flex gap-4 justify-start items-center">
|
||||
<p-button icon="pi pi-minus" rounded="true" (click)="decreaseFontSize()"></p-button>
|
||||
<p-button icon="pi pi-minus" rounded="true" size="small" (click)="decreaseFontSize()"></p-button>
|
||||
<p>{{ fontSize }}%</p>
|
||||
<p-button icon="pi pi-plus" rounded="true" (click)="increaseFontSize()"></p-button>
|
||||
<p-button icon="pi pi-plus" rounded="true" size="small" (click)="increaseFontSize()"></p-button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -2,11 +2,12 @@
|
||||
<div class="rounded-xl overflow-hidden">
|
||||
<p-tabs [(value)]="activeTab">
|
||||
<p-tablist>
|
||||
<p-tab [value]="SettingsTab.BookReader">Book Reader</p-tab>
|
||||
<p-tab [value]="SettingsTab.BookReader">Reader Settings</p-tab>
|
||||
<ng-container *ngIf="userData.permissions.admin">
|
||||
<p-tab [value]="SettingsTab.UserManagement">User Management</p-tab>
|
||||
<p-tab [value]="SettingsTab.Email">Email Setting</p-tab>
|
||||
<p-tab [value]="SettingsTab.GlobalSettings">Other Settings</p-tab>
|
||||
<p-tab [value]="SettingsTab.GlobalSettings">Admin Settings</p-tab>
|
||||
<p-tab [value]="SettingsTab.AuthenticationSettings">Authentication Settings</p-tab>
|
||||
</ng-container>
|
||||
</p-tablist>
|
||||
|
||||
@@ -24,6 +25,9 @@
|
||||
<p-tabpanel [value]="SettingsTab.GlobalSettings">
|
||||
<app-global-preferences></app-global-preferences>
|
||||
</p-tabpanel>
|
||||
<p-tabpanel [value]="SettingsTab.AuthenticationSettings">
|
||||
<app-authentication-settings></app-authentication-settings>
|
||||
</p-tabpanel>
|
||||
</ng-container>
|
||||
</p-tabpanels>
|
||||
</p-tabs>
|
||||
|
||||
@@ -8,12 +8,14 @@ import {GlobalPreferencesComponent} from './global-preferences/global-preference
|
||||
import {ActivatedRoute, Router} from '@angular/router';
|
||||
import {Subscription} from 'rxjs';
|
||||
import {UserManagementComponent} from './user-management/user-management.component';
|
||||
import {AuthenticationSettingsComponent} from '../oauth2-management/authentication-settings.component';
|
||||
|
||||
export enum SettingsTab {
|
||||
BookReader = 'book-reader',
|
||||
UserManagement = 'user-management',
|
||||
Email = 'email',
|
||||
GlobalSettings = 'global-settings'
|
||||
GlobalSettings = 'global-settings',
|
||||
AuthenticationSettings = 'auth-settings'
|
||||
}
|
||||
|
||||
@Component({
|
||||
@@ -29,7 +31,8 @@ export enum SettingsTab {
|
||||
AsyncPipe,
|
||||
EmailComponent,
|
||||
GlobalPreferencesComponent,
|
||||
UserManagementComponent
|
||||
UserManagementComponent,
|
||||
AuthenticationSettingsComponent
|
||||
],
|
||||
templateUrl: './settings.component.html',
|
||||
styleUrl: './settings.component.scss'
|
||||
|
||||
@@ -10,6 +10,7 @@
|
||||
<p-table [value]="users" class="mt-4">
|
||||
<ng-template pTemplate="header">
|
||||
<tr>
|
||||
<th>Provisioning</th>
|
||||
<th>Username</th>
|
||||
<th>Full Name</th>
|
||||
<th>Email</th>
|
||||
@@ -26,6 +27,9 @@
|
||||
|
||||
<ng-template pTemplate="body" let-user>
|
||||
<tr>
|
||||
<td>
|
||||
{{ (user.provisioningMethod || 'LOCAL') | lowercase | titlecase }}
|
||||
</td>
|
||||
<td>{{ user.username }}</td>
|
||||
<td>
|
||||
<input *ngIf="user.isEditing" type="text" [(ngModel)]="user.name" class="p-inputtext w-full"/>
|
||||
|
||||
@@ -4,7 +4,7 @@ import {Button} from 'primeng/button';
|
||||
import {DialogService, DynamicDialogRef} from 'primeng/dynamicdialog';
|
||||
import {CreateUserDialogComponent} from './create-user-dialog/create-user-dialog.component';
|
||||
import {TableModule} from 'primeng/table';
|
||||
import {NgIf, NgStyle} from '@angular/common';
|
||||
import {LowerCasePipe, NgIf, NgStyle, TitleCasePipe} from '@angular/common';
|
||||
import {User, UserService} from './user.service';
|
||||
import {MessageService} from 'primeng/api';
|
||||
import {Checkbox} from 'primeng/checkbox';
|
||||
@@ -25,7 +25,9 @@ import {Password} from 'primeng/password';
|
||||
NgStyle,
|
||||
MultiSelect,
|
||||
Dialog,
|
||||
Password
|
||||
Password,
|
||||
LowerCasePipe,
|
||||
TitleCasePipe
|
||||
],
|
||||
templateUrl: './user-management.component.html',
|
||||
styleUrls: ['./user-management.component.scss'],
|
||||
|
||||
@@ -21,6 +21,7 @@ export interface User {
|
||||
canManipulateLibrary: boolean;
|
||||
};
|
||||
bookPreferences: UserBookPreferences;
|
||||
provisioningMethod?: 'LOCAL' | 'OIDC' | 'REMOTE';
|
||||
}
|
||||
|
||||
export interface UserBookPreferences {
|
||||
|
||||
@@ -0,0 +1,30 @@
|
||||
import { inject, Injectable } from '@angular/core';
|
||||
import { CanActivate, Router } from '@angular/router';
|
||||
import { HttpClient } from '@angular/common/http';
|
||||
import { Observable, map, catchError, of } from 'rxjs';
|
||||
import { API_CONFIG } from '../config/api-config';
|
||||
|
||||
@Injectable({
|
||||
providedIn: 'root',
|
||||
})
|
||||
export class LoginGuard implements CanActivate {
|
||||
private readonly url = `${API_CONFIG.BASE_URL}/api/v1/setup`;
|
||||
private http = inject(HttpClient);
|
||||
private router = inject(Router);
|
||||
|
||||
canActivate(): Observable<boolean> {
|
||||
return this.http.get<{ data: boolean }>(`${this.url}/status`).pipe(
|
||||
map(res => {
|
||||
if (!res.data) {
|
||||
this.router.navigate(['/setup']);
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}),
|
||||
catchError(() => {
|
||||
this.router.navigate(['/setup']);
|
||||
return of(false);
|
||||
})
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
import {inject, Injectable} from '@angular/core';
|
||||
import { CanActivate, Router } from '@angular/router';
|
||||
import { HttpClient } from '@angular/common/http';
|
||||
import { Observable, map } from 'rxjs';
|
||||
import {API_CONFIG} from '../config/api-config';
|
||||
|
||||
@Injectable({
|
||||
providedIn: 'root',
|
||||
})
|
||||
export class SetupRedirectGuard implements CanActivate {
|
||||
private readonly url = `${API_CONFIG.BASE_URL}/api/v1/setup`;
|
||||
|
||||
private http = inject(HttpClient);
|
||||
private router = inject(Router);
|
||||
|
||||
canActivate(): Observable<boolean> {
|
||||
return this.http.get<{ data: boolean }>(`${this.url}/status`).pipe(
|
||||
map(res => {
|
||||
if (!res.data) {
|
||||
this.router.navigate(['/setup']);
|
||||
} else {
|
||||
this.router.navigate(['/dashboard']);
|
||||
}
|
||||
return false;
|
||||
})
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
<div class="setup-container">
|
||||
<div class="setup-wrapper">
|
||||
<h1 class="app-title">BookLore</h1>
|
||||
<p-card class="w-96">
|
||||
<ng-template pTemplate="title">
|
||||
<div class="text-center pb-2">Initial Admin Setup</div>
|
||||
</ng-template>
|
||||
<ng-template pTemplate="content">
|
||||
<form class="flex flex-col gap-4" [formGroup]="setupForm" (ngSubmit)="onSubmit()">
|
||||
|
||||
<div class="flex flex-col gap-2">
|
||||
<label for="name">Username</label>
|
||||
<input pInputText id="name" type="text" formControlName="username" required />
|
||||
<small class="text-red-500" *ngIf="setupForm.get('username')?.invalid && setupForm.get('username')?.touched">
|
||||
Username is required.
|
||||
</small>
|
||||
</div>
|
||||
|
||||
<div class="flex flex-col gap-2">
|
||||
<label for="name">Name</label>
|
||||
<input pInputText id="name" type="text" formControlName="name" required />
|
||||
<small class="text-red-500" *ngIf="setupForm.get('name')?.invalid && setupForm.get('name')?.touched">
|
||||
Name is required.
|
||||
</small>
|
||||
</div>
|
||||
|
||||
<div class="flex flex-col gap-2">
|
||||
<label for="email">Email</label>
|
||||
<input pInputText id="email" type="email" formControlName="email" required />
|
||||
<small class="text-red-500" *ngIf="setupForm.get('email')?.invalid && setupForm.get('email')?.touched">
|
||||
Valid email is required.
|
||||
</small>
|
||||
</div>
|
||||
|
||||
<div class="flex flex-col gap-2">
|
||||
<label for="password">Password</label>
|
||||
<p-password fluid id="password" formControlName="password" [feedback]="false" required></p-password>
|
||||
<small class="text-red-500" *ngIf="setupForm.get('password')?.invalid && setupForm.get('password')?.touched">
|
||||
Minimum 6 characters required.
|
||||
</small>
|
||||
</div>
|
||||
|
||||
<div class="flex flex-col gap-3 mt-4">
|
||||
<p-button fluid severity="success" type="submit"
|
||||
[label]="loading ? 'Creating…' : 'Create Admin Account'"
|
||||
[disabled]="loading || setupForm.invalid"
|
||||
icon="pi pi-user-plus">
|
||||
</p-button>
|
||||
<p-message *ngIf="error" severity="error" text="{{ error }}"></p-message>
|
||||
<p-message *ngIf="success" severity="success" text="Admin account created! Redirecting…"></p-message>
|
||||
</div>
|
||||
</form>
|
||||
</ng-template>
|
||||
</p-card>
|
||||
</div>
|
||||
</div>
|
||||
@@ -0,0 +1,12 @@
|
||||
.setup-container {
|
||||
@apply flex items-center justify-center min-h-screen bg-gradient-to-br from-blue-900 via-cyan-600 to-blue-400 relative;
|
||||
}
|
||||
|
||||
.setup-wrapper {
|
||||
@apply flex flex-col items-center gap-6 absolute top-1/4 transform -translate-y-1/4;
|
||||
}
|
||||
|
||||
.app-title {
|
||||
@apply text-5xl font-extrabold text-white drop-shadow-lg;
|
||||
text-shadow: 0px 4px 6px rgba(0, 0, 0, 0.3);
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
import { Component } from '@angular/core';
|
||||
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
|
||||
import { Router } from '@angular/router';
|
||||
import { SetupService } from './setup.service';
|
||||
import { NgIf } from '@angular/common';
|
||||
import { ReactiveFormsModule } from '@angular/forms';
|
||||
import { Card } from 'primeng/card';
|
||||
import { PrimeTemplate } from 'primeng/api';
|
||||
import { InputText } from 'primeng/inputtext';
|
||||
import { Password } from 'primeng/password';
|
||||
import { Button } from 'primeng/button';
|
||||
import { Message } from 'primeng/message';
|
||||
|
||||
@Component({
|
||||
selector: 'app-setup',
|
||||
templateUrl: './setup.component.html',
|
||||
styleUrls: ['./setup.component.scss'],
|
||||
standalone: true,
|
||||
imports: [
|
||||
ReactiveFormsModule,
|
||||
NgIf,
|
||||
Card,
|
||||
PrimeTemplate,
|
||||
InputText,
|
||||
Password,
|
||||
Button,
|
||||
Message
|
||||
]
|
||||
})
|
||||
export class SetupComponent {
|
||||
setupForm: FormGroup;
|
||||
loading = false;
|
||||
error: string | null = null;
|
||||
success = false;
|
||||
|
||||
constructor(
|
||||
private fb: FormBuilder,
|
||||
private setupService: SetupService,
|
||||
private router: Router
|
||||
) {
|
||||
this.setupForm = this.fb.group({
|
||||
name: ['', [Validators.required]],
|
||||
username: ['', [Validators.required]],
|
||||
email: ['', [Validators.required, Validators.email]],
|
||||
password: ['', [Validators.required, Validators.minLength(6)]],
|
||||
});
|
||||
}
|
||||
|
||||
onSubmit(): void {
|
||||
if (this.setupForm.invalid) return;
|
||||
|
||||
this.loading = true;
|
||||
this.error = null;
|
||||
|
||||
this.setupService.createAdmin(this.setupForm.value).subscribe({
|
||||
next: () => {
|
||||
this.success = true;
|
||||
setTimeout(() => this.router.navigate(['/login']), 1500);
|
||||
},
|
||||
error: (err) => {
|
||||
this.loading = false;
|
||||
this.error =
|
||||
err?.error?.message || 'Failed to create admin user. Try again.';
|
||||
},
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
import {inject, Injectable} from '@angular/core';
|
||||
import {
|
||||
CanActivate,
|
||||
Router,
|
||||
UrlTree
|
||||
} from '@angular/router';
|
||||
import {Observable} from 'rxjs';
|
||||
import {map} from 'rxjs/operators';
|
||||
import {HttpClient} from '@angular/common/http';
|
||||
import {API_CONFIG} from '../config/api-config';
|
||||
|
||||
@Injectable({
|
||||
providedIn: 'root'
|
||||
})
|
||||
export class SetupGuard implements CanActivate {
|
||||
|
||||
private readonly url = `${API_CONFIG.BASE_URL}/api/v1/setup`;
|
||||
|
||||
private http = inject(HttpClient);
|
||||
private router = inject(Router);
|
||||
|
||||
canActivate(): Observable<boolean | UrlTree> {
|
||||
return this.http.get<any>(`${this.url}/status`).pipe(
|
||||
map(response => {
|
||||
if (response?.data === true) {
|
||||
return this.router.createUrlTree(['/login']);
|
||||
}
|
||||
return true;
|
||||
})
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
import {inject, Injectable} from '@angular/core';
|
||||
import {HttpClient} from '@angular/common/http';
|
||||
import {Observable} from 'rxjs';
|
||||
import {API_CONFIG} from '../config/api-config';
|
||||
|
||||
export interface SetupPayload {
|
||||
email: string;
|
||||
password: string;
|
||||
}
|
||||
|
||||
@Injectable({providedIn: 'root'})
|
||||
export class SetupService {
|
||||
|
||||
private readonly url = `${API_CONFIG.BASE_URL}/api/v1/setup`;
|
||||
|
||||
private http = inject(HttpClient);
|
||||
|
||||
createAdmin(payload: SetupPayload): Observable<void> {
|
||||
return this.http.post<void>(this.url, payload);
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
import {RxStompConfig} from '@stomp/rx-stomp';
|
||||
import {API_CONFIG} from '../../config/api-config';
|
||||
import {AuthService} from '../../core/service/auth.service';
|
||||
import {API_CONFIG} from '../../config/api-config';
|
||||
|
||||
export function createRxStompConfig(authService: AuthService): RxStompConfig {
|
||||
return {
|
||||
@@ -9,10 +9,17 @@ export function createRxStompConfig(authService: AuthService): RxStompConfig {
|
||||
heartbeatOutgoing: 20000,
|
||||
reconnectDelay: 200,
|
||||
beforeConnect: (stomp) => {
|
||||
stomp.stompClient.connectHeaders = {'Authorization': `Bearer ${authService.getToken()}`};
|
||||
const oidcToken = authService.getOidcAccessToken();
|
||||
const internalToken = authService.getInternalAccessToken();
|
||||
const token = oidcToken || internalToken;
|
||||
if (token) {
|
||||
stomp.stompClient.connectHeaders = {
|
||||
'Authorization': `Bearer ${token}`,
|
||||
};
|
||||
}
|
||||
},
|
||||
debug: (msg: string): void => {
|
||||
//console.log(new Date(), msg);
|
||||
// console.log(new Date(), msg);
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { Injectable } from '@angular/core';
|
||||
import { RxStomp } from '@stomp/rx-stomp';
|
||||
import {RxStomp, RxStompConfig} from '@stomp/rx-stomp';
|
||||
import { AuthService } from '../../core/service/auth.service';
|
||||
import { createRxStompConfig } from './rx-stomp.config';
|
||||
|
||||
@@ -7,9 +7,14 @@ import { createRxStompConfig } from './rx-stomp.config';
|
||||
providedIn: 'root',
|
||||
})
|
||||
export class RxStompService extends RxStomp {
|
||||
|
||||
constructor(private authService: AuthService) {
|
||||
super();
|
||||
const stompConfig = createRxStompConfig(this.authService);
|
||||
this.configure(stompConfig);
|
||||
}
|
||||
|
||||
public updateConfig(config: RxStompConfig) {
|
||||
this.configure(config);
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user