diff --git a/web/angular/src/app/app.component.html b/web/angular/src/app/app.component.html index 2e2c5df..fefc544 100644 --- a/web/angular/src/app/app.component.html +++ b/web/angular/src/app/app.component.html @@ -1,6 +1,6 @@

{{title}}

- + diff --git a/web/angular/src/app/app.module.ts b/web/angular/src/app/app.module.ts index 9364eed..75c4404 100644 --- a/web/angular/src/app/app.module.ts +++ b/web/angular/src/app/app.module.ts @@ -1,31 +1,48 @@ +// browser stuff and polyfills import { BrowserModule } from '@angular/platform-browser'; -import { NgModule } from '@angular/core'; -import { InjectionToken } from '@angular/core'; -import {NgbModule} from '@ng-bootstrap/ng-bootstrap'; - -import { HttpClientModule } from '@angular/common/http'; +// core module and dependency injection +import { NgModule, InjectionToken } from '@angular/core'; +// forms (ngModel) and two way data binding with templates +import { FormsModule } from '@angular/forms'; +// bootstrap 4 for angular +import { NgbModule } from '@ng-bootstrap/ng-bootstrap'; +// http client and http client interceptors +import { HttpClientModule, HTTP_INTERCEPTORS } from '@angular/common/http'; +// application code import { ApiClientService } from '../api/index' import { AppComponent } from './app.component'; import { ConsoleComponent } from './console/console.component'; import { ConsoleService } from './console.service'; import { NoticesComponent } from './notices/notices.component'; -import { HTTP_INTERCEPTORS } from '@angular/common/http'; -import { DelayRequestInterceptor } from './app.interceptors'; +import { DelayInterceptor } from './delay.interceptor'; +import { LoginComponent } from './login/login.component'; +import { AuthService } from './auth.service'; +import { AuthInterceptor } from './auth.interceptor'; @NgModule({ declarations: [ AppComponent, ConsoleComponent, - NoticesComponent + NoticesComponent, + LoginComponent, ], imports: [ NgbModule.forRoot(), BrowserModule, + FormsModule, HttpClientModule ], - // define the domain in ApiClientService see https://angular.io/guide/dependency-injection - providers: [{provide: "domain", useValue: "/api"}, {provide: HTTP_INTERCEPTORS, useClass: DelayRequestInterceptor, multi: true}, ApiClientService, ConsoleService], + + providers: [ + // define the domain in ApiClientService see https://angular.io/guide/dependency-injection + {provide: "domain", useValue: "/api"}, + // add two global interceptors (one two slow down the server and one for authentication) + {provide: HTTP_INTERCEPTORS, useClass: DelayInterceptor, multi: true}, + {provide: HTTP_INTERCEPTORS, useClass: AuthInterceptor, multi: true}, + // add our application services (api access, logging, authentication) + ApiClientService, ConsoleService, AuthService + ], bootstrap: [AppComponent] }) export class AppModule { } diff --git a/web/angular/src/app/auth.interceptor.ts b/web/angular/src/app/auth.interceptor.ts new file mode 100644 index 0000000..cf4cc91 --- /dev/null +++ b/web/angular/src/app/auth.interceptor.ts @@ -0,0 +1,58 @@ +import {Injectable, Optional, Inject} from '@angular/core'; +import {HttpEvent, HttpInterceptor, HttpHandler, HttpRequest} from '@angular/common/http'; +import { Observable } from 'rxjs/Observable'; +import { HttpResponse } from '@angular/common/http'; +import { Subject } from 'rxjs/Subject'; +import { ConsoleService } from './console.service'; +import { AuthService } from './auth.service'; +import { Injector } from '@angular/core'; + +/** + * This interceptor intercepts http requests and attaches a + * basic auth header to them as long as the auth service is + * issuing them. + */ +@Injectable() +export class AuthInterceptor implements HttpInterceptor { + + /** + * The authentication service to get tokens. + */ + private authService: AuthService; + + /** + * Creates a new interceptor with the injected console service + * and auth service. + * + * @param consoleService The console service for logging. + * @param authService The auth service to generate auth headers. + */ + constructor(private consoleService: ConsoleService, private injector: Injector) { } + + /** + * Intercepts the requests and possibly attaches an auth header. + * + * @param req The request that is intercepted. + * @param next The handler to continue the request. + */ + intercept(req: HttpRequest, next: HttpHandler): Observable> { + if (this.authService == null) { + // this is dumb, but by using http service in the + // auth service (indirectly through ApiClientService) + // there will be a cyclic dependency between: + // ApiClientService -> HttpClient -> AuthInterceptor -> AuthSerivce -> ApiClientService + // but it can be resolved at runtime (see https://github.com/angular/angular/issues/18224) + this.authService = this.injector.get(AuthService); + } + let authHeader = this.authService.getHeader(); + let clone = req; + if (authHeader != null) { + this.consoleService.log("Attaching Authorization header."); + clone = req.clone({ headers: req.headers.set("Authorization", authHeader)}); + } else { + this.consoleService.log("Skipping Authorization header."); + } + return next.handle(clone); + } + +} \ No newline at end of file diff --git a/web/angular/src/app/auth.service.spec.ts b/web/angular/src/app/auth.service.spec.ts new file mode 100644 index 0000000..bd98634 --- /dev/null +++ b/web/angular/src/app/auth.service.spec.ts @@ -0,0 +1,15 @@ +import { TestBed, inject } from '@angular/core/testing'; + +import { AuthService } from './auth.service'; + +describe('AuthService', () => { + beforeEach(() => { + TestBed.configureTestingModule({ + providers: [AuthService] + }); + }); + + it('should be created', inject([AuthService], (service: AuthService) => { + expect(service).toBeTruthy(); + })); +}); diff --git a/web/angular/src/app/auth.service.ts b/web/angular/src/app/auth.service.ts new file mode 100644 index 0000000..6d42ab7 --- /dev/null +++ b/web/angular/src/app/auth.service.ts @@ -0,0 +1,188 @@ +import { Injectable } from '@angular/core'; +import { ConsoleService } from './console.service'; +import { ApiClientService } from '../api/index'; +import { OnInit } from '@angular/core/src/metadata/lifecycle_hooks'; +import { User } from '../api/models/user.model'; +import { BehaviorSubject } from 'rxjs/BehaviorSubject'; +import { HttpErrorResponse } from '@angular/common/http'; + +/** + * The possible states of the auth service. + */ +export enum AuthState { + /** + * The user has not tried to login. + */ + Unauthorized, + /** + * The user is currently logging in. + */ + Authorizing, + /** + * The user has logged in. + */ + Authorized +} + +/** + * A service to manage the user's credentials and login state. The + * service can be in one of the AuthStates. While the user is + * Authorized, the service will maintain a reference to the + * user object from the server. In addition, when the service is + * in the AutState.Authorizing or AuthState.Authorized, a request + * interceptor will use the service getAuthHeader() method to + * compute a basic auth header that is transmitted with each request. + * + * To let the user's login state survive a page reload (without + * actually having a session on the server), the credentials are + * stored in the browser's session storage (if available). According + * to the docs, the session storage is "secure" enough to do this. + * However, since Safari does not support session storage in the + * private browsing mode, we also store the credentials in memory. + */ +@Injectable() +export class AuthService { + + private static KEY_LOGIN = "login"; + private static KEY_PASSWORD = "password"; + + private login: string; + private password: string; + + user: BehaviorSubject = new BehaviorSubject(null); + state: BehaviorSubject = new BehaviorSubject(AuthState.Unauthorized); + error: BehaviorSubject = new BehaviorSubject(null); + + constructor(private consoleService: ConsoleService, private apiClientService: ApiClientService) { + // get the username from the session storage, if it is there + if (window.sessionStorage) { + this.login = window.sessionStorage.getItem(AuthService.KEY_LOGIN); + this.password = window.sessionStorage.getItem(AuthService.KEY_PASSWORD); + } + // immediately login, if we have credentials + if (this.isSet(this.login) && this.isSet(this.password)) { + // but return the service first, otherwise + // angular will go through an infinite service + // creation loop since the constructor did not + // return yet + setTimeout(() => { + this.requestLogin(); + }, 100); + } + } + + /** + * Returns the login name, if set. + * + * @returns The login name. + */ + getLogin(): string { + return this.login; + } + + /** + * Asks the service to perform a login. If there is no + * on-going server interacton, the service will try to + * retrieve the current user's account which validates + * the credential as a side-effect. If there is an + * ongoing interaction, the call to this method will + * be ignored. + */ + requestLogin(): void { + if (this.state.getValue() != AuthState.Authorizing) { + this.consoleService.log("Issuing login request."); + this.state.next(AuthState.Authorizing); + this.user.next(null); + this.error.next(null); + this.apiClientService.getCurrentUser().subscribe(result => { + this.user.next(result.body); + this.state.next(AuthState.Authorized); + // store the username into the session storage to + // make it survive a browser reload + if (window.sessionStorage) { + this.consoleService.log("Storing login."); + window.sessionStorage.setItem(AuthService.KEY_LOGIN, this.login); + window.sessionStorage.setItem(AuthService.KEY_PASSWORD, this.password); + } + }, error => { + this.consoleService.log("Error during login."); + if (error instanceof HttpErrorResponse) { + var message = error.status + ": " + error.statusText; + this.consoleService.log("HttpError: " + message); + this.error.next(message); + } else { + this.consoleService.log("Unknown login error " + error); + } + this.state.next(AuthState.Unauthorized); + }); + } else { + this.consoleService.log("Ignoring login request during login."); + } + } + + /** + * Asks the service to update the credentials. Similar to + * request login and request logout, this method will only + * do something while there is no ongoing service interaction. + * + * @param login The login name. + * @param password The password. + */ + setCredential(login: string, password: string): void { + if (this.state.getValue() != AuthState.Authorizing) { + this.login = login; + this.password = password; + this.state.next(AuthState.Unauthorized); + this.error.next(null); + this.user.next(null); + } + } + + /** + * Returns the auth header for the current username and password + * or null, if none are set or the service is not authorizing or + * authorized. + * + * @returns A basic auth header or null. + */ + getHeader(): string { + if (this.state.getValue() != AuthState.Unauthorized && this.isSet(this.login) && this.isSet(this.password)) { + return "Basic " + btoa(this.login + ":" + this.password); + } else { + return null; + } + } + + /** + * Requests a logout, that will be executed unless the + * service is currently interacting with the server. + */ + requestLogout(): void { + if (this.state.getValue() != AuthState.Authorizing) { + // forget the credentials in memory + this.login = null; + this.password = null; + // also wipe the session storage + if (window.sessionStorage) { + window.sessionStorage.removeItem(AuthService.KEY_LOGIN); + window.sessionStorage.removeItem(AuthService.KEY_PASSWORD); + } + // reset the service's state + this.state.next(AuthState.Unauthorized); + this.error.next(null); + this.user.next(null); + } + } + + /** + * Determines whether the value is set by + * checking that it is not null and has a + * length > 0. + * + * @param value The value. + */ + private isSet(value: string) { + return value != null && value.length > 0; + } + +} diff --git a/web/angular/src/app/console/console.component.html b/web/angular/src/app/console/console.component.html index 0d65ff1..e05e67a 100644 --- a/web/angular/src/app/console/console.component.html +++ b/web/angular/src/app/console/console.component.html @@ -1,8 +1,8 @@
-
+
-

Console

+
Console
@@ -24,7 +24,7 @@
    -
  • {{message}}
  • +
  • {{message}}
diff --git a/web/angular/src/app/app.interceptors.ts b/web/angular/src/app/delay.interceptor.ts similarity index 83% rename from web/angular/src/app/app.interceptors.ts rename to web/angular/src/app/delay.interceptor.ts index 1d96020..020a76c 100644 --- a/web/angular/src/app/app.interceptors.ts +++ b/web/angular/src/app/delay.interceptor.ts @@ -2,7 +2,6 @@ import {Injectable, Optional, Inject} from '@angular/core'; import {HttpEvent, HttpInterceptor, HttpHandler, HttpRequest} from '@angular/common/http'; import { Observable } from 'rxjs/Observable'; import { HttpResponse } from '@angular/common/http'; -import { timeout, delay } from 'q'; import { Subject } from 'rxjs/Subject'; import { ConsoleService } from './console.service'; @@ -12,7 +11,7 @@ import { ConsoleService } from './console.service'; * not be delivered before the configured delay. */ @Injectable() -export class DelayRequestInterceptor implements HttpInterceptor { +export class DelayInterceptor implements HttpInterceptor { /** * The delay to slow down requests. @@ -38,6 +37,12 @@ export class DelayRequestInterceptor implements HttpInterceptor { * @param next The handler to continue the request. */ intercept(req: HttpRequest, next: HttpHandler): Observable> { + // if we only want to delay the values, we could use this construct + // + // import { delay } from 'rxjs/operators'; + // return next.handle(req).pipe(delay(10000)); + // + // but we also want to delay errors, so we need to fully specify it const started = Date.now(); var delayedRequest: Subject> = new Subject>(); next.handle(req).subscribe(event => { @@ -45,10 +50,12 @@ export class DelayRequestInterceptor implements HttpInterceptor { this.schedule(started, ()=> delayedRequest.next(event) ); }, error => { this.consoleService.log("Scheduling error for " + req.urlWithParams); - this.schedule(started, ()=> delayedRequest.error(error) ); + // hacky: +1 to ensure that error is sent after result + this.schedule(started + 1, ()=> delayedRequest.error(error) ); }, () => { this.consoleService.log("Scheduling completion for " + req.urlWithParams); - this.schedule(started, ()=> delayedRequest.complete() ); + // hacky: +2 to ensure that completion is sent last + this.schedule(started + 2, ()=> delayedRequest.complete() ); }); return delayedRequest; } diff --git a/web/angular/src/app/login/login.component.css b/web/angular/src/app/login/login.component.css new file mode 100644 index 0000000..e69de29 diff --git a/web/angular/src/app/login/login.component.html b/web/angular/src/app/login/login.component.html new file mode 100644 index 0000000..ccee111 --- /dev/null +++ b/web/angular/src/app/login/login.component.html @@ -0,0 +1,45 @@ +
+ +
+ +
+ +
+
+ Please specify your login. +
+
+ Minimum 5, maximu 32 characters (only letters and numbers). +
+
+
+ +
+ +
+
+ Please provide your password. +
+
+
+ +
+ +
+ +
+
+
+
+ +
Loading
+
+
+
+ + + +
+ +
+
\ No newline at end of file diff --git a/web/angular/src/app/login/login.component.spec.ts b/web/angular/src/app/login/login.component.spec.ts new file mode 100644 index 0000000..d6d85a8 --- /dev/null +++ b/web/angular/src/app/login/login.component.spec.ts @@ -0,0 +1,25 @@ +import { async, ComponentFixture, TestBed } from '@angular/core/testing'; + +import { LoginComponent } from './login.component'; + +describe('LoginComponent', () => { + let component: LoginComponent; + let fixture: ComponentFixture; + + beforeEach(async(() => { + TestBed.configureTestingModule({ + declarations: [ LoginComponent ] + }) + .compileComponents(); + })); + + beforeEach(() => { + fixture = TestBed.createComponent(LoginComponent); + component = fixture.componentInstance; + fixture.detectChanges(); + }); + + it('should create', () => { + expect(component).toBeTruthy(); + }); +}); diff --git a/web/angular/src/app/login/login.component.ts b/web/angular/src/app/login/login.component.ts new file mode 100644 index 0000000..eb72378 --- /dev/null +++ b/web/angular/src/app/login/login.component.ts @@ -0,0 +1,57 @@ +import { Component, OnInit, ViewEncapsulation } from '@angular/core'; +import { ConsoleService } from '../console.service'; +import { AuthService, AuthState } from '../auth.service'; +import { BehaviorSubject } from 'rxjs/BehaviorSubject'; +import { User } from '../../api/models/user.model'; + +@Component({ + selector: 'app-login', + templateUrl: './login.component.html', + styleUrls: ['./login.component.css'], + encapsulation: ViewEncapsulation.None +}) +export class LoginComponent implements OnInit { + + /** + * This is dumb but since the template does not know AuthState, we cannot use it in html, + * e.g. to select upon the enum's value in an ngSwitch directive. As a workaround, we can + * define a field pointing to the enum. Thus, we can reference the enum through the field. + * If we use the same name, it looks even somewhat ok in html. + * + * See https://www.gurustop.net/blog/2016/05/24/how-to-use-typescript-enum-with-angular2/ + */ + AuthState = AuthState; + + login: string; + password: string; + + constructor(private consoleService: ConsoleService, private authService: AuthService) { } + + ngOnInit() { + this.login = this.authService.getLogin(); + } + + getUser(): BehaviorSubject { + return this.authService.user; + } + + getAuthState(): BehaviorSubject { + return this.authService.state; + } + + getError(): BehaviorSubject { + return this.authService.error; + } + + requestLogin(): void { + this.authService.setCredential(this.login, this.password); + this.authService.requestLogin(); + } + + requestLogout(): void { + this.authService.requestLogout(); + this.login = null; + this.password = null; + } + +} diff --git a/web/angular/src/app/notices/notices.component.ts b/web/angular/src/app/notices/notices.component.ts index 48e3d41..388406a 100644 --- a/web/angular/src/app/notices/notices.component.ts +++ b/web/angular/src/app/notices/notices.component.ts @@ -48,7 +48,7 @@ export class NoticesComponent implements OnInit { hasReload(): boolean { - return (this.page == null && !this.loading); + return (!this.loading); } hasNext(): boolean {