Files
maptology/web/angular/src/app/auth.service.ts
T
2017-12-10 03:35:09 +01:00

221 lines
7.5 KiB
TypeScript

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';
import {UserRegistration} from "../api/models/userregistration.model";
/**
* 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;
}
/**
* 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.
*/
registerUser(user: UserRegistration): void {
this.consoleService.log("User registration with name" + user.name + " requested.");
this.error.next(null);
this.user.next(null);
this.apiClientService.registerUser(user).subscribe(result => {
this.consoleService.log("User registration received.");
// this.user.next(result.body);
}, error => {
if (error.status == 400) {
let message = error.status + ": " + error.statusText;
this.consoleService.log("Invalid user registration.");
this.error.next(message);
} else if (error.status == 409) {
let message = error.status + ": " + error.statusText;
this.consoleService.log("User login already registered.");
this.error.next(message);
} else {
this.consoleService.log("Unknown error.");
console.dir(error); // print it to the console
}
});
}
}