Merge branch 'bvander/loading-registries' into 'master'

refactor token service to use the token registry

See merge request grassrootseconomics/cic-staff-client!29
This commit is contained in:
Blair Vanderlugt 2021-06-12 15:08:10 +00:00
commit a93be027c6
12 changed files with 903 additions and 838 deletions

1469
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@ -33,10 +33,10 @@
"@angular/platform-browser-dynamic": "~10.2.0", "@angular/platform-browser-dynamic": "~10.2.0",
"@angular/router": "~10.2.0", "@angular/router": "~10.2.0",
"@angular/service-worker": "~10.2.0", "@angular/service-worker": "~10.2.0",
"@cicnet/cic-client": "^0.1.6",
"@cicnet/schemas-data-validator": "*", "@cicnet/schemas-data-validator": "*",
"@popperjs/core": "^2.5.4", "@popperjs/core": "^2.5.4",
"bootstrap": "^4.5.3", "bootstrap": "^4.5.3",
"cic-client": "0.1.4",
"cic-client-meta": "0.0.7-alpha.6", "cic-client-meta": "0.0.7-alpha.6",
"ethers": "^5.0.31", "ethers": "^5.0.31",
"http-server": "^0.12.3", "http-server": "^0.12.3",

View File

@ -1,3 +1,4 @@
import { AuthService } from '@app/_services';
import { Injectable } from '@angular/core'; import { Injectable } from '@angular/core';
import { HttpRequest, HttpHandler, HttpEvent, HttpInterceptor } from '@angular/common/http'; import { HttpRequest, HttpHandler, HttpEvent, HttpInterceptor } from '@angular/common/http';
import { Observable } from 'rxjs'; import { Observable } from 'rxjs';
@ -8,10 +9,11 @@ export class HttpConfigInterceptor implements HttpInterceptor {
intercept(request: HttpRequest<unknown>, next: HttpHandler): Observable<HttpEvent<unknown>> { intercept(request: HttpRequest<unknown>, next: HttpHandler): Observable<HttpEvent<unknown>> {
// const token: string = sessionStorage.getItem(btoa('CICADA_SESSION_TOKEN')); // const token: string = sessionStorage.getItem(btoa('CICADA_SESSION_TOKEN'));
const token: string = AuthService.getSessionToken();
// if (token) { if (token) {
// request = request.clone({headers: request.headers.set('Authorization', 'Bearer ' + token)}); request = request.clone({ headers: request.headers.set('Authorization', 'Bearer ' + token) });
// } }
return next.handle(request); return next.handle(request);
} }

View File

@ -14,13 +14,6 @@ import { BehaviorSubject, Observable } from 'rxjs';
providedIn: 'root', providedIn: 'root',
}) })
export class AuthService { export class AuthService {
mutableKeyStore: MutableKeyStore;
trustedUsers: Array<Staff> = [];
private trustedUsersList: BehaviorSubject<Array<Staff>> = new BehaviorSubject<Array<Staff>>(
this.trustedUsers
);
trustedUsersSubject: Observable<Array<Staff>> = this.trustedUsersList.asObservable();
constructor( constructor(
private httpClient: HttpClient, private httpClient: HttpClient,
private loggingService: LoggingService, private loggingService: LoggingService,
@ -28,6 +21,16 @@ export class AuthService {
) { ) {
this.mutableKeyStore = new MutablePgpKeyStore(); this.mutableKeyStore = new MutablePgpKeyStore();
} }
mutableKeyStore: MutableKeyStore;
trustedUsers: Array<Staff> = [];
private trustedUsersList: BehaviorSubject<Array<Staff>> = new BehaviorSubject<Array<Staff>>(
this.trustedUsers
);
trustedUsersSubject: Observable<Array<Staff>> = this.trustedUsersList.asObservable();
public static getSessionToken(): string {
return sessionStorage.getItem(btoa('CICADA_SESSION_TOKEN'));
}
async init(): Promise<void> { async init(): Promise<void> {
await this.mutableKeyStore.loadKeyring(); await this.mutableKeyStore.loadKeyring();
@ -35,10 +38,6 @@ export class AuthService {
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 { setSessionToken(token): void {
sessionStorage.setItem(btoa('CICADA_SESSION_TOKEN'), token); sessionStorage.setItem(btoa('CICADA_SESSION_TOKEN'), token);
@ -49,85 +48,80 @@ export class AuthService {
} }
getWithToken(): Promise<boolean> { getWithToken(): Promise<boolean> {
const headers = { const headers = {
Authorization: 'Bearer ' + this.getSessionToken, Authorization: 'Bearer ' + AuthService.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,
}; };
return fetch(environment.cicMetaUrl, options).then((response) => { return fetch(environment.cicMetaUrl, options).then((response) => {
if (!response.ok) { if (!response.ok) {
this.loggingService.sendErrorLevelMessage('failed to get with auth token.', this.loggingService.sendErrorLevelMessage('failed to get with auth token.', this, {
this, error: '',
{ error: "" }); });
return false; return false;
} }
return 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
sendSignedChallenge(hobaResponseEncoded: any): Promise<any> { sendSignedChallenge(hobaResponseEncoded: any): Promise<any> {
const headers = { const headers = {
Authorization: 'HOBA ' + hobaResponseEncoded, Authorization: 'HOBA ' + hobaResponseEncoded,
'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,
}; };
return fetch(environment.cicMetaUrl, options) return fetch(environment.cicMetaUrl, options);
} }
getChallenge(): Promise<any> { getChallenge(): Promise<any> {
return fetch(environment.cicMetaUrl) return fetch(environment.cicMetaUrl).then((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 hobaParseChallengeHeader(authHeader);
return hobaParseChallengeHeader(authHeader); }
} });
});
} }
async login(): Promise<boolean> { async login(): Promise<boolean> {
if (this.getSessionToken()) { if (AuthService.getSessionToken()) {
sessionStorage.removeItem(btoa('CICADA_SESSION_TOKEN')); sessionStorage.removeItem(btoa('CICADA_SESSION_TOKEN'));
} else {
const o = await this.getChallenge();
const r = await signChallenge(
o.challenge,
o.realm,
environment.cicMetaUrl,
this.mutableKeyStore
);
const tokenResponse = await this.sendSignedChallenge(r)
.then(response => {
const token = response.headers.get('Token')
if (token) {
return token
}
if (response.status === 401) {
let e = new HttpError("You are not authorized to use this system", response.status)
throw e
}
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
} }
const o = await this.getChallenge();
const r = await signChallenge(
o.challenge,
o.realm,
environment.cicMetaUrl,
this.mutableKeyStore
);
const tokenResponse = await this.sendSignedChallenge(r).then((response) => {
const token = response.headers.get('Token');
if (token) {
return token;
}
if (response.status === 401) {
throw new HttpError('You are not authorized to use this system', response.status);
}
if (!response.ok) {
throw new HttpError('Unknown error from authentication server', response.status);
}
});
if (tokenResponse) {
this.setSessionToken(tokenResponse);
this.setState('Click button to log in');
return true;
}
return false;
} }
loginView(): void { loginView(): void {

View File

@ -1,6 +1,6 @@
import { Injectable } from '@angular/core'; import { Injectable } from '@angular/core';
import { Settings } from '@app/_models'; import { Settings } from '@app/_models';
import { TransactionHelper } from 'cic-client'; import { TransactionHelper } from '@cicnet/cic-client';
import { first } from 'rxjs/operators'; import { first } from 'rxjs/operators';
import { TransactionService } from '@app/_services/transaction.service'; import { TransactionService } from '@app/_services/transaction.service';
import { environment } from '@src/environments/environment'; import { environment } from '@src/environments/environment';

View File

@ -1,8 +1,10 @@
import { Injectable } from '@angular/core'; import { Injectable } from '@angular/core';
import { environment } from '@src/environments/environment'; import { environment } from '@src/environments/environment';
import { CICRegistry, FileGetter } from 'cic-client'; import { CICRegistry, FileGetter } from '@cicnet/cic-client';
import { AccountIndex, TokenRegistry } from '@app/_eth';
import { HttpGetter } from '@app/_helpers'; import { HttpGetter } from '@app/_helpers';
import { Web3Service } from '@app/_services/web3.service'; import { Web3Service } from '@app/_services/web3.service';
import { BehaviorSubject } from 'rxjs';
@Injectable({ @Injectable({
providedIn: 'root', providedIn: 'root',
@ -10,8 +12,9 @@ import { Web3Service } from '@app/_services/web3.service';
export class RegistryService { export class RegistryService {
static fileGetter: FileGetter = new HttpGetter(); static fileGetter: FileGetter = new HttpGetter();
private static registry: CICRegistry; private static registry: CICRegistry;
private static tokenRegistry: TokenRegistry;
constructor() {} private static accountRegistry: AccountIndex;
private static load: BehaviorSubject<boolean> = new BehaviorSubject<boolean>(false);
public static async getRegistry(): Promise<CICRegistry> { public static async getRegistry(): Promise<CICRegistry> {
if (!RegistryService.registry) { if (!RegistryService.registry) {
@ -24,7 +27,43 @@ export class RegistryService {
); );
RegistryService.registry.declaratorHelper.addTrust(environment.trustedDeclaratorAddress); RegistryService.registry.declaratorHelper.addTrust(environment.trustedDeclaratorAddress);
await RegistryService.registry.load(); await RegistryService.registry.load();
RegistryService.load.next(true);
return RegistryService.registry;
} }
return RegistryService.registry; return RegistryService.registry;
} }
public static async getTokenRegistry(): Promise<TokenRegistry> {
if (!RegistryService.tokenRegistry) {
// then initial it
const registry = await RegistryService.getRegistry();
RegistryService.load.subscribe(async (status: boolean) => {
if (status) {
const tokenRegistryAddress = await registry.getContractAddressByName('TokenRegistry');
RegistryService.tokenRegistry = new TokenRegistry(tokenRegistryAddress);
return RegistryService.tokenRegistry;
}
});
// return new Promise((resolve, reject) => {
// resolve(RegistryService.tokenRegistry);
// });
}
return RegistryService.tokenRegistry;
}
public static async getAccountRegistry(): Promise<AccountIndex> {
if (!RegistryService.accountRegistry) {
const registry = await RegistryService.getRegistry();
RegistryService.load.subscribe(async (status: boolean) => {
if (status) {
const accountIndexAddress: string = await registry.getContractAddressByName(
'AccountRegistry'
);
RegistryService.accountRegistry = new AccountIndex(accountIndexAddress);
return RegistryService.accountRegistry;
}
});
}
return RegistryService.accountRegistry;
}
} }

View File

@ -1,10 +1,9 @@
import { Injectable } from '@angular/core'; import { Injectable } from '@angular/core';
import { CICRegistry } from 'cic-client'; import { CICRegistry } from '@cicnet/cic-client';
import { TokenRegistry } from '@app/_eth'; import { TokenRegistry } from '@app/_eth';
import { HttpClient } from '@angular/common/http';
import { RegistryService } from '@app/_services/registry.service'; import { RegistryService } from '@app/_services/registry.service';
import { Token } from '@app/_models'; import { Token } from '@app/_models';
import {BehaviorSubject, Observable, Subject} from 'rxjs'; import { BehaviorSubject, Observable, Subject } from 'rxjs';
@Injectable({ @Injectable({
providedIn: 'root', providedIn: 'root',
@ -12,21 +11,19 @@ import {BehaviorSubject, Observable, Subject} from 'rxjs';
export class TokenService { export class TokenService {
registry: CICRegistry; registry: CICRegistry;
tokenRegistry: TokenRegistry; tokenRegistry: TokenRegistry;
onload: (status: boolean) => void;
tokens: Array<Token> = []; tokens: Array<Token> = [];
private tokensList: BehaviorSubject<Array<Token>> = new BehaviorSubject<Array<Token>>(this.tokens); private tokensList: BehaviorSubject<Array<Token>> = new BehaviorSubject<Array<Token>>(
this.tokens
);
tokensSubject: Observable<Array<Token>> = this.tokensList.asObservable(); tokensSubject: Observable<Array<Token>> = this.tokensList.asObservable();
load: BehaviorSubject<boolean> = new BehaviorSubject<boolean>(false);
constructor(private httpClient: HttpClient) {} constructor() {}
async init(): Promise<void> { async init(): Promise<void> {
this.registry = await RegistryService.getRegistry(); this.registry = await RegistryService.getRegistry();
this.registry.onload = async (address: string): Promise<void> => { this.tokenRegistry = await RegistryService.getTokenRegistry();
this.tokenRegistry = new TokenRegistry( this.load.next(true);
await this.registry.getContractAddressByName('TokenRegistry')
);
this.onload(this.tokenRegistry !== undefined);
};
} }
addToken(token: Token): void { addToken(token: Token): void {

View File

@ -14,7 +14,7 @@ import { AuthService } from '@app/_services/auth.service';
import { defaultAccount } from '@app/_models'; import { defaultAccount } from '@app/_models';
import { LoggingService } from '@app/_services/logging.service'; import { LoggingService } from '@app/_services/logging.service';
import { HttpClient } from '@angular/common/http'; import { HttpClient } from '@angular/common/http';
import { CICRegistry } from 'cic-client'; import { CICRegistry } from '@cicnet/cic-client';
import { RegistryService } from '@app/_services/registry.service'; import { RegistryService } from '@app/_services/registry.service';
import Web3 from 'web3'; import Web3 from 'web3';
import { Web3Service } from '@app/_services/web3.service'; import { Web3Service } from '@app/_services/web3.service';

View File

@ -7,10 +7,9 @@ import { ArgPair, Envelope, Phone, Syncable, User } from 'cic-client-meta';
import { AccountDetails } from '@app/_models'; import { AccountDetails } from '@app/_models';
import { LoggingService } from '@app/_services/logging.service'; import { LoggingService } from '@app/_services/logging.service';
import { TokenService } from '@app/_services/token.service'; import { TokenService } from '@app/_services/token.service';
import { AccountIndex } from '@app/_eth';
import { MutableKeyStore, PGPSigner, Signer } from '@app/_pgp'; import { MutableKeyStore, PGPSigner, Signer } from '@app/_pgp';
import { RegistryService } from '@app/_services/registry.service'; import { RegistryService } from '@app/_services/registry.service';
import { CICRegistry } from 'cic-client'; import { CICRegistry } from '@cicnet/cic-client';
import { AuthService } from '@app/_services/auth.service'; import { AuthService } from '@app/_services/auth.service';
import { personValidation, vcardValidation } from '@app/_helpers'; import { personValidation, vcardValidation } from '@app/_helpers';
import { add0x } from '@src/assets/js/ethtx/dist/hex'; import { add0x } from '@src/assets/js/ethtx/dist/hex';
@ -43,7 +42,7 @@ export class UserService {
) {} ) {}
async init(): Promise<void> { async init(): Promise<void> {
await this.authService.init(); // await this.authService.init();
await this.tokenService.init(); await this.tokenService.init();
this.keystore = this.authService.mutableKeyStore; this.keystore = this.authService.mutableKeyStore;
this.signer = new PGPSigner(this.keystore); this.signer = new PGPSigner(this.keystore);
@ -179,11 +178,8 @@ export class UserService {
async loadAccounts(limit: number = 100, offset: number = 0): Promise<void> { async loadAccounts(limit: number = 100, offset: number = 0): Promise<void> {
this.resetAccountsList(); this.resetAccountsList();
const accountIndexAddress: string = await this.registry.getContractAddressByName( const accountRegistry = await RegistryService.getAccountRegistry();
'AccountRegistry' const accountAddresses: Array<string> = await accountRegistry.last(limit);
);
const accountIndexQuery = new AccountIndex(accountIndexAddress);
const accountAddresses: Array<string> = await accountIndexQuery.last(limit);
this.loggingService.sendInfoLevelMessage(accountAddresses); this.loggingService.sendInfoLevelMessage(accountAddresses);
for (const accountAddress of accountAddresses.slice(offset, offset + limit)) { for (const accountAddress of accountAddresses.slice(offset, offset + limit)) {
await this.getAccountByAddress(accountAddress, limit); await this.getAccountByAddress(accountAddress, limit);
@ -201,11 +197,13 @@ export class UserService {
const account: Syncable = Envelope.fromJSON(JSON.stringify(res)).unwrap(); const account: Syncable = Envelope.fromJSON(JSON.stringify(res)).unwrap();
const accountInfo = account.m.data; const accountInfo = account.m.data;
await personValidation(accountInfo); await personValidation(accountInfo);
this.tokenService.onload = async (status: boolean): Promise<void> => { this.tokenService.load.subscribe(async (status: boolean) => {
accountInfo.balance = await this.tokenService.getTokenBalance( if (status) {
accountInfo.identities.evm[`bloxberg:${environment.bloxbergChainId}`][0] accountInfo.balance = await this.tokenService.getTokenBalance(
); accountInfo.identities.evm[`bloxberg:${environment.bloxbergChainId}`][0]
}; );
}
});
accountInfo.vcard = vCard.parse(atob(accountInfo.vcard)); accountInfo.vcard = vCard.parse(atob(accountInfo.vcard));
await vcardValidation(accountInfo.vcard); await vcardValidation(accountInfo.vcard);
this.addAccount(accountInfo, limit); this.addAccount(accountInfo, limit);

View File

@ -22,7 +22,7 @@ export class AuthComponent implements OnInit {
private authService: AuthService, private authService: AuthService,
private formBuilder: FormBuilder, private formBuilder: FormBuilder,
private router: Router, private router: Router,
private errorDialogService: ErrorDialogService, private errorDialogService: ErrorDialogService
) {} ) {}
async ngOnInit(): Promise<void> { async ngOnInit(): Promise<void> {
@ -49,10 +49,10 @@ export class AuthComponent implements OnInit {
async login(): Promise<void> { async login(): Promise<void> {
try { try {
const loginResult = await this.authService.login() const loginResult = await this.authService.login();
if (loginResult) { if (loginResult) {
this.router.navigate(['/home']); this.router.navigate(['/home']);
} }
} catch (HttpError) { } catch (HttpError) {
this.errorDialogService.openDialog({ this.errorDialogService.openDialog({
message: HttpError.message, message: HttpError.message,

View File

@ -29,9 +29,11 @@ export class TokensComponent implements OnInit {
async ngOnInit(): Promise<void> { async ngOnInit(): Promise<void> {
await this.tokenService.init(); await this.tokenService.init();
this.tokenService.onload = async (status: boolean): Promise<void> => { this.tokenService.load.subscribe(async (status: boolean) => {
await this.tokenService.getTokens(); if (status) {
}; await this.tokenService.getTokens();
}
});
this.tokenService.tokensSubject.subscribe((tokens) => { this.tokenService.tokensSubject.subscribe((tokens) => {
this.loggingService.sendInfoLevelMessage(tokens); this.loggingService.sendInfoLevelMessage(tokens);
this.dataSource = new MatTableDataSource(tokens); this.dataSource = new MatTableDataSource(tokens);

View File

@ -6,7 +6,7 @@ export const environment = {
logLevel: NgxLoggerLevel.ERROR, logLevel: NgxLoggerLevel.ERROR,
serverLogLevel: NgxLoggerLevel.OFF, serverLogLevel: NgxLoggerLevel.OFF,
loggingUrl: 'http://localhost:8000', loggingUrl: 'http://localhost:8000',
cicMetaUrl: 'https://meta.dev.grassrootseconomics.net', cicMetaUrl: 'https://meta-auth.dev.grassrootseconomics.net',
publicKeysUrl: 'https://dev.grassrootseconomics.net/.well-known/publickeys/', publicKeysUrl: 'https://dev.grassrootseconomics.net/.well-known/publickeys/',
cicCacheUrl: 'https://cache.dev.grassrootseconomics.net', cicCacheUrl: 'https://cache.dev.grassrootseconomics.net',
web3Provider: 'wss://bloxberg-ws.dev.grassrootseconomics.net', web3Provider: 'wss://bloxberg-ws.dev.grassrootseconomics.net',