Fun with services, interceptors, di and forms.
lbs-gitea/maptology/master This commit looks good

This commit is contained in:
2017-11-21 18:22:26 +01:00
parent c46824cd72
commit 852fb2ffd0
12 changed files with 431 additions and 19 deletions
+1 -1
View File
@@ -1,6 +1,6 @@
<div class="container">
<h1>{{title}}</h1>
<app-login></app-login>
<app-notices></app-notices>
<app-console></app-console>
+27 -10
View File
@@ -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 { }
+58
View File
@@ -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<any>, next: HttpHandler): Observable<HttpEvent<any>> {
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);
}
}
+15
View File
@@ -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();
}));
});
+188
View File
@@ -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<User> = new BehaviorSubject<User>(null);
state: BehaviorSubject<AuthState> = new BehaviorSubject<AuthState>(AuthState.Unauthorized);
error: BehaviorSubject<string> = new BehaviorSubject<string>(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;
}
}
@@ -1,8 +1,8 @@
<div class="card fixed-bottom">
<div class="card-header">
<div class="card-header p-2 m-0">
<div class="row no-gutters">
<div class="col">
<h4><i class="fa fa-bug" aria-hidden="true"></i> Console</h4>
<h5><i class="fa fa-bug" aria-hidden="true"></i> Console</h5>
</div>
<div class="pull-xs-right">
<div *ngIf="hasMessages()">
@@ -24,7 +24,7 @@
<div class="collapse" id="messages" [ngbCollapse]="isCollapsed">
<div class="pre-scrollable">
<ul class="list-group list-group-flush">
<li class="list-group-item" *ngFor='let message of getMessages() | async'> {{message}} </li>
<li class="list-group-item m-0 p-1" *ngFor='let message of getMessages() | async'> {{message}} </li>
</ul>
</div>
</div>
@@ -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<any>, next: HttpHandler): Observable<HttpEvent<any>> {
// 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<HttpEvent<any>> = new Subject<HttpEvent<any>>();
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;
}
@@ -0,0 +1,45 @@
<form #loginForm="ngForm">
<ng-container *ngIf="((getAuthState() | async) != AuthState.Authorized); else authorized">
<div class="form-group row">
<label for="login" class="col-sm-2 col-form-label">Login</label>
<div class="col-sm-4">
<input type="text" class="form-control" id="login" placeholder="Login&hellip;" pattern="([a-zA-Z0-9]){5,32}" required [(ngModel)]="login" name="login" #loginModel="ngModel" [disabled]="((getAuthState() | async) != AuthState.Unauthorized)">
</div>
<div class="col-sm-5 alert alert-warning p-1 m-0" *ngIf="loginForm.dirty && loginModel.errors?.required">
Please specify your login.
</div>
<div class="col-sm-5 alert alert-warning p-1 m-0" *ngIf="loginForm.dirty && loginModel.errors?.pattern">
Minimum 5, maximu 32 characters (only letters and numbers).
</div>
</div>
<div class="form-group row">
<label for="password" class="col-sm-2 col-form-label">Password</label>
<div class="col-sm-4">
<input type="password" class="form-control" placeholder="Password&hellip;" id="password" required [(ngModel)]="password" name="password" #passwordModel="ngModel" [disabled]="((getAuthState() | async) != AuthState.Unauthorized)">
</div>
<div class="col-sm-5 alert alert-warning p-1 m-0" *ngIf="loginForm.dirty && passwordModel.errors?.required">
Please provide your password.
</div>
</div>
</ng-container>
<ng-template #authorized>
<div class="form-group row">
<label for="name" class="col-sm-2 col-form-label">Name</label>
<div class="col-sm-4">
<input type="text" class="form-control" disabled [value]="(getUser() | async)?.name">
</div>
</div>
</ng-template>
<div class="form-group row">
<ng-container [ngSwitch]="getAuthState() | async">
<div *ngSwitchCase="AuthState.Authorizing" class="col-sm-2 text-center mt-2"><i class="fa fa-spinner fa-pulse fa-fw" aria-hidden="true"></i><span class="sr-only">Loading</span></div>
<div *ngSwitchDefault class="col-sm-2 text-center mt-2"></div>
</ng-container>
<div class="col-sm-4" [ngSwitch]="getAuthState() | async">
<button *ngSwitchCase="AuthState.Unauthorized" type="button" class="btn btn-primary" (click)="requestLogin()" [disabled]="!loginForm.valid">Login</button>
<button *ngSwitchCase="AuthState.Authorized" type="button" class="btn btn-primary" (click)="requestLogout()">Logout</button>
<button *ngSwitchDefault type="button" class="btn btn-primary disabled">Login</button>
</div>
<div class="col-sm-5 alert alert-danger p-1 mb-0" *ngIf="getError() | async; let e; " role="alert"> {{ e }} </div>
</div>
</form>
@@ -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<LoginComponent>;
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [ LoginComponent ]
})
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(LoginComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});
@@ -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<User> {
return this.authService.user;
}
getAuthState(): BehaviorSubject<AuthState> {
return this.authService.state;
}
getError(): BehaviorSubject<string> {
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;
}
}
@@ -48,7 +48,7 @@ export class NoticesComponent implements OnInit {
hasReload(): boolean {
return (this.page == null && !this.loading);
return (!this.loading);
}
hasNext(): boolean {