BAEL-7380 : ul (CONFIGURATION)

OAuth2 BFF with spring-addons
This commit is contained in:
ch4mpy
2024-02-10 03:21:58 -10:00
parent 6ada5de93e
commit db46099bce
96 changed files with 25925 additions and 0 deletions
@@ -0,0 +1,16 @@
# Editor configuration, see https://editorconfig.org
root = true
[*]
charset = utf-8
indent_style = space
indent_size = 2
insert_final_newline = true
trim_trailing_whitespace = true
[*.ts]
quote_type = single
[*.md]
max_line_length = off
trim_trailing_whitespace = false
@@ -0,0 +1,42 @@
# See http://help.github.com/ignore-files/ for more about ignoring files.
# Compiled output
/dist
/tmp
/out-tsc
/bazel-out
# Node
/node_modules
npm-debug.log
yarn-error.log
# IDEs and editors
.idea/
.project
.classpath
.c9/
*.launch
.settings/
*.sublime-workspace
# Visual Studio Code
.vscode/*
!.vscode/settings.json
!.vscode/tasks.json
!.vscode/launch.json
!.vscode/extensions.json
.history/*
# Miscellaneous
/.angular/cache
.sass-cache/
/connect.lock
/coverage
/libpeerconnection.log
testem.log
/typings
# System files
.DS_Store
Thumbs.db
@@ -0,0 +1,110 @@
{
"$schema": "./node_modules/@angular/cli/lib/config/schema.json",
"version": 1,
"newProjectRoot": "projects",
"projects": {
"angular-ui": {
"projectType": "application",
"schematics": {
"@schematics/angular:component": {
"style": "scss"
}
},
"root": "",
"sourceRoot": "src",
"prefix": "app",
"architect": {
"build": {
"builder": "@angular-devkit/build-angular:application",
"options": {
"baseHref": "/angular-ui/",
"outputPath": "dist/angular-ui",
"index": "src/index.html",
"browser": "src/main.ts",
"polyfills": [
"zone.js"
],
"tsConfig": "tsconfig.app.json",
"inlineStyleLanguage": "scss",
"assets": [
"src/favicon.ico",
"src/assets"
],
"styles": [
"src/styles.scss"
],
"scripts": []
},
"configurations": {
"production": {
"budgets": [
{
"type": "initial",
"maximumWarning": "500kb",
"maximumError": "1mb"
},
{
"type": "anyComponentStyle",
"maximumWarning": "2kb",
"maximumError": "4kb"
}
],
"outputHashing": "all"
},
"development": {
"optimization": false,
"extractLicenses": false,
"sourceMap": true
}
},
"defaultConfiguration": "production"
},
"serve": {
"builder": "@angular-devkit/build-angular:dev-server",
"configurations": {
"production": {
"buildTarget": "angular-ui:build:production"
},
"development": {
"buildTarget": "angular-ui:build:development"
},
"local": {
"buildTarget": "angular-ui:build:development",
"host": "0.0.0.0",
"port": 4201
}
},
"defaultConfiguration": "development"
},
"extract-i18n": {
"builder": "@angular-devkit/build-angular:extract-i18n",
"options": {
"buildTarget": "angular-ui:build"
}
},
"test": {
"builder": "@angular-devkit/build-angular:karma",
"options": {
"polyfills": [
"zone.js",
"zone.js/testing"
],
"tsConfig": "tsconfig.spec.json",
"inlineStyleLanguage": "scss",
"assets": [
"src/favicon.ico",
"src/assets"
],
"styles": [
"src/styles.scss"
],
"scripts": []
}
}
}
}
},
"cli": {
"analytics": "23e97199-7e93-4604-8730-91fe13971aa4"
}
}
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,38 @@
{
"name": "angular-ui",
"version": "0.0.0",
"scripts": {
"ng": "ng",
"start": "ng serve -c local",
"build": "ng build",
"watch": "ng build --watch --configuration development",
"test": "ng test"
},
"private": true,
"dependencies": {
"@angular/animations": "^17.0.0",
"@angular/common": "^17.0.0",
"@angular/compiler": "^17.0.0",
"@angular/core": "^17.0.0",
"@angular/forms": "^17.0.0",
"@angular/platform-browser": "^17.0.0",
"@angular/platform-browser-dynamic": "^17.0.0",
"@angular/router": "^17.0.0",
"rxjs": "~7.8.0",
"tslib": "^2.3.0",
"zone.js": "~0.14.2"
},
"devDependencies": {
"@angular-devkit/build-angular": "^17.0.10",
"@angular/cli": "^17.0.10",
"@angular/compiler-cli": "^17.0.0",
"@types/jasmine": "~5.1.0",
"jasmine-core": "~5.1.0",
"karma": "~6.4.0",
"karma-chrome-launcher": "~3.2.0",
"karma-coverage": "~2.2.0",
"karma-jasmine": "~5.1.0",
"karma-jasmine-html-reporter": "~2.1.0",
"typescript": "~5.2.2"
}
}
@@ -0,0 +1,18 @@
import { Component } from '@angular/core';
import { NavigationComponent } from './navigation.component';
@Component({
selector: 'app-about',
standalone: true,
imports: [NavigationComponent],
template: `<app-navigation
[destination]="['']"
label="HOME"
></app-navigation>
<p>
This application is a show-case for an Angular app consuming a REST API
through an OAuth2 BFF.
</p>`,
styles: ``,
})
export class AboutView {}
@@ -0,0 +1,27 @@
import { CommonModule } from '@angular/common';
import { HttpClientModule } from '@angular/common/http';
import { Component } from '@angular/core';
import { RouterOutlet } from '@angular/router';
import { AuthenticationComponent } from './auth/authentication.component';
@Component({
selector: 'app-root',
standalone: true,
imports: [
CommonModule,
RouterOutlet,
HttpClientModule,
AuthenticationComponent,
],
template: `<div style="display: flex;">
<div style="margin: auto;"></div>
<h1>Angular UI</h1>
<div style="margin: auto;"></div>
<app-authentication style="margin: auto 1em;"></app-authentication>
</div>
<div>
<router-outlet></router-outlet>
</div>`,
styles: [],
})
export class AppComponent {}
@@ -0,0 +1,12 @@
import { ApplicationConfig } from '@angular/core';
import { provideRouter } from '@angular/router';
import { provideHttpClient } from '@angular/common/http';
import { routes } from './app.routes';
export const appConfig: ApplicationConfig = {
providers: [provideRouter(routes), provideHttpClient()],
};
export const reverseProxyUri = 'http://localhost:7080';
export const baseUri = `${reverseProxyUri}/angular-ui/`;
@@ -0,0 +1,9 @@
import { Routes } from '@angular/router';
import { AboutView } from './about.view';
import { HomeView } from './home.view';
export const routes: Routes = [
{ path: '', component: HomeView },
{ path: 'about', component: AboutView },
{ path: '**', redirectTo: '/' },
];
@@ -0,0 +1,27 @@
import { CommonModule } from '@angular/common';
import { Component } from '@angular/core';
import { FormControl, ReactiveFormsModule, Validators } from '@angular/forms';
import { DomSanitizer, SafeUrl } from '@angular/platform-browser';
import { Router } from '@angular/router';
import { baseUri, reverseProxyUri } from '../app.config';
import { UserService } from './user.service';
import { LoginComponent } from './login.component';
import { LogoutComponent } from './logout.component';
@Component({
selector: 'app-authentication',
standalone: true,
imports: [CommonModule, ReactiveFormsModule, LoginComponent, LogoutComponent],
template: `<span>
<app-login *ngIf="!isAuthenticated"></app-login>
<app-logout *ngIf="isAuthenticated"></app-logout>
</span>`,
styles: ``,
})
export class AuthenticationComponent {
constructor(private user: UserService) {}
get isAuthenticated(): boolean {
return this.user.current.isAuthenticated;
}
}
@@ -0,0 +1,152 @@
import { HttpClient } from '@angular/common/http';
import { Component } from '@angular/core';
import { FormControl, ReactiveFormsModule, Validators } from '@angular/forms';
import { DomSanitizer, SafeUrl } from '@angular/platform-browser';
import { Observable, map } from 'rxjs';
import { UserService } from './user.service';
import { baseUri } from '../app.config';
import { Router } from '@angular/router';
import { CommonModule } from '@angular/common';
enum LoginExperience {
IFRAME,
DEFAULT,
}
interface LoginOptionDto {
label: string;
loginUri: string;
isSameAuthority: boolean;
}
function loginOptions(http: HttpClient): Observable<Array<LoginOptionDto>> {
return http
.get('/bff/login-options')
.pipe(map((dto: any) => dto as LoginOptionDto[]));
}
@Component({
selector: 'app-login',
standalone: true,
imports: [CommonModule, ReactiveFormsModule],
template: `<span>
<select *ngIf="loginExperiences.length > 1" [formControl]="selectedLoginExperience">
<option *ngFor="let le of loginExperiences">
{{ loginExperienceLabel(le) }}
</option>
</select>
<button (click)="login()" [disabled]="!isLoginEnabled">Login</button>
</span>
<div
class="modal-overlay"
*ngIf="isLoginModalDisplayed && !isAuthenticated"
(click)="isLoginModalDisplayed = false"
>
<div class="modal">
<iframe
[src]="iframeSrc"
frameborder="0"
(load)="onIframeLoad($event)"
></iframe>
<button class="close-button" (click)="isLoginModalDisplayed = false">
Discard
</button>
</div>
</div>`,
styles: `.modal-overlay {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
background-color: rgba(0, 0, 0, 0.5);
display: flex;
justify-content: center;
align-items: center;
z-index: 9999;
}
.modal {
background-color: #fff;
padding: 20px;
border-radius: 5px;
position: relative;
width: 100%;
max-width: 800px;
}
.modal iframe {
width: 100%;
height: 600px;
border: none;
}`,
})
export class LoginComponent {
isLoginModalDisplayed = false;
iframeSrc?: SafeUrl;
loginExperiences: LoginExperience[] = [];
selectedLoginExperience = new FormControl<LoginExperience | null>(null, [
Validators.required,
]);
private loginUri?: string;
constructor(
http: HttpClient,
private user: UserService,
private router: Router,
private sanitizer: DomSanitizer
) {
loginOptions(http).subscribe((opts) => {
if (opts.length) {
this.loginUri = opts[0].loginUri;
if (opts[0].isSameAuthority) {
this.loginExperiences.push(LoginExperience.IFRAME);
}
this.loginExperiences.push(LoginExperience.DEFAULT);
this.selectedLoginExperience.patchValue(this.loginExperiences[0]);
}
});
}
get isLoginEnabled(): boolean {
return (
this.selectedLoginExperience.valid && !this.user.current.isAuthenticated
);
}
get isAuthenticated(): boolean {
return this.user.current.isAuthenticated;
}
login() {
if (!this.loginUri) {
return;
}
const url = new URL(this.loginUri);
url.searchParams.append(
'post_login_success_uri',
`${baseUri}${this.router.url}`
);
const loginUrl = url.toString();
if (this.selectedLoginExperience.value === LoginExperience.IFRAME) {
this.iframeSrc = this.sanitizer.bypassSecurityTrustResourceUrl(loginUrl);
this.isLoginModalDisplayed = true;
} else {
window.location.href = loginUrl;
}
}
onIframeLoad(event: any) {
if (!!event.currentTarget.src) {
this.user.refresh();
this.isLoginModalDisplayed = !this.user.current.isAuthenticated;
}
}
loginExperienceLabel(le: LoginExperience) {
return LoginExperience[le].toLowerCase()
}
}
@@ -0,0 +1,39 @@
import { Component } from '@angular/core';
import { UserService } from './user.service';
import { lastValueFrom } from 'rxjs';
import { HttpClient } from '@angular/common/http';
import { baseUri } from '../app.config';
@Component({
selector: 'app-logout',
standalone: true,
imports: [],
template: `
<button (click)="logout()">Logout</button>
`,
styles: ``
})
export class LogoutComponent {
constructor(private http: HttpClient, private user: UserService) {}
logout() {
lastValueFrom(
this.http.post('/bff/logout', null, {
headers: {
'X-POST-LOGOUT-SUCCESS-URI': baseUri,
},
observe: 'response',
})
)
.then((resp) => {
const logoutUri = resp.headers.get('Location');
if (!!logoutUri) {
window.location.href = logoutUri;
}
})
.finally(() => {
this.user.refresh();
});
}
}
@@ -0,0 +1,88 @@
import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { BehaviorSubject, Observable, Subscription, interval } from 'rxjs';
interface UserinfoDto {
username: string;
email: string;
roles: string[];
exp: number;
}
export class User {
static readonly ANONYMOUS = new User('', '', []);
constructor(
readonly name: string,
readonly email: string,
readonly roles: string[]
) {}
get isAuthenticated(): boolean {
return !!this.name;
}
hasAnyRole(...roles: string[]): boolean {
for (const r of roles) {
if (this.roles.includes(r)) {
return true;
}
}
return false;
}
}
@Injectable({
providedIn: 'root',
})
export class UserService {
private user$ = new BehaviorSubject<User>(User.ANONYMOUS);
private refreshSub?: Subscription;
constructor(private http: HttpClient) {
this.refresh();
}
refresh(): void {
this.refreshSub?.unsubscribe();
this.http.get('/bff/api/me').subscribe({
next: (dto: any) => {
const user = dto as UserinfoDto;
if (
user.username !== this.user$.value.name ||
user.email !== this.user$.value.email ||
(user.roles || []).toString() !== this.user$.value.roles.toString()
) {
this.user$.next(
user.username
? new User(
user.username || '',
user.email || '',
user.roles || []
)
: User.ANONYMOUS
);
}
if (!!user.exp) {
const now = Date.now();
const delay = (1000 * user.exp - now) * 0.8;
if (delay > 2000) {
this.refreshSub = interval(delay).subscribe(() => this.refresh());
}
}
},
error: (error) => {
console.warn(error);
this.user$.next(User.ANONYMOUS);
},
});
}
get valueChanges(): Observable<User> {
return this.user$;
}
get current(): User {
return this.user$.value;
}
}
@@ -0,0 +1,40 @@
import { Component } from '@angular/core';
import { Subscription } from 'rxjs';
import { NavigationComponent } from './navigation.component';
import { User, UserService } from './auth/user.service';
@Component({
selector: 'app-home',
standalone: true,
imports: [NavigationComponent],
template: `<app-navigation
[destination]="['about']"
label="About"
></app-navigation>
<p>{{ message }}</p>`,
styles: [],
})
export class HomeView {
message = '';
private userSubscription?: Subscription;
constructor(user: UserService) {
this.userSubscription = user.valueChanges.subscribe((u) => {
this.message = u.isAuthenticated
? `Hi ${u.name}, you are granted with ${HomeView.rolesStr(u)}.`
: 'You are not authenticated.';
});
}
static rolesStr(user: User) {
if(!user?.roles?.length) {
return '[]'
}
return `["${user.roles.join('", "')}"]`
}
ngOnDestroy() {
this.userSubscription?.unsubscribe();
}
}
@@ -0,0 +1,30 @@
import { Component, Input } from '@angular/core';
import { Router } from '@angular/router';
import { Subscription } from 'rxjs';
@Component({
selector: 'app-navigation',
standalone: true,
imports: [],
template: `<button (click)="navigate()">{{ label }}</button>`,
styles: ``,
})
export class NavigationComponent {
@Input()
label!: string;
@Input()
destination!: string[];
private userSubscription?: Subscription;
constructor(private router: Router) {}
ngOnDestroy() {
this.userSubscription?.unsubscribe();
}
navigate() {
this.router.navigate(this.destination);
}
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 15 KiB

@@ -0,0 +1,13 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>AngularUi</title>
<base href="/">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="icon" type="image/x-icon" href="/favicon.ico">
</head>
<body>
<app-root></app-root>
</body>
</html>
@@ -0,0 +1,6 @@
import { bootstrapApplication } from '@angular/platform-browser';
import { appConfig } from './app/app.config';
import { AppComponent } from './app/app.component';
bootstrapApplication(AppComponent, appConfig)
.catch((err) => console.error(err));
@@ -0,0 +1 @@
/* You can add global styles to this file, and also import other style files */
@@ -0,0 +1,14 @@
/* To learn more about this file see: https://angular.io/config/tsconfig. */
{
"extends": "./tsconfig.json",
"compilerOptions": {
"outDir": "./out-tsc/app",
"types": []
},
"files": [
"src/main.ts"
],
"include": [
"src/**/*.d.ts"
]
}
@@ -0,0 +1,33 @@
/* To learn more about this file see: https://angular.io/config/tsconfig. */
{
"compileOnSave": false,
"compilerOptions": {
"outDir": "./dist/out-tsc",
"forceConsistentCasingInFileNames": true,
"strict": true,
"noImplicitOverride": true,
"noPropertyAccessFromIndexSignature": true,
"noImplicitReturns": true,
"noFallthroughCasesInSwitch": true,
"skipLibCheck": true,
"esModuleInterop": true,
"sourceMap": true,
"declaration": false,
"experimentalDecorators": true,
"moduleResolution": "node",
"importHelpers": true,
"target": "ES2022",
"module": "ES2022",
"useDefineForClassFields": false,
"lib": [
"ES2022",
"dom"
]
},
"angularCompilerOptions": {
"enableI18nLegacyMessageIdFormat": false,
"strictInjectionParameters": true,
"strictInputAccessModifiers": true,
"strictTemplates": true
}
}
@@ -0,0 +1,14 @@
/* To learn more about this file see: https://angular.io/config/tsconfig. */
{
"extends": "./tsconfig.json",
"compilerOptions": {
"outDir": "./out-tsc/spec",
"types": [
"jasmine"
]
},
"include": [
"src/**/*.spec.ts",
"src/**/*.d.ts"
]
}