auth flow fixes

This commit is contained in:
Blair Vanderlugt 2021-06-08 17:59:01 -07:00
parent 78c4bd5de8
commit a9763f9109
4 changed files with 117 additions and 94 deletions

View File

@ -12,7 +12,7 @@ import { HttpError, rejectBody } from '@app/_helpers/global-error-handler';
providedIn: 'root', providedIn: 'root',
}) })
export class AuthService { export class AuthService {
sessionToken: any; //sessionToken: any;
mutableKeyStore: MutableKeyStore; mutableKeyStore: MutableKeyStore;
constructor( constructor(
@ -26,40 +26,47 @@ 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 // TODO setting these together should be atomic
if (sessionStorage.getItem(btoa('CICADA_SESSION_TOKEN'))) { //if (sessionStorage.getItem(btoa('CICADA_SESSION_TOKEN'))) {
this.sessionToken = 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 {
console.log('Setting sessiong token! ', token)
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)); console.log("failed to getWithToken...maybe try clearing the token and try again?")
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',
@ -68,85 +75,105 @@ 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(); //try {
return response === true; // // TODO do we need to do this? is it just a test of the token?
} catch (e) { // const response: boolean = await this.getWithToken();
this.loggingService.sendErrorLevelMessage('Login token failed', this, { error: e }); // return response
} //} catch (e) {
// this.loggingService.sendErrorLevelMessage('Login token failed', this, { error: e });
//}
} else { } else {
try { 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) {
return token
}
if (response.status === 401) {
this.errorDialogService.openDialog({ this.errorDialogService.openDialog({
message: 'You are not authorized to use this system', message: 'You are not authorized to use this system',
}); });
} else if (error.status === 401) { return
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 === 403) {
// TODO define this error console.log('Getting back a 403 but I think the server should send 200')
this.errorDialogService.openDialog({ message: 'Incorrect key passphrase.' }); //this.errorDialogService.openDialog({
// message: 'You are not authorized to use this system',
//});
// return
} }
resolve(false); if (!response.ok) {
console.log("Failed to get a login token with signed challenge 😭", response.statusText)
return
} }
}); })
if (tokenResponse) {
this.setSessionToken(tokenResponse);
this.setState('Click button to log in');
return true
}
return false
} catch (e) {
this.loggingService.sendErrorLevelMessage('Login challenge failed', this, { error: e });
}
}
}
async loginResponse(o: { challenge: string; realm: any }): Promise<any> {
const r = await signChallenge(
o.challenge,
o.realm,
environment.cicMetaUrl,
this.mutableKeyStore
);
return this.sendSignedChallenge(r);
// if (error instanceof HttpError) {
// if (error.status === 403) {
// this.errorDialogService.openDialog({
// 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 {
// // TODO define this error
// this.errorDialogService.openDialog({ message: 'Incorrect key passphrase.' });
// }
// resolve(false);
} }
loginView(): void { loginView(): void {
@ -186,7 +213,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

@ -42,10 +42,10 @@ export class UserService {
private registryService: RegistryService, private registryService: RegistryService,
private authService: AuthService private authService: AuthService
) { ) {
this.authService.init().then(() => { //this.authService.init().then(() => {
this.keystore = authService.mutableKeyStore; // this.keystore = authService.mutableKeyStore;
this.signer = new PGPSigner(this.keystore); // this.signer = new PGPSigner(this.keystore);
}); //});
this.registry = registryService.getRegistry(); this.registry = registryService.getRegistry();
this.registry.load(); this.registry.load();
} }

View File

@ -26,7 +26,7 @@ export class AuthComponent implements OnInit {
this.keyForm = this.formBuilder.group({ this.keyForm = this.formBuilder.group({
key: ['', Validators.required], key: ['', Validators.required],
}); });
await this.authService.init(); //await this.authService.init();
// if (this.authService.privateKey !== undefined) { // if (this.authService.privateKey !== undefined) {
// const setKey = await this.authService.setKey(this.authService.privateKey); // const setKey = await this.authService.setKey(this.authService.privateKey);
// } // }
@ -49,19 +49,19 @@ export class AuthComponent implements OnInit {
this.loading = false; this.loading = false;
} }
login(): void { async login(): Promise<void> {
// TODO check if we have privatekey // TODO check if we have privatekey
// Send us to home if we have a private key // Send us to home if we have a private key
// talk to meta somehow // talk to meta somehow
// in the error interceptor if 401/403 handle it // in the error interceptor if 401/403 handle it
// if 200 go /home // if 200 go /home
if (this.authService.getPrivateKey()) { const loginResult = await this.authService.login()
if (loginResult) {
this.router.navigate(['/home']); this.router.navigate(['/home']);
} }
} }
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);

View File

@ -33,21 +33,18 @@ export class AccountsComponent implements OnInit {
private loggingService: LoggingService, private loggingService: LoggingService,
private router: Router private router: Router
) { ) {
(async () => { }
try {
// TODO it feels like this should be in the onInit handler async ngOnInit(): Promise<void> {
try { // TODO it feels like this should be in the onInit handler
await this.userService.loadAccounts(100); await this.userService.loadAccounts(100);
} catch (error) { } catch (error) {
this.loggingService.sendErrorLevelMessage('Failed to load accounts', this, { error }); this.loggingService.sendErrorLevelMessage('Failed to load accounts', this, { error });
} }
})();
this.userService this.userService
.getAccountTypes() .getAccountTypes()
.pipe(first()) .pipe(first())
.subscribe((res) => (this.accountTypes = res)); .subscribe((res) => (this.accountTypes = res));
}
ngOnInit(): void {
this.userService.accountsSubject.subscribe((accounts) => { this.userService.accountsSubject.subscribe((accounts) => {
this.dataSource = new MatTableDataSource<any>(accounts); this.dataSource = new MatTableDataSource<any>(accounts);
this.dataSource.paginator = this.paginator; this.dataSource.paginator = this.paginator;