import { Injectable } from '@angular/core'; import { hobaParseChallengeHeader } from '@src/assets/js/hoba.js'; import { signChallenge } from '@src/assets/js/hoba-pgp.js'; import {environment} from '@src/environments/environment'; import {LoggingService} from '@app/_services/logging.service'; import {MutableKeyStore, MutablePgpKeyStore} from '@app/_pgp'; import {ErrorDialogService} from '@app/_services/error-dialog.service'; import {tap} from 'rxjs/operators'; import { HttpClient } from '@angular/common/http'; import {Observable } from 'rxjs'; @Injectable({ providedIn: 'root' }) export class AuthService { sessionToken: any; sessionLoginCount = 0; privateKey: any; mutableKeyStore: MutableKeyStore = new MutablePgpKeyStore(); constructor( private httpClient: HttpClient, private loggingService: LoggingService, private errorDialogService: ErrorDialogService ) { // TODO setting these together shoulds be atomic if (sessionStorage.getItem(btoa('CICADA_SESSION_TOKEN'))) { this.sessionToken = sessionStorage.getItem(btoa('CICADA_SESSION_TOKEN')); } if (localStorage.getItem(btoa('CICADA_PRIVATE_KEY'))) { this.privateKey = localStorage.getItem(btoa('CICADA_PRIVATE_KEY')); } } setState(s): void { document.getElementById('state').innerHTML = s; } getWithToken(): void { const xhr = new XMLHttpRequest(); xhr.responseType = 'text'; xhr.open('GET', environment.cicMetaUrl + window.location.search.substring(1)); xhr.setRequestHeader('Authorization', 'Bearer ' + this.sessionToken); xhr.setRequestHeader('Content-Type', 'application/json'); xhr.setRequestHeader('x-cic-automerge', 'none'); xhr.addEventListener('load', (e) => { if (xhr.status === 401) { throw new Error('login rejected'); } this.sessionLoginCount++; this.setState('Click button to perform login ' + this.sessionLoginCount + ' with token ' + this.sessionToken); return; }); xhr.send(); } sendResponse(hobaResponseEncoded): void { const xhr = new XMLHttpRequest(); xhr.responseType = 'text'; xhr.open('GET', environment.cicMetaUrl + window.location.search.substring(1)); xhr.setRequestHeader('Authorization', 'HOBA ' + hobaResponseEncoded); xhr.setRequestHeader('Content-Type', 'application/json'); xhr.setRequestHeader('x-cic-automerge', 'none'); xhr.addEventListener('load', (e) => { if (xhr.status === 401) { throw new Error('login rejected'); } this.sessionToken = xhr.getResponseHeader('Token'); sessionStorage.setItem(btoa('CICADA_SESSION_TOKEN'), this.sessionToken); this.sessionLoginCount++; this.setState('Click button to perform login ' + this.sessionLoginCount + ' with token ' + this.sessionToken); return; }); xhr.send(); } getChallenge(): void { const xhr = new XMLHttpRequest(); xhr.responseType = 'arraybuffer'; xhr.open('GET', environment.cicMetaUrl + window.location.search.substring(1)); xhr.onload = async (e) => { if (xhr.status === 401) { const authHeader = xhr.getResponseHeader('WWW-Authenticate'); const o = hobaParseChallengeHeader(authHeader); await this.loginResponse(o); } }; xhr.send(); } login(): boolean { if (this.sessionToken !== undefined) { try { this.getWithToken(); return true; } catch (e) { this.loggingService.sendErrorLevelMessage('Login token failed', this, {error: e}); } } else { try { this.getChallenge(); } catch (e) { this.loggingService.sendErrorLevelMessage('Login challenge failed', this, {error: e}); } } return false; } async loginResponse(o): Promise { const r = await signChallenge(o.challenge, o.realm, environment.cicMetaUrl, this.mutableKeyStore); this.sendResponse(r); } loginView(): void { document.getElementById('one').style.display = 'none'; document.getElementById('two').style.display = 'block'; this.setState('Click button to log in with PGP key ' + this.mutableKeyStore.getPrivateKeyId()); } async setKey(privateKeyArmored): Promise { try { const isValidKeyCheck = await this.mutableKeyStore.isValidKey(privateKeyArmored) if (!isValidKeyCheck) { throw Error('The private key is invalid'); } const key = await this.mutableKeyStore.importPrivateKey(privateKeyArmored); localStorage.setItem(btoa('CICADA_PRIVATE_KEY'), privateKeyArmored); } catch (err) { this.loggingService.sendErrorLevelMessage('Failed setting key', this, {error: err}); // TODO use a global error handler here this.errorDialogService.openDialog({ message: `Failed to set key: ${err.message || err.statusText}`, }); return false; } this.loginView(); return true; } logout(): void { sessionStorage.removeItem(btoa('CICADA_SESSION_TOKEN')); window.location.reload(true); } getTrustedUsers(): any { let trustedUsers = []; this.mutableKeyStore.getPublicKeys().forEach(key => trustedUsers.push(key.users[0].userId)); return trustedUsers; } getPublicKeys(): Observable { return this.httpClient.get(`${environment.publicKeysUrl}`, {responseType: 'text'}) .pipe(tap( data => { }, error => { this.loggingService.sendErrorLevelMessage('Unable to load trusted public keys.', this, {error}); } )); } async getPrivateKeys(): Promise { if (this.privateKey !== undefined) { await this.mutableKeyStore.importPrivateKey(this.privateKey); } } }