Merge branch 'bvander/auth-flow' into 'master'

auth flow fixes

See merge request grassrootseconomics/cic-staff-client!27
This commit is contained in:
Blair Vanderlugt 2021-06-10 14:18:53 +00:00
commit 060c47f840
2 changed files with 69 additions and 97 deletions

View File

@ -14,7 +14,6 @@ import { BehaviorSubject, Observable } from 'rxjs';
providedIn: 'root', providedIn: 'root',
}) })
export class AuthService { export class AuthService {
sessionToken: any;
mutableKeyStore: MutableKeyStore; mutableKeyStore: MutableKeyStore;
trustedUsers: Array<Staff> = []; trustedUsers: Array<Staff> = [];
private trustedUsersList: BehaviorSubject<Array<Staff>> = new BehaviorSubject<Array<Staff>>( private trustedUsersList: BehaviorSubject<Array<Staff>> = new BehaviorSubject<Array<Staff>>(
@ -32,41 +31,46 @@ export class AuthService {
async init(): Promise<void> { async init(): Promise<void> {
await this.mutableKeyStore.loadKeyring(); await this.mutableKeyStore.loadKeyring();
// TODO setting these together should be atomic
if (sessionStorage.getItem(btoa('CICADA_SESSION_TOKEN'))) {
this.sessionToken = sessionStorage.getItem(btoa('CICADA_SESSION_TOKEN'));
}
if (localStorage.getItem(btoa('CICADA_PRIVATE_KEY'))) { if (localStorage.getItem(btoa('CICADA_PRIVATE_KEY'))) {
await this.mutableKeyStore.importPrivateKey(localStorage.getItem(btoa('CICADA_PRIVATE_KEY'))); await this.mutableKeyStore.importPrivateKey(localStorage.getItem(btoa('CICADA_PRIVATE_KEY')));
} }
} }
getSessionToken(): string {
return sessionStorage.getItem(btoa('CICADA_SESSION_TOKEN'));
}
setSessionToken(token): void {
sessionStorage.setItem(btoa('CICADA_SESSION_TOKEN'), token);
}
setState(s): void { setState(s): void {
document.getElementById('state').innerHTML = s; document.getElementById('state').innerHTML = s;
} }
getWithToken(): Promise<boolean> { getWithToken(): Promise<boolean> {
return new Promise((resolve, reject) => {
const headers = { const headers = {
Authorization: 'Bearer ' + this.sessionToken, Authorization: 'Bearer ' + this.getSessionToken,
'Content-Type': 'application/json;charset=utf-8', 'Content-Type': 'application/json;charset=utf-8',
'x-cic-automerge': 'none', 'x-cic-automerge': 'none',
}; };
const options = { const options = {
headers, headers,
}; };
fetch(environment.cicMetaUrl, options).then((response) => { return fetch(environment.cicMetaUrl, options).then((response) => {
if (response.status === 401) { if (!response.ok) {
return reject(rejectBody(response)); this.loggingService.sendErrorLevelMessage('failed to get with auth token.',
this,
{ error: "" });
return false;
} }
return resolve(true); return true;
});
}); });
} }
// TODO rename to send signed challenge and set session. Also separate these responsibilities // TODO rename to send signed challenge and set session. Also separate these responsibilities
sendResponse(hobaResponseEncoded: any): Promise<boolean> { sendSignedChallenge(hobaResponseEncoded: any): Promise<any> {
return new Promise((resolve, reject) => {
const headers = { const headers = {
Authorization: 'HOBA ' + hobaResponseEncoded, Authorization: 'HOBA ' + hobaResponseEncoded,
'Content-Type': 'application/json;charset=utf-8', 'Content-Type': 'application/json;charset=utf-8',
@ -75,85 +79,55 @@ export class AuthService {
const options = { const options = {
headers, headers,
}; };
fetch(environment.cicMetaUrl, options).then((response) => { return fetch(environment.cicMetaUrl, options)
if (response.status === 401) {
return reject(rejectBody(response));
}
this.sessionToken = response.headers.get('Token');
sessionStorage.setItem(btoa('CICADA_SESSION_TOKEN'), this.sessionToken);
this.setState('Click button to log in');
return resolve(true);
});
});
} }
getChallenge(): Promise<any> { getChallenge(): Promise<any> {
return new Promise((resolve, reject) => { return fetch(environment.cicMetaUrl)
fetch(environment.cicMetaUrl).then(async (response) => { .then(response => {
if (response.status === 401) { if (response.status === 401) {
const authHeader: string = response.headers.get('WWW-Authenticate'); const authHeader: string = response.headers.get('WWW-Authenticate');
return resolve(hobaParseChallengeHeader(authHeader)); return hobaParseChallengeHeader(authHeader);
} }
if (!response.ok) {
return reject(rejectBody(response));
}
});
}); });
} }
async login(): Promise<boolean> { async login(): Promise<boolean> {
if (this.sessionToken !== undefined) { if (this.getSessionToken()) {
try { sessionStorage.removeItem(btoa('CICADA_SESSION_TOKEN'));
const response: boolean = await this.getWithToken();
return response === true;
} catch (e) {
this.loggingService.sendErrorLevelMessage('Login token failed', this, { error: e });
}
} else { } else {
try {
const o = await this.getChallenge(); const o = await this.getChallenge();
const response: boolean = await this.loginResponse(o);
return response === true;
} catch (e) {
this.loggingService.sendErrorLevelMessage('Login challenge failed', this, { error: e });
}
}
return false;
}
async loginResponse(o: { challenge: string; realm: any }): Promise<any> {
return new Promise(async (resolve, reject) => {
try {
const r = await signChallenge( const r = await signChallenge(
o.challenge, o.challenge,
o.realm, o.realm,
environment.cicMetaUrl, environment.cicMetaUrl,
this.mutableKeyStore this.mutableKeyStore
); );
const response: boolean = await this.sendResponse(r);
resolve(response); const tokenResponse = await this.sendSignedChallenge(r)
} catch (error) { .then(response => {
if (error instanceof HttpError) { const token = response.headers.get('Token')
if (error.status === 403) { if (token) {
this.errorDialogService.openDialog({ return token
message: 'You are not authorized to use this system',
});
} else if (error.status === 401) {
this.errorDialogService.openDialog({
message:
'Unable to authenticate with the service. ' +
'Please speak with the staff at Grassroots ' +
'Economics for requesting access ' +
'staff@grassrootseconomics.net.',
});
} }
} else { if (response.status === 401) {
// TODO define this error let e = new HttpError("You are not authorized to use this system", response.status)
this.errorDialogService.openDialog({ message: 'Incorrect key passphrase.' }); throw e
} }
resolve(false); if (!response.ok) {
let e = new HttpError("Unknown error from authentication server", response.status)
throw e
}
})
if (tokenResponse) {
this.setSessionToken(tokenResponse);
this.setState('Click button to log in');
return true
}
return false
} }
});
} }
loginView(): void { loginView(): void {
@ -193,7 +167,6 @@ export class AuthService {
logout(): void { logout(): void {
sessionStorage.removeItem(btoa('CICADA_SESSION_TOKEN')); sessionStorage.removeItem(btoa('CICADA_SESSION_TOKEN'));
localStorage.removeItem(btoa('CICADA_PRIVATE_KEY')); localStorage.removeItem(btoa('CICADA_PRIVATE_KEY'));
this.sessionToken = undefined;
window.location.reload(); window.location.reload();
} }

View File

@ -2,6 +2,8 @@ import { ChangeDetectionStrategy, Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms'; import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { CustomErrorStateMatcher } from '@app/_helpers'; import { CustomErrorStateMatcher } from '@app/_helpers';
import { AuthService } from '@app/_services'; import { AuthService } from '@app/_services';
import { ErrorDialogService } from '@app/_services/error-dialog.service';
import { LoggingService } from '@app/_services/logging.service';
import { Router } from '@angular/router'; import { Router } from '@angular/router';
@Component({ @Component({
@ -19,18 +21,14 @@ export class AuthComponent implements OnInit {
constructor( constructor(
private authService: AuthService, private authService: AuthService,
private formBuilder: FormBuilder, private formBuilder: FormBuilder,
private router: Router private router: Router,
private errorDialogService: ErrorDialogService,
) {} ) {}
async ngOnInit(): Promise<void> { async ngOnInit(): Promise<void> {
this.keyForm = this.formBuilder.group({ this.keyForm = this.formBuilder.group({
key: ['', Validators.required], key: ['', Validators.required],
}); });
await this.authService.init();
// if (this.authService.privateKey !== undefined) {
// const setKey = await this.authService.setKey(this.authService.privateKey);
// }
// }
} }
get keyFormStub(): any { get keyFormStub(): any {
@ -49,19 +47,20 @@ export class AuthComponent implements OnInit {
this.loading = false; this.loading = false;
} }
login(): void { async login(): Promise<void> {
// TODO check if we have privatekey try {
// Send us to home if we have a private key const loginResult = await this.authService.login()
// talk to meta somehow if (loginResult) {
// in the error interceptor if 401/403 handle it
// if 200 go /home
if (this.authService.getPrivateKey()) {
this.router.navigate(['/home']); this.router.navigate(['/home']);
} }
} catch (HttpError) {
this.errorDialogService.openDialog({
message: HttpError.message,
});
}
} }
switchWindows(): void { switchWindows(): void {
this.authService.sessionToken = undefined;
const divOne: HTMLElement = document.getElementById('one'); const divOne: HTMLElement = document.getElementById('one');
const divTwo: HTMLElement = document.getElementById('two'); const divTwo: HTMLElement = document.getElementById('two');
this.toggleDisplay(divOne); this.toggleDisplay(divOne);