From a2e320d92323375b9a757414ccce5a7cbcbd770f Mon Sep 17 00:00:00 2001 From: Spencer Ofwiti Date: Sun, 25 Apr 2021 13:32:23 +0300 Subject: [PATCH] Refactor update of data on meta service. --- src/app/_interceptors/error.interceptor.ts | 2 +- src/app/_services/auth.service.ts | 7 ++- src/app/_services/user.service.ts | 39 +++++++++----- .../account-details.component.html | 4 +- .../account-details.component.ts | 53 +++++++++---------- 5 files changed, 59 insertions(+), 46 deletions(-) diff --git a/src/app/_interceptors/error.interceptor.ts b/src/app/_interceptors/error.interceptor.ts index 96c404f..1fbf0d9 100644 --- a/src/app/_interceptors/error.interceptor.ts +++ b/src/app/_interceptors/error.interceptor.ts @@ -37,7 +37,7 @@ export class ErrorInterceptor implements HttpInterceptor { this.router.navigateByUrl('/auth').then(); break; case 403: // forbidden - location.reload(true); + alert('Access to resource is not allowed!'); break; } // Return an observable with a user-facing error message. diff --git a/src/app/_services/auth.service.ts b/src/app/_services/auth.service.ts index ba4651a..eefe056 100644 --- a/src/app/_services/auth.service.ts +++ b/src/app/_services/auth.service.ts @@ -22,12 +22,17 @@ export class AuthService { private loggingService: LoggingService, private errorDialogService: ErrorDialogService ) { - // TODO setting these together shoulds be atomic + } + + async init(): Promise { + 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'))) { this.privateKey = localStorage.getItem(btoa('CICADA_PRIVATE_KEY')); + await this.getPrivateKeys(); } } diff --git a/src/app/_services/user.service.ts b/src/app/_services/user.service.ts index 27b344b..02dd4b3 100644 --- a/src/app/_services/user.service.ts +++ b/src/app/_services/user.service.ts @@ -1,16 +1,17 @@ import {Injectable} from '@angular/core'; -import {BehaviorSubject, Observable, of, Subject} from 'rxjs'; +import {BehaviorSubject, Observable, Subject} from 'rxjs'; import {HttpClient, HttpHeaders, HttpParams} from '@angular/common/http'; import {environment} from '@src/environments/environment'; import {first} from 'rxjs/operators'; import {ArgPair, Envelope, Phone, Syncable, User} from 'cic-client-meta'; -import {AccountDetails, MetaResponse} from '@app/_models'; +import {AccountDetails} from '@app/_models'; import {LoggingService} from '@app/_services/logging.service'; import {TokenService} from '@app/_services/token.service'; import {AccountIndex} from '@app/_eth'; -import {MutableKeyStore, MutablePgpKeyStore, PGPSigner, Signer} from '@app/_pgp'; +import {MutableKeyStore, PGPSigner, Signer} from '@app/_pgp'; import {RegistryService} from '@app/_services/registry.service'; import {CICRegistry} from 'cic-client'; +import {AuthService} from './auth.service'; const vCard = require('vcard-parser'); @Injectable({ @@ -18,8 +19,8 @@ const vCard = require('vcard-parser'); }) export class UserService { headers: HttpHeaders = new HttpHeaders({'x-cic-automerge': 'client'}); - keystore: MutableKeyStore = new MutablePgpKeyStore(); - signer: Signer = new PGPSigner(this.keystore); + keystore: MutableKeyStore; + signer: Signer; registry: CICRegistry; accountsMeta = []; @@ -40,7 +41,12 @@ export class UserService { private loggingService: LoggingService, private tokenService: TokenService, private registryService: RegistryService, + private authService: AuthService, ) { + this.authService.init().then(() => { + this.keystore = authService.mutableKeyStore; + this.signer = new PGPSigner(this.keystore); + }); this.registry = registryService.getRegistry(); this.registry.load(); } @@ -60,10 +66,16 @@ export class UserService { } async changeAccountInfo(address: string, name: string, phoneNumber: string, age: string, type: string, bio: string, gender: string, - businessCategory: string, userLocation: string, location: string, locationType: string, metaAccount: MetaResponse + businessCategory: string, userLocation: string, location: string, locationType: string, ): Promise { - let reqBody = metaAccount; - let accountInfo = reqBody.m.data; + let accountInfo: any = { + vcard: { + fn: [{}], + n: [{}], + tel: [{}] + }, + location: {} + }; accountInfo.vcard.fn[0].value = name; accountInfo.vcard.n[0].value = name.split(' '); accountInfo.vcard.tel[0].value = phoneNumber; @@ -75,14 +87,13 @@ export class UserService { accountInfo.location.area = location; accountInfo.location.area_name = userLocation; accountInfo.location.area_type = locationType; - accountInfo.vcard = vCard.generate(accountInfo.vcard); - reqBody.m.data = accountInfo; + accountInfo.vcard = btoa(vCard.generate(accountInfo.vcard)); const accountKey = await User.toKey(address); - this.httpClient.get(`${environment.cicMetaUrl}/${accountKey}`, { headers: this.headers }).pipe(first()).subscribe(async res => { + this.getAccountDetailsFromMeta(accountKey).pipe(first()).subscribe(async res => { const syncableAccount: Syncable = Envelope.fromJSON(JSON.stringify(res)).unwrap(); let update = []; - for (const prop in reqBody) { - update.push(new ArgPair(prop, reqBody[prop])); + for (const prop in accountInfo) { + update.push(new ArgPair(prop, accountInfo[prop])); } syncableAccount.update(update, 'client-branch'); await this.updateMeta(syncableAccount, accountKey, this.headers); @@ -184,7 +195,7 @@ export class UserService { return accountSubject.asObservable(); } - async getAccountByPhone(phoneNumber: string, limit: number = 100): Promise { + async getAccountByPhone(phoneNumber: string, limit: number = 100): Promise> { let accountSubject = new Subject(); this.getAccountDetailsFromMeta(await Phone.toKey(phoneNumber)).pipe(first()).subscribe(async res => { const response = Envelope.fromJSON(JSON.stringify(res)).unwrap(); diff --git a/src/app/pages/accounts/account-details/account-details.component.html b/src/app/pages/accounts/account-details/account-details.component.html index c1ee838..187ca9d 100644 --- a/src/app/pages/accounts/account-details/account-details.component.html +++ b/src/app/pages/accounts/account-details/account-details.component.html @@ -14,7 +14,7 @@
@@ -240,7 +240,7 @@
- +
diff --git a/src/app/pages/accounts/account-details/account-details.component.ts b/src/app/pages/accounts/account-details/account-details.component.ts index 8695592..7530d05 100644 --- a/src/app/pages/accounts/account-details/account-details.component.ts +++ b/src/app/pages/accounts/account-details/account-details.component.ts @@ -1,4 +1,4 @@ -import {ChangeDetectionStrategy, Component, OnInit, ViewChild} from '@angular/core'; +import {ChangeDetectionStrategy, ChangeDetectorRef, Component, OnInit, ViewChild} from '@angular/core'; import {MatTableDataSource} from '@angular/material/table'; import {MatPaginator} from '@angular/material/paginator'; import {MatSort} from '@angular/material/sort'; @@ -7,8 +7,6 @@ import {ActivatedRoute, Params, Router} from '@angular/router'; import {first} from 'rxjs/operators'; import {FormBuilder, FormGroup, Validators} from '@angular/forms'; import {CustomErrorStateMatcher, exportCsv} from '@app/_helpers'; -import {Envelope, User} from 'cic-client-meta'; -const vCard = require('vcard-parser'); @Component({ selector: 'app-account-details', @@ -34,9 +32,7 @@ export class AccountDetailsComponent implements OnInit { accountInfoForm: FormGroup; account: any; accountAddress: string; - accountBalance: number; accountStatus: any; - metaAccount: any; accounts: any[] = []; accountsType = 'all'; locations: any; @@ -56,7 +52,8 @@ export class AccountDetailsComponent implements OnInit { private router: Router, private tokenService: TokenService, private loggingService: LoggingService, - private blockSyncService: BlockSyncService + private blockSyncService: BlockSyncService, + private cdr: ChangeDetectorRef, ) { this.accountInfoForm = this.formBuilder.group({ name: ['', Validators.required], @@ -73,25 +70,27 @@ export class AccountDetailsComponent implements OnInit { this.route.paramMap.subscribe(async (params: Params) => { this.accountAddress = params.get('id'); this.bloxbergLink = 'https://blockexplorer.bloxberg.org/address/' + this.accountAddress + '/transactions'; - this.userService.getAccountDetailsFromMeta(await User.toKey(this.accountAddress)).pipe(first()).subscribe(async res => { - this.metaAccount = Envelope.fromJSON(JSON.stringify(res.body)).unwrap(); - this.account = this.metaAccount.m.data; - this.loggingService.sendInfoLevelMessage(this.account); - this.accountBalance = await this.tokenService.getTokenBalance(this.accountAddress); - this.account.vcard = vCard.parse(atob(this.account.vcard)); - this.userService.getAccountStatus(this.account.vcard?.tel[0].value).pipe(first()).subscribe(response => this.accountStatus = response); - this.accountInfoForm.patchValue({ - name: this.account.vcard?.fn[0].value, - phoneNumber: this.account.vcard?.tel[0].value, - age: this.account.age, - type: this.account.type, - bio: this.account.products, - gender: this.account.gender, - businessCategory: this.account.category, - userLocation: this.account.location.area_name, - location: this.account.location.area, - locationType: this.account.location.area_type, - }); + (await this.userService.getAccountByAddress(this.accountAddress, 100)).subscribe(async res => { + if (res !== undefined) { + this.account = res; + this.cdr.detectChanges(); + this.loggingService.sendInfoLevelMessage(this.account); + // this.userService.getAccountStatus(this.account.vcard?.tel[0].value).pipe(first()).subscribe(response => this.accountStatus = response); + this.accountInfoForm.patchValue({ + name: this.account.vcard?.fn[0].value, + phoneNumber: this.account.vcard?.tel[0].value, + age: this.account.age, + type: this.account.type, + bio: this.account.products, + gender: this.account.gender, + businessCategory: this.account.category, + userLocation: this.account.location.area_name, + location: this.account.location.area, + locationType: this.account.location.area_type, + }); + } else { + alert('Account not found!'); + } }); this.blockSyncService.blockSync(this.accountAddress); }); @@ -140,7 +139,7 @@ export class AccountDetailsComponent implements OnInit { this.submitted = true; if (this.accountInfoForm.invalid || !confirm('Change user\'s profile information?')) { return; } const accountKey = await this.userService.changeAccountInfo( - this.account.address, + this.accountAddress, this.accountInfoFormStub.name.value, this.accountInfoFormStub.phoneNumber.value, this.accountInfoFormStub.age.value, @@ -151,9 +150,7 @@ export class AccountDetailsComponent implements OnInit { this.accountInfoFormStub.userLocation.value, this.accountInfoFormStub.location.value, this.accountInfoFormStub.locationType.value, - this.metaAccount ); - this.loggingService.sendInfoLevelMessage(`Response: ${accountKey}`); this.submitted = false; }