From 8c9eb4a6a339eb29b1207a2e936a8f66414fe979 Mon Sep 17 00:00:00 2001 From: Blair Vanderlugt Date: Sat, 12 Jun 2021 09:57:30 -0700 Subject: [PATCH 01/11] added account registry to registries --- src/app/_services/registry.service.ts | 83 ++++++++++++++++----------- src/app/_services/user.service.ts | 23 +++++--- 2 files changed, 65 insertions(+), 41 deletions(-) diff --git a/src/app/_services/registry.service.ts b/src/app/_services/registry.service.ts index 0f652fb..5e67991 100644 --- a/src/app/_services/registry.service.ts +++ b/src/app/_services/registry.service.ts @@ -1,7 +1,8 @@ import { Injectable } from '@angular/core'; + import { environment } from '@src/environments/environment'; import { CICRegistry, FileGetter } from '@cicnet/cic-client'; -import { TokenRegistry } from '@app/_eth'; +import { TokenRegistry, AccountIndex } from '@app/_eth'; import { HttpGetter } from '@app/_helpers'; import { Web3Service } from '@app/_services/web3.service'; @@ -12,43 +13,59 @@ import { Web3Service } from '@app/_services/web3.service'; //} @Injectable({ - providedIn: 'root', + providedIn: 'root', }) export class RegistryService { - static fileGetter: FileGetter = new HttpGetter(); - private static registry: CICRegistry; - private static tokenRegistry: TokenRegistry; - //private static registries: RegistryCollection; + static fileGetter: FileGetter = new HttpGetter(); + private static registry: CICRegistry; + private static tokenRegistry: TokenRegistry; + private static accountRegistry: AccountIndex; + //private static registries: RegistryCollection; - public static async getRegistry(): Promise { - if (!RegistryService.registry) { - RegistryService.registry = new CICRegistry( - Web3Service.getInstance(), - environment.registryAddress, - 'Registry', - RegistryService.fileGetter, - ['../../assets/js/block-sync/data'] - ); - RegistryService.registry.declaratorHelper.addTrust(environment.trustedDeclaratorAddress); - await RegistryService.registry.load() + public static async getRegistry(): Promise { + if (!RegistryService.registry) { + RegistryService.registry = new CICRegistry( + Web3Service.getInstance(), + environment.registryAddress, + 'Registry', + RegistryService.fileGetter, + ['../../assets/js/block-sync/data'] + ); + RegistryService.registry.declaratorHelper.addTrust(environment.trustedDeclaratorAddress); + await RegistryService.registry.load() + } + return RegistryService.registry; } - return RegistryService.registry; - } - public static async getTokenRegistry(): Promise { - if (!RegistryService.tokenRegistry) { - //then initial it - const registry = await RegistryService.getRegistry() - const tokenRegistryAddress = await RegistryService.registry.getContractAddressByName('TokenRegistry') - RegistryService.tokenRegistry = new TokenRegistry(tokenRegistryAddress); - return new Promise((resolve, reject) => { - resolve(RegistryService.tokenRegistry) - }) - } - return new Promise((resolve, reject) => { - resolve(RegistryService.tokenRegistry); - }) - } + public static async getTokenRegistry(): Promise { + return new Promise(async (resolve, reject) => { + if (!RegistryService.tokenRegistry) { + const registry = await RegistryService.getRegistry() + const tokenRegistryAddress = await RegistryService.registry.getContractAddressByName('TokenRegistry') + if (!tokenRegistryAddress) { + return reject("Unable to initialize Token Registry") + } + RegistryService.tokenRegistry = new TokenRegistry(tokenRegistryAddress); + return resolve(RegistryService.tokenRegistry) + } + return resolve(RegistryService.tokenRegistry); + }) + } + + public static async getAccountRegistry(): Promise { + return new Promise(async (resolve, reject) => { + if (!RegistryService.accountRegistry) { + const registry = await RegistryService.getRegistry() + const accountRegistryAddress = await RegistryService.registry.getContractAddressByName('AccountRegistry') + if (!accountRegistryAddress) { + return reject("Unable to initialize Account Registry") + } + RegistryService.accountRegistry = new AccountIndex(accountRegistryAddress); + return resolve(RegistryService.accountRegistry) + } + return resolve(RegistryService.accountRegistry); + }) + } } diff --git a/src/app/_services/user.service.ts b/src/app/_services/user.service.ts index 82b6551..9dd604f 100644 --- a/src/app/_services/user.service.ts +++ b/src/app/_services/user.service.ts @@ -179,14 +179,21 @@ export class UserService { async loadAccounts(limit: number = 100, offset: number = 0): Promise { this.resetAccountsList(); - const accountIndexAddress: string = await this.registry.getContractAddressByName( - 'AccountRegistry' - ); - const accountIndexQuery = new AccountIndex(accountIndexAddress); - const accountAddresses: Array = await accountIndexQuery.last(limit); - this.loggingService.sendInfoLevelMessage(accountAddresses); - for (const accountAddress of accountAddresses.slice(offset, offset + limit)) { - await this.getAccountByAddress(accountAddress, limit); + //const accountIndexAddress: string = await this.registry.getContractAddressByName( + // 'AccountRegistry' + //); + //const accountIndexQuery = new AccountIndex(accountIndexAddress); + //const accountAddresses: Array = await accountIndexQuery.last(limit); + try{ + const accountRegistry = await RegistryService.getAccountRegistry(); + const accountAddresses: Array = await accountRegistry.last(limit); + this.loggingService.sendInfoLevelMessage(accountAddresses); + for (const accountAddress of accountAddresses.slice(offset, offset + limit)) { + await this.getAccountByAddress(accountAddress, limit); + } + } catch (error) { + this.loggingService.sendErrorLevelMessage("Unable to load accounts.", "user.service", error) + throw error } } From f815c28bc04c26b854e35a1d73100c7a14ebc490 Mon Sep 17 00:00:00 2001 From: Blair Vanderlugt Date: Sat, 12 Jun 2021 10:15:13 -0700 Subject: [PATCH 02/11] fix imports --- src/app/_services/block-sync.service.ts | 2 +- src/app/_services/registry.service.ts | 2 +- src/app/_services/token.service.ts | 2 +- src/app/_services/transaction.service.ts | 2 +- src/app/_services/user.service.ts | 2 +- 5 files changed, 5 insertions(+), 5 deletions(-) diff --git a/src/app/_services/block-sync.service.ts b/src/app/_services/block-sync.service.ts index 55b03e6..f983a6d 100644 --- a/src/app/_services/block-sync.service.ts +++ b/src/app/_services/block-sync.service.ts @@ -1,6 +1,6 @@ import { Injectable } from '@angular/core'; import { Settings } from '@app/_models'; -import { TransactionHelper } from 'cic-client'; +import { TransactionHelper } from '@cicnet/cic-client'; import { first } from 'rxjs/operators'; import { TransactionService } from '@app/_services/transaction.service'; import { environment } from '@src/environments/environment'; diff --git a/src/app/_services/registry.service.ts b/src/app/_services/registry.service.ts index ac2bbd7..bac571a 100644 --- a/src/app/_services/registry.service.ts +++ b/src/app/_services/registry.service.ts @@ -1,7 +1,7 @@ import { Injectable } from '@angular/core'; import { environment } from '@src/environments/environment'; -import { CICRegistry, FileGetter } from '@cicnet/cic-client'; +import { CICRegistry, FileGetter } from '@cicnet/@cicnet/cic-client'; import { TokenRegistry, AccountIndex } from '@app/_eth'; import { HttpGetter } from '@app/_helpers'; import { Web3Service } from '@app/_services/web3.service'; diff --git a/src/app/_services/token.service.ts b/src/app/_services/token.service.ts index d9ffed8..0c40549 100644 --- a/src/app/_services/token.service.ts +++ b/src/app/_services/token.service.ts @@ -1,5 +1,5 @@ import { Injectable } from '@angular/core'; -import { CICRegistry } from 'cic-client'; +import { CICRegistry } from '@cicnet/cic-client'; import { TokenRegistry } from '@app/_eth'; import { HttpClient } from '@angular/common/http'; import { RegistryService } from '@app/_services/registry.service'; diff --git a/src/app/_services/transaction.service.ts b/src/app/_services/transaction.service.ts index 5a6c7d8..63937b0 100644 --- a/src/app/_services/transaction.service.ts +++ b/src/app/_services/transaction.service.ts @@ -14,7 +14,7 @@ import { AuthService } from '@app/_services/auth.service'; import { defaultAccount } from '@app/_models'; import { LoggingService } from '@app/_services/logging.service'; 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 Web3 from 'web3'; import { Web3Service } from '@app/_services/web3.service'; diff --git a/src/app/_services/user.service.ts b/src/app/_services/user.service.ts index a81ff9a..fd03138 100644 --- a/src/app/_services/user.service.ts +++ b/src/app/_services/user.service.ts @@ -10,7 +10,7 @@ import { TokenService } from '@app/_services/token.service'; import { AccountIndex } from '@app/_eth'; import { MutableKeyStore, PGPSigner, Signer } from '@app/_pgp'; 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 { personValidation, vcardValidation } from '@app/_helpers'; import { add0x } from '@src/assets/js/ethtx/dist/hex'; From 81861f57406aae6be4b506c6d08616c5bc8e4eb1 Mon Sep 17 00:00:00 2001 From: Blair Vanderlugt Date: Sat, 12 Jun 2021 10:34:47 -0700 Subject: [PATCH 03/11] account registry added --- src/app/_services/registry.service.ts | 2 +- src/environments/environment.ts | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/app/_services/registry.service.ts b/src/app/_services/registry.service.ts index bac571a..ac2bbd7 100644 --- a/src/app/_services/registry.service.ts +++ b/src/app/_services/registry.service.ts @@ -1,7 +1,7 @@ import { Injectable } from '@angular/core'; import { environment } from '@src/environments/environment'; -import { CICRegistry, FileGetter } from '@cicnet/@cicnet/cic-client'; +import { CICRegistry, FileGetter } from '@cicnet/cic-client'; import { TokenRegistry, AccountIndex } from '@app/_eth'; import { HttpGetter } from '@app/_helpers'; import { Web3Service } from '@app/_services/web3.service'; diff --git a/src/environments/environment.ts b/src/environments/environment.ts index df02af7..f2d7c4f 100644 --- a/src/environments/environment.ts +++ b/src/environments/environment.ts @@ -6,7 +6,7 @@ export const environment = { logLevel: NgxLoggerLevel.ERROR, serverLogLevel: NgxLoggerLevel.OFF, 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/', cicCacheUrl: 'https://cache.dev.grassrootseconomics.net', web3Provider: 'wss://bloxberg-ws.dev.grassrootseconomics.net', From ad71df5c52efa970bbddbc0bf3b1cfbf53d09d38 Mon Sep 17 00:00:00 2001 From: Blair Vanderlugt Date: Sat, 12 Jun 2021 10:57:20 -0700 Subject: [PATCH 04/11] auth double click got dropped from the revert I think --- src/app/_services/auth.service.ts | 312 +++++++++++++++--------------- 1 file changed, 155 insertions(+), 157 deletions(-) diff --git a/src/app/_services/auth.service.ts b/src/app/_services/auth.service.ts index 937f2ce..87c79b5 100644 --- a/src/app/_services/auth.service.ts +++ b/src/app/_services/auth.service.ts @@ -11,91 +11,90 @@ import { Staff } from '@app/_models'; import { BehaviorSubject, Observable } from 'rxjs'; @Injectable({ - providedIn: 'root', + providedIn: 'root', }) export class AuthService { - mutableKeyStore: MutableKeyStore; - trustedUsers: Array = []; - private trustedUsersList: BehaviorSubject> = new BehaviorSubject>( - this.trustedUsers - ); - trustedUsersSubject: Observable> = this.trustedUsersList.asObservable(); + mutableKeyStore: MutableKeyStore; + trustedUsers: Array = []; + private trustedUsersList: BehaviorSubject> = new BehaviorSubject>( + this.trustedUsers + ); + trustedUsersSubject: Observable> = this.trustedUsersList.asObservable(); - constructor( - private httpClient: HttpClient, - private loggingService: LoggingService, - private errorDialogService: ErrorDialogService - ) { - this.mutableKeyStore = new MutablePgpKeyStore(); - } - - async init(): Promise { - await this.mutableKeyStore.loadKeyring(); - if (localStorage.getItem(btoa('CICADA_PRIVATE_KEY'))) { - await this.mutableKeyStore.importPrivateKey(localStorage.getItem(btoa('CICADA_PRIVATE_KEY'))); + constructor( + private httpClient: HttpClient, + private loggingService: LoggingService, + private errorDialogService: ErrorDialogService + ) { + this.mutableKeyStore = new MutablePgpKeyStore(); } - } - - getSessionToken(): string { - return sessionStorage.getItem(btoa('CICADA_SESSION_TOKEN')); - } - setSessionToken(token): void { - sessionStorage.setItem(btoa('CICADA_SESSION_TOKEN'), token); - } - - setState(s): void { - document.getElementById('state').innerHTML = s; - } - - getWithToken(): Promise { - const headers = { - Authorization: 'Bearer ' + this.getSessionToken, - 'Content-Type': 'application/json;charset=utf-8', - 'x-cic-automerge': 'none', - }; - const options = { - headers, - }; - return fetch(environment.cicMetaUrl, options).then((response) => { - if (!response.ok) { - this.loggingService.sendErrorLevelMessage('failed to get with auth token.', - this, - { error: "" }); - - return false; + async init(): Promise { + await this.mutableKeyStore.loadKeyring(); + if (localStorage.getItem(btoa('CICADA_PRIVATE_KEY'))) { + await this.mutableKeyStore.importPrivateKey(localStorage.getItem(btoa('CICADA_PRIVATE_KEY'))); } - return true; - }); - } + } - // TODO rename to send signed challenge and set session. Also separate these responsibilities - sendSignedChallenge(hobaResponseEncoded: any): Promise { - const headers = { - Authorization: 'HOBA ' + hobaResponseEncoded, - 'Content-Type': 'application/json;charset=utf-8', - 'x-cic-automerge': 'none', - }; - const options = { - headers, - }; - return fetch(environment.cicMetaUrl, options) - } + getSessionToken(): string { + return sessionStorage.getItem(btoa('CICADA_SESSION_TOKEN')); + } - getChallenge(): Promise { - return fetch(environment.cicMetaUrl) + setSessionToken(token): void { + sessionStorage.setItem(btoa('CICADA_SESSION_TOKEN'), token); + } + + setState(s): void { + document.getElementById('state').innerHTML = s; + } + + getWithToken(): Promise { + const headers = { + Authorization: 'Bearer ' + this.getSessionToken, + 'Content-Type': 'application/json;charset=utf-8', + 'x-cic-automerge': 'none', + }; + const options = { + headers, + }; + return fetch(environment.cicMetaUrl, options).then((response) => { + if (!response.ok) { + this.loggingService.sendErrorLevelMessage('failed to get with auth token.', + this, + { error: "" }); + return false; + } + return true; + }); + } + + // TODO rename to send signed challenge and set session. Also separate these responsibilities + sendSignedChallenge(hobaResponseEncoded: any): Promise { + const headers = { + Authorization: 'HOBA ' + hobaResponseEncoded, + 'Content-Type': 'application/json;charset=utf-8', + 'x-cic-automerge': 'none', + }; + const options = { + headers, + }; + return fetch(environment.cicMetaUrl, options) + } + + getChallenge(): Promise { + return fetch(environment.cicMetaUrl) .then(response => { if (response.status === 401) { const authHeader: string = response.headers.get('WWW-Authenticate'); return hobaParseChallengeHeader(authHeader); } }); - } + } - async login(): Promise { - if (this.getSessionToken()) { - sessionStorage.removeItem(btoa('CICADA_SESSION_TOKEN')); - } else { + async login(): Promise { + if (this.getSessionToken()) { + sessionStorage.removeItem(btoa('CICADA_SESSION_TOKEN')); + } const o = await this.getChallenge(); const r = await signChallenge( @@ -106,20 +105,20 @@ export class AuthService { ); 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 - } - }) + .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); @@ -128,83 +127,82 @@ export class AuthService { } return false } - } - 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'); - } - // TODO leaving this out for now. - // const isEncryptedKeyCheck = await this.mutableKeyStore.isEncryptedPrivateKey(privateKeyArmored); - // if (!isEncryptedKeyCheck) { - // throw Error('The private key doesn\'t have a password!'); - // } - const key = await this.mutableKeyStore.importPrivateKey(privateKeyArmored); - localStorage.setItem(btoa('CICADA_PRIVATE_KEY'), privateKeyArmored); - } catch (err) { - this.loggingService.sendErrorLevelMessage( - `Failed to set key: ${err.message || err.statusText}`, - this, - { error: err } - ); - this.errorDialogService.openDialog({ - message: `Failed to set key: ${err.message || err.statusText}`, - }); - return false; + 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()); } - this.loginView(); - return true; - } - logout(): void { - sessionStorage.removeItem(btoa('CICADA_SESSION_TOKEN')); - localStorage.removeItem(btoa('CICADA_PRIVATE_KEY')); - window.location.reload(); - } - - addTrustedUser(user: Staff): void { - const savedIndex = this.trustedUsers.findIndex((staff) => staff.userid === user.userid); - if (savedIndex === 0) { - return; - } - if (savedIndex > 0) { - this.trustedUsers.splice(savedIndex, 1); - } - this.trustedUsers.unshift(user); - this.trustedUsersList.next(this.trustedUsers); - } - - getTrustedUsers(): void { - this.mutableKeyStore.getPublicKeys().forEach((key) => { - this.addTrustedUser(key.users[0].userId); - }); - } - - async getPublicKeys(): Promise { - return new Promise((resolve, reject) => { - fetch(environment.publicKeysUrl).then((res) => { - if (!res.ok) { - // TODO does angular recommend an error interface? - return reject(rejectBody(res)); + async setKey(privateKeyArmored): Promise { + try { + const isValidKeyCheck = await this.mutableKeyStore.isValidKey(privateKeyArmored); + if (!isValidKeyCheck) { + throw Error('The private key is invalid'); + } + // TODO leaving this out for now. + // const isEncryptedKeyCheck = await this.mutableKeyStore.isEncryptedPrivateKey(privateKeyArmored); + // if (!isEncryptedKeyCheck) { + // throw Error('The private key doesn\'t have a password!'); + // } + const key = await this.mutableKeyStore.importPrivateKey(privateKeyArmored); + localStorage.setItem(btoa('CICADA_PRIVATE_KEY'), privateKeyArmored); + } catch (err) { + this.loggingService.sendErrorLevelMessage( + `Failed to set key: ${err.message || err.statusText}`, + this, + { error: err } + ); + this.errorDialogService.openDialog({ + message: `Failed to set key: ${err.message || err.statusText}`, + }); + return false; } - return resolve(res.text()); - }); - }); - } + this.loginView(); + return true; + } - getPrivateKey(): any { - return this.mutableKeyStore.getPrivateKey(); - } + logout(): void { + sessionStorage.removeItem(btoa('CICADA_SESSION_TOKEN')); + localStorage.removeItem(btoa('CICADA_PRIVATE_KEY')); + window.location.reload(); + } - getPrivateKeyInfo(): any { - return this.getPrivateKey().users[0].userId; - } + addTrustedUser(user: Staff): void { + const savedIndex = this.trustedUsers.findIndex((staff) => staff.userid === user.userid); + if (savedIndex === 0) { + return; + } + if (savedIndex > 0) { + this.trustedUsers.splice(savedIndex, 1); + } + this.trustedUsers.unshift(user); + this.trustedUsersList.next(this.trustedUsers); + } + + getTrustedUsers(): void { + this.mutableKeyStore.getPublicKeys().forEach((key) => { + this.addTrustedUser(key.users[0].userId); + }); + } + + async getPublicKeys(): Promise { + return new Promise((resolve, reject) => { + fetch(environment.publicKeysUrl).then((res) => { + if (!res.ok) { + // TODO does angular recommend an error interface? + return reject(rejectBody(res)); + } + return resolve(res.text()); + }); + }); + } + + getPrivateKey(): any { + return this.mutableKeyStore.getPrivateKey(); + } + + getPrivateKeyInfo(): any { + return this.getPrivateKey().users[0].userId; + } } From 36c6d4b16dc50bacccf9a21bac55d50a73812eba Mon Sep 17 00:00:00 2001 From: Blair Vanderlugt Date: Sat, 12 Jun 2021 12:37:54 -0700 Subject: [PATCH 05/11] added comment and indents --- src/app/_eth/accountIndex.ts | 7 +++++-- src/app/_services/registry.service.ts | 5 ++++- 2 files changed, 9 insertions(+), 3 deletions(-) diff --git a/src/app/_eth/accountIndex.ts b/src/app/_eth/accountIndex.ts index bf7445b..7764800 100644 --- a/src/app/_eth/accountIndex.ts +++ b/src/app/_eth/accountIndex.ts @@ -12,10 +12,13 @@ export class AccountIndex { constructor(contractAddress: string, signerAddress?: string) { this.contractAddress = contractAddress; this.contract = new web3.eth.Contract(abi, this.contractAddress); + // TODO this signer logic should be part of the web3service + // if signer address is not passed (for example in user service) then + // this fallsback to a web3 wallet that is not even connected??? if (signerAddress) { - this.signerAddress = signerAddress; + this.signerAddress = signerAddress; } else { - this.signerAddress = web3.eth.accounts[0]; + this.signerAddress = web3.eth.accounts[0]; } } diff --git a/src/app/_services/registry.service.ts b/src/app/_services/registry.service.ts index ac2bbd7..8bf3b00 100644 --- a/src/app/_services/registry.service.ts +++ b/src/app/_services/registry.service.ts @@ -51,7 +51,10 @@ export class RegistryService { return new Promise(async (resolve, reject) => { if (!RegistryService.accountRegistry) { const registry = await RegistryService.getRegistry() - const accountRegistryAddress = await RegistryService.registry.getContractAddressByName('AccountRegistry') + const accountRegistryAddress = await RegistryService + .registry + .getContractAddressByName('AccountRegistry') + if (!accountRegistryAddress) { return reject("Unable to initialize Account Registry") } From 472d9b2cd1b25392751bf0e47fd8752686c6b62a Mon Sep 17 00:00:00 2001 From: Spencer Ofwiti Date: Mon, 14 Jun 2021 16:50:04 +0300 Subject: [PATCH 06/11] Format files using linter. --- src/app/_eth/accountIndex.ts | 6 +- src/app/_services/auth.service.ts | 17 +++-- src/app/_services/registry.service.ts | 98 +++++++++++++-------------- src/app/_services/user.service.ts | 24 +++---- 4 files changed, 72 insertions(+), 73 deletions(-) diff --git a/src/app/_eth/accountIndex.ts b/src/app/_eth/accountIndex.ts index c8c94a7..42b115d 100644 --- a/src/app/_eth/accountIndex.ts +++ b/src/app/_eth/accountIndex.ts @@ -35,12 +35,12 @@ export class AccountIndex { this.contractAddress = contractAddress; this.contract = new web3.eth.Contract(abi, this.contractAddress); // TODO this signer logic should be part of the web3service - // if signer address is not passed (for example in user service) then + // if signer address is not passed (for example in user service) then // this fallsback to a web3 wallet that is not even connected??? if (signerAddress) { - this.signerAddress = signerAddress; + this.signerAddress = signerAddress; } else { - this.signerAddress = web3.eth.accounts[0]; + this.signerAddress = web3.eth.accounts[0]; } } diff --git a/src/app/_services/auth.service.ts b/src/app/_services/auth.service.ts index 30f2fe8..bc26bd7 100644 --- a/src/app/_services/auth.service.ts +++ b/src/app/_services/auth.service.ts @@ -82,15 +82,14 @@ export class AuthService { return fetch(environment.cicMetaUrl, options); } - getChallenge(): Promise { - return fetch(environment.cicMetaUrl) - .then(response => { - if (response.status === 401) { - const authHeader: string = response.headers.get('WWW-Authenticate'); - return hobaParseChallengeHeader(authHeader); - } - }); - } + getChallenge(): Promise { + return fetch(environment.cicMetaUrl).then((response) => { + if (response.status === 401) { + const authHeader: string = response.headers.get('WWW-Authenticate'); + return hobaParseChallengeHeader(authHeader); + } + }); + } async login(): Promise { if (this.getSessionToken()) { diff --git a/src/app/_services/registry.service.ts b/src/app/_services/registry.service.ts index 467f76a..39dd58d 100644 --- a/src/app/_services/registry.service.ts +++ b/src/app/_services/registry.service.ts @@ -9,58 +9,58 @@ import { Web3Service } from '@app/_services/web3.service'; providedIn: 'root', }) export class RegistryService { - static fileGetter: FileGetter = new HttpGetter(); - private static registry: CICRegistry; - private static tokenRegistry: TokenRegistry; - private static accountRegistry: AccountIndex; + static fileGetter: FileGetter = new HttpGetter(); + private static registry: CICRegistry; + private static tokenRegistry: TokenRegistry; + private static accountRegistry: AccountIndex; - public static async getRegistry(): Promise { - if (!RegistryService.registry) { - RegistryService.registry = new CICRegistry( - Web3Service.getInstance(), - environment.registryAddress, - 'Registry', - RegistryService.fileGetter, - ['../../assets/js/block-sync/data'] - ); - RegistryService.registry.declaratorHelper.addTrust(environment.trustedDeclaratorAddress); - await RegistryService.registry.load() + public static async getRegistry(): Promise { + if (!RegistryService.registry) { + RegistryService.registry = new CICRegistry( + Web3Service.getInstance(), + environment.registryAddress, + 'Registry', + RegistryService.fileGetter, + ['../../assets/js/block-sync/data'] + ); + RegistryService.registry.declaratorHelper.addTrust(environment.trustedDeclaratorAddress); + await RegistryService.registry.load(); + } + return RegistryService.registry; + } + public static async getTokenRegistry(): Promise { + return new Promise(async (resolve, reject) => { + if (!RegistryService.tokenRegistry) { + const registry = await RegistryService.getRegistry(); + const tokenRegistryAddress = await RegistryService.registry.getContractAddressByName( + 'TokenRegistry' + ); + if (!tokenRegistryAddress) { + return reject('Unable to initialize Token Registry'); } - return RegistryService.registry; - } + RegistryService.tokenRegistry = new TokenRegistry(tokenRegistryAddress); + return resolve(RegistryService.tokenRegistry); + } + return resolve(RegistryService.tokenRegistry); + }); + } - public static async getTokenRegistry(): Promise { - return new Promise(async (resolve, reject) => { - if (!RegistryService.tokenRegistry) { - const registry = await RegistryService.getRegistry() - const tokenRegistryAddress = await RegistryService.registry.getContractAddressByName('TokenRegistry') - if (!tokenRegistryAddress) { - return reject("Unable to initialize Token Registry") - } - RegistryService.tokenRegistry = new TokenRegistry(tokenRegistryAddress); - return resolve(RegistryService.tokenRegistry) - } - return resolve(RegistryService.tokenRegistry); - }) - } - - public static async getAccountRegistry(): Promise { - return new Promise(async (resolve, reject) => { - if (!RegistryService.accountRegistry) { - const registry = await RegistryService.getRegistry() - const accountRegistryAddress = await RegistryService - .registry - .getContractAddressByName('AccountRegistry') - - if (!accountRegistryAddress) { - return reject("Unable to initialize Account Registry") - } - RegistryService.accountRegistry = new AccountIndex(accountRegistryAddress); - return resolve(RegistryService.accountRegistry) - } - return resolve(RegistryService.accountRegistry); - }) - } + public static async getAccountRegistry(): Promise { + return new Promise(async (resolve, reject) => { + if (!RegistryService.accountRegistry) { + const registry = await RegistryService.getRegistry(); + const accountRegistryAddress = await RegistryService.registry.getContractAddressByName( + 'AccountRegistry' + ); + if (!accountRegistryAddress) { + return reject('Unable to initialize Account Registry'); + } + RegistryService.accountRegistry = new AccountIndex(accountRegistryAddress); + return resolve(RegistryService.accountRegistry); + } + return resolve(RegistryService.accountRegistry); + }); + } } diff --git a/src/app/_services/user.service.ts b/src/app/_services/user.service.ts index 1bce78f..914e73f 100644 --- a/src/app/_services/user.service.ts +++ b/src/app/_services/user.service.ts @@ -179,21 +179,21 @@ export class UserService { async loadAccounts(limit: number = 100, offset: number = 0): Promise { this.resetAccountsList(); - //const accountIndexAddress: string = await this.registry.getContractAddressByName( + // const accountIndexAddress: string = await this.registry.getContractAddressByName( // 'AccountRegistry' - //); - //const accountIndexQuery = new AccountIndex(accountIndexAddress); - //const accountAddresses: Array = await accountIndexQuery.last(limit); - try{ - const accountRegistry = await RegistryService.getAccountRegistry(); - const accountAddresses: Array = await accountRegistry.last(limit); - this.loggingService.sendInfoLevelMessage(accountAddresses); - for (const accountAddress of accountAddresses.slice(offset, offset + limit)) { + // ); + // const accountIndexQuery = new AccountIndex(accountIndexAddress); + // const accountAddresses: Array = await accountIndexQuery.last(limit); + try { + const accountRegistry = await RegistryService.getAccountRegistry(); + const accountAddresses: Array = await accountRegistry.last(limit); + this.loggingService.sendInfoLevelMessage(accountAddresses); + for (const accountAddress of accountAddresses.slice(offset, offset + limit)) { await this.getAccountByAddress(accountAddress, limit); - } + } } catch (error) { - this.loggingService.sendErrorLevelMessage("Unable to load accounts.", "user.service", error) - throw error + this.loggingService.sendErrorLevelMessage('Unable to load accounts.', 'user.service', error); + throw error; } } From 23d262303afd13ec6b60f64017967ebe61df4ba6 Mon Sep 17 00:00:00 2001 From: Spencer Ofwiti Date: Mon, 14 Jun 2021 17:03:17 +0300 Subject: [PATCH 07/11] Refactor auth guard to use session token. --- src/app/_guards/auth.guard.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/app/_guards/auth.guard.ts b/src/app/_guards/auth.guard.ts index 395d37b..f2383ec 100644 --- a/src/app/_guards/auth.guard.ts +++ b/src/app/_guards/auth.guard.ts @@ -39,7 +39,7 @@ export class AuthGuard implements CanActivate { route: ActivatedRouteSnapshot, state: RouterStateSnapshot ): Observable | Promise | boolean | UrlTree { - if (localStorage.getItem(btoa('CICADA_PRIVATE_KEY'))) { + if (sessionStorage.getItem(btoa('CICADA_SESSION_TOKEN'))) { return true; } this.router.navigate(['/auth']); From f6e709373ea90f78011fb7546e4e51622848c078 Mon Sep 17 00:00:00 2001 From: Spencer Ofwiti Date: Mon, 14 Jun 2021 17:10:40 +0300 Subject: [PATCH 08/11] Cleanup registry. --- src/app/_services/registry.service.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/app/_services/registry.service.ts b/src/app/_services/registry.service.ts index 39dd58d..9e94b07 100644 --- a/src/app/_services/registry.service.ts +++ b/src/app/_services/registry.service.ts @@ -33,7 +33,7 @@ export class RegistryService { return new Promise(async (resolve, reject) => { if (!RegistryService.tokenRegistry) { const registry = await RegistryService.getRegistry(); - const tokenRegistryAddress = await RegistryService.registry.getContractAddressByName( + const tokenRegistryAddress = await registry.getContractAddressByName( 'TokenRegistry' ); if (!tokenRegistryAddress) { @@ -50,7 +50,7 @@ export class RegistryService { return new Promise(async (resolve, reject) => { if (!RegistryService.accountRegistry) { const registry = await RegistryService.getRegistry(); - const accountRegistryAddress = await RegistryService.registry.getContractAddressByName( + const accountRegistryAddress = await registry.getContractAddressByName( 'AccountRegistry' ); From 11c814b2436fca71f4b102da11cc54cbbea7134f Mon Sep 17 00:00:00 2001 From: Spencer Ofwiti Date: Mon, 14 Jun 2021 17:19:49 +0300 Subject: [PATCH 09/11] Add check for meta url before adding bearer token. --- src/app/_interceptors/http-config.interceptor.ts | 13 +++++++++---- src/app/_services/registry.service.ts | 8 ++------ 2 files changed, 11 insertions(+), 10 deletions(-) diff --git a/src/app/_interceptors/http-config.interceptor.ts b/src/app/_interceptors/http-config.interceptor.ts index 0bce86a..cb4431c 100644 --- a/src/app/_interceptors/http-config.interceptor.ts +++ b/src/app/_interceptors/http-config.interceptor.ts @@ -4,6 +4,7 @@ import { Injectable } from '@angular/core'; // Third party imports import { Observable } from 'rxjs'; +import { environment } from '@src/environments/environment'; /** Intercepts and handles setting of configurations to outgoing HTTP request. */ @Injectable() @@ -19,11 +20,15 @@ export class HttpConfigInterceptor implements HttpInterceptor { * @returns The forwarded request. */ intercept(request: HttpRequest, next: HttpHandler): Observable> { - // const token: string = sessionStorage.getItem(btoa('CICADA_SESSION_TOKEN')); + if (request.url.startsWith(environment.cicMetaUrl)) { + const token: string = sessionStorage.getItem(btoa('CICADA_SESSION_TOKEN')); - // if (token) { - // request = request.clone({headers: request.headers.set('Authorization', 'Bearer ' + token)}); - // } + if (token) { + request = request.clone({ + headers: request.headers.set('Authorization', 'Bearer ' + token), + }); + } + } return next.handle(request); } diff --git a/src/app/_services/registry.service.ts b/src/app/_services/registry.service.ts index 9e94b07..d116efa 100644 --- a/src/app/_services/registry.service.ts +++ b/src/app/_services/registry.service.ts @@ -33,9 +33,7 @@ export class RegistryService { return new Promise(async (resolve, reject) => { if (!RegistryService.tokenRegistry) { const registry = await RegistryService.getRegistry(); - const tokenRegistryAddress = await registry.getContractAddressByName( - 'TokenRegistry' - ); + const tokenRegistryAddress = await registry.getContractAddressByName('TokenRegistry'); if (!tokenRegistryAddress) { return reject('Unable to initialize Token Registry'); } @@ -50,9 +48,7 @@ export class RegistryService { return new Promise(async (resolve, reject) => { if (!RegistryService.accountRegistry) { const registry = await RegistryService.getRegistry(); - const accountRegistryAddress = await registry.getContractAddressByName( - 'AccountRegistry' - ); + const accountRegistryAddress = await registry.getContractAddressByName('AccountRegistry'); if (!accountRegistryAddress) { return reject('Unable to initialize Account Registry'); From bdc8f98d6b2c234d10e6a43d925d2babdc6458d6 Mon Sep 17 00:00:00 2001 From: Spencer Ofwiti Date: Mon, 14 Jun 2021 17:23:45 +0300 Subject: [PATCH 10/11] Update environment variables. --- src/environments/environment.dev.ts | 2 +- src/environments/environment.prod.ts | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/environments/environment.dev.ts b/src/environments/environment.dev.ts index 978f71f..cde24f3 100644 --- a/src/environments/environment.dev.ts +++ b/src/environments/environment.dev.ts @@ -6,7 +6,7 @@ export const environment = { logLevel: NgxLoggerLevel.ERROR, serverLogLevel: NgxLoggerLevel.OFF, loggingUrl: '', - cicMetaUrl: 'https://meta.dev.grassrootseconomics.net', + cicMetaUrl: 'https://meta-auth.dev.grassrootseconomics.net', publicKeysUrl: 'https://dev.grassrootseconomics.net/.well-known/publickeys/', cicCacheUrl: 'https://cache.dev.grassrootseconomics.net', web3Provider: 'wss://bloxberg-ws.dev.grassrootseconomics.net', diff --git a/src/environments/environment.prod.ts b/src/environments/environment.prod.ts index f4786c1..32cc50b 100644 --- a/src/environments/environment.prod.ts +++ b/src/environments/environment.prod.ts @@ -6,7 +6,7 @@ export const environment = { logLevel: NgxLoggerLevel.ERROR, serverLogLevel: NgxLoggerLevel.OFF, loggingUrl: '', - cicMetaUrl: 'https://meta.dev.grassrootseconomics.net', + cicMetaUrl: 'https://meta-auth.dev.grassrootseconomics.net', publicKeysUrl: 'https://dev.grassrootseconomics.net/.well-known/publickeys/', cicCacheUrl: 'https://cache.dev.grassrootseconomics.net', web3Provider: 'wss://bloxberg-ws.dev.grassrootseconomics.net', From f0918087147461a026d2e5bcc6d40e8bec180627 Mon Sep 17 00:00:00 2001 From: Spencer Ofwiti Date: Mon, 14 Jun 2021 17:37:14 +0300 Subject: [PATCH 11/11] Add promises to get registry. --- src/app/_services/registry.service.ts | 27 +++++++++++++++------------ 1 file changed, 15 insertions(+), 12 deletions(-) diff --git a/src/app/_services/registry.service.ts b/src/app/_services/registry.service.ts index d116efa..5a6a879 100644 --- a/src/app/_services/registry.service.ts +++ b/src/app/_services/registry.service.ts @@ -15,18 +15,21 @@ export class RegistryService { private static accountRegistry: AccountIndex; public static async getRegistry(): Promise { - if (!RegistryService.registry) { - RegistryService.registry = new CICRegistry( - Web3Service.getInstance(), - environment.registryAddress, - 'Registry', - RegistryService.fileGetter, - ['../../assets/js/block-sync/data'] - ); - RegistryService.registry.declaratorHelper.addTrust(environment.trustedDeclaratorAddress); - await RegistryService.registry.load(); - } - return RegistryService.registry; + return new Promise(async (resolve, reject) => { + if (!RegistryService.registry) { + RegistryService.registry = new CICRegistry( + Web3Service.getInstance(), + environment.registryAddress, + 'Registry', + RegistryService.fileGetter, + ['../../assets/js/block-sync/data'] + ); + RegistryService.registry.declaratorHelper.addTrust(environment.trustedDeclaratorAddress); + await RegistryService.registry.load(); + return resolve(RegistryService.registry); + } + return resolve(RegistryService.registry); + }); } public static async getTokenRegistry(): Promise {