Scrap HttpWrapperService.

This commit is contained in:
Spencer Ofwiti 2021-03-21 14:02:18 +03:00
parent 8e26628092
commit 0ce75b2951
15 changed files with 49 additions and 153 deletions

View File

@ -45,7 +45,7 @@ class MutablePgpKeyStore implements MutableKeyStore{
} }
importPublicKey(publicKey: any): void { importPublicKey(publicKey: any): void {
keyring.publicKeys.importKey(publicKey) keyring.publicKeys.importKey(publicKey);
} }
async importPrivateKey(privateKey: any): Promise<void> { async importPrivateKey(privateKey: any): Promise<void> {
@ -78,12 +78,8 @@ class MutablePgpKeyStore implements MutableKeyStore{
async isValidKey(key): Promise<boolean> { async isValidKey(key): Promise<boolean> {
// There is supposed to be an opengpg.readKey() method but I can't find it? // There is supposed to be an opengpg.readKey() method but I can't find it?
const _key = await openpgp.key.readArmored(key) const _key = await openpgp.key.readArmored(key);
if (_key.err) { return !_key.err;
return false
} else {
return true
}
} }
getFingerprint(): string { getFingerprint(): string {

View File

@ -3,12 +3,11 @@ import { hobaParseChallengeHeader } from '@src/assets/js/hoba.js';
import { signChallenge } from '@src/assets/js/hoba-pgp.js'; import { signChallenge } from '@src/assets/js/hoba-pgp.js';
import {environment} from '@src/environments/environment'; import {environment} from '@src/environments/environment';
import {LoggingService} from '@app/_services/logging.service'; import {LoggingService} from '@app/_services/logging.service';
import {HttpWrapperService} from '@app/_services/http-wrapper.service';
import {MutableKeyStore, MutablePgpKeyStore} from '@app/_pgp'; import {MutableKeyStore, MutablePgpKeyStore} from '@app/_pgp';
import {ErrorDialogService} from '@app/_services/error-dialog.service'; import {ErrorDialogService} from '@app/_services/error-dialog.service';
import {catchError, first, tap} from 'rxjs/operators'; import {tap} from 'rxjs/operators';
import { HttpClient, HttpErrorResponse } from '@angular/common/http'; import { HttpClient, HttpErrorResponse } from '@angular/common/http';
import { throwError } from 'rxjs'; import {Observable, throwError} from 'rxjs';
@Injectable({ @Injectable({
providedIn: 'root' providedIn: 'root'
@ -20,7 +19,6 @@ export class AuthService {
mutableKeyStore: MutableKeyStore = new MutablePgpKeyStore(); mutableKeyStore: MutableKeyStore = new MutablePgpKeyStore();
constructor( constructor(
private httpWrapperService: HttpWrapperService,
private httpClient: HttpClient, private httpClient: HttpClient,
private loggingService: LoggingService, private loggingService: LoggingService,
private errorDialogService: ErrorDialogService private errorDialogService: ErrorDialogService
@ -125,7 +123,7 @@ export class AuthService {
try { try {
const isValidKeyCheck = await this.mutableKeyStore.isValidKey(privateKeyArmored) const isValidKeyCheck = await this.mutableKeyStore.isValidKey(privateKeyArmored)
if (!isValidKeyCheck) { if (!isValidKeyCheck) {
throw Error("The private key is invalid") throw Error('The private key is invalid');
} }
const key = await this.mutableKeyStore.importPrivateKey(privateKeyArmored); const key = await this.mutableKeyStore.importPrivateKey(privateKeyArmored);
localStorage.setItem(btoa('CICADA_PRIVATE_KEY'), privateKeyArmored); localStorage.setItem(btoa('CICADA_PRIVATE_KEY'), privateKeyArmored);
@ -152,12 +150,12 @@ export class AuthService {
return trustedUsers; return trustedUsers;
} }
getPublicKeys() { getPublicKeys(): Observable<any> {
return this.httpClient.get(`${environment.publicKeysUrl}`, {responseType: 'text'}) return this.httpClient.get(`${environment.publicKeysUrl}`, {responseType: 'text'})
.pipe(tap( .pipe(tap(
data => { }, data => { },
error => { this.handleError(error, 'Unable to load trusted public keys.') } error => { this.handleError(error, 'Unable to load trusted public keys.'); }
)) ));
} }
async getPrivateKeys(): Promise<void> { async getPrivateKeys(): Promise<void> {
@ -167,7 +165,7 @@ export class AuthService {
} }
// TODO this is from the docs and for reference. Move it somewhere better. // TODO this is from the docs and for reference. Move it somewhere better.
private handleError(error: HttpErrorResponse, customMessage: string) { private handleError(error: HttpErrorResponse, customMessage: string): Observable<any> {
if (error.error instanceof ErrorEvent) { if (error.error instanceof ErrorEvent) {
// A client-side or network error occurred. Handle it accordingly. // A client-side or network error occurred. Handle it accordingly.
console.error('An error occurred:', error.error.message); console.error('An error occurred:', error.error.message);

View File

@ -59,11 +59,11 @@ export class BlockSyncService {
}); });
if (address === null) { if (address === null) {
this.transactionService.getAllTransactions(offset, limit).pipe(first()).subscribe(res => { this.transactionService.getAllTransactions(offset, limit).pipe(first()).subscribe(res => {
this.fetcher(settings, res.body); this.fetcher(settings, res);
}); });
} else { } else {
this.transactionService.getAddressTransactions(address, offset, limit).pipe(first()).subscribe(res => { this.transactionService.getAddressTransactions(address, offset, limit).pipe(first()).subscribe(res => {
this.fetcher(settings, res.body); this.fetcher(settings, res);
}); });
} }
} }

View File

@ -1,16 +0,0 @@
import { TestBed } from '@angular/core/testing';
import { HttpWrapperService } from './http-wrapper.service';
describe('HttpWrapperService', () => {
let service: HttpWrapperService;
beforeEach(() => {
TestBed.configureTestingModule({});
service = TestBed.inject(HttpWrapperService);
});
it('should be created', () => {
expect(service).toBeTruthy();
});
});

View File

@ -1,60 +0,0 @@
import { Injectable } from '@angular/core';
import {HttpClient, HttpRequest} from '@angular/common/http';
import {Observable} from 'rxjs';
import * as moment from 'moment';
import { Moment } from 'moment';
import {LoggingService} from '@app/_services/logging.service';
@Injectable({
providedIn: 'root'
})
export class HttpWrapperService {
constructor(
private http: HttpClient,
private loggingService: LoggingService,
) { }
get(url: string, options?: any): Observable<Response> {
return this.request('GET', url, null, options);
}
post(url: string, body: any, options?: any): Observable<Response> {
return this.request('POST', url, body, options);
}
put(url: string, body: any, options?: any): Observable<Response> {
return this.request('PUT', url, body, options);
}
delete(url: string, options?: any): Observable<Response> {
return this.request('DELETE', url, null, options);
}
private logTime(startMoment: Moment, url: string, method: string): void {
const requestDuration = moment().diff(startMoment, 'milliseconds');
this.loggingService.sendInfoLevelMessage(`HTTP ${method}, URL: ${url}, Duration: ${requestDuration} ms`);
}
private request(method: string, url: string, body?: any, options?: any): Observable<any> {
this.loggingService.sendInfoLevelMessage(`Options: ${options}`);
return Observable.create((observer: any) => {
const requestBeginTime = moment();
this.http.request(new HttpRequest(method, url, body, options)).subscribe((response) => {
this.loggingService.sendInfoLevelMessage(response);
this.logTime(requestBeginTime, `${url}`, method);
observer.next(response);
observer.complete();
}, (error) => {
switch (error.status) {
case 403:
observer.complete();
break;
default:
observer.error(error);
break;
}
});
});
}
}

View File

@ -5,5 +5,4 @@ export * from '@app/_services/token.service';
export * from '@app/_services/block-sync.service'; export * from '@app/_services/block-sync.service';
export * from '@app/_services/location.service'; export * from '@app/_services/location.service';
export * from '@app/_services/logging.service'; export * from '@app/_services/logging.service';
export * from '@app/_services/http-wrapper.service';
export * from '@app/_services/error-dialog.service'; export * from '@app/_services/error-dialog.service';

View File

@ -2,7 +2,7 @@ import { Injectable } from '@angular/core';
import {BehaviorSubject} from 'rxjs'; import {BehaviorSubject} from 'rxjs';
import {environment} from '@src/environments/environment'; import {environment} from '@src/environments/environment';
import {first} from 'rxjs/operators'; import {first} from 'rxjs/operators';
import {HttpWrapperService} from '@app/_services/http-wrapper.service'; import {HttpClient} from '@angular/common/http';
@Injectable({ @Injectable({
providedIn: 'root' providedIn: 'root'
@ -13,10 +13,10 @@ export class LocationService {
locationsSubject = this.locationsList.asObservable(); locationsSubject = this.locationsList.asObservable();
constructor( constructor(
private httpWrapperService: HttpWrapperService, private httpClient: HttpClient,
) { } ) { }
getLocations(): void { getLocations(): void {
this.httpWrapperService.get(`${environment.cicCacheUrl}/locations`).pipe(first()).subscribe(res => this.locationsList.next(res.body)); this.httpClient.get(`${environment.cicCacheUrl}/locations`).pipe(first()).subscribe(res => this.locationsList.next(res));
} }
} }

View File

@ -4,8 +4,8 @@ import {BehaviorSubject, Observable} from 'rxjs';
import {HttpGetter} from '@app/_helpers'; import {HttpGetter} from '@app/_helpers';
import {CICRegistry} from 'cic-client'; import {CICRegistry} from 'cic-client';
import Web3 from 'web3'; import Web3 from 'web3';
import {HttpWrapperService} from '@app/_services/http-wrapper.service';
import {Registry, TokenRegistry} from '@app/_eth'; import {Registry, TokenRegistry} from '@app/_eth';
import {HttpClient} from '@angular/common/http';
@Injectable({ @Injectable({
providedIn: 'root' providedIn: 'root'
@ -20,7 +20,7 @@ export class TokenService {
tokensSubject = this.tokensList.asObservable(); tokensSubject = this.tokensList.asObservable();
constructor( constructor(
private httpWrapperService: HttpWrapperService, private httpClient: HttpClient,
) { } ) { }
async getTokens(): Promise<any> { async getTokens(): Promise<any> {
@ -30,7 +30,7 @@ export class TokenService {
} }
getTokenBySymbol(symbol: string): Observable<any> { getTokenBySymbol(symbol: string): Observable<any> {
return this.httpWrapperService.get(`${environment.cicCacheUrl}/tokens/${symbol}`); return this.httpClient.get(`${environment.cicCacheUrl}/tokens/${symbol}`);
} }
async getTokenBalance(address: string): Promise<number> { async getTokenBalance(address: string): Promise<number> {

View File

@ -13,8 +13,8 @@ import * as secp256k1 from 'secp256k1';
import {AuthService} from '@app/_services/auth.service'; 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 {HttpWrapperService} from '@app/_services/http-wrapper.service';
import {Registry} from '@app/_eth'; import {Registry} from '@app/_eth';
import {HttpClient} from '@angular/common/http';
const Web3 = require('web3'); const Web3 = require('web3');
const vCard = require('vcard-parser'); const vCard = require('vcard-parser');
@ -30,18 +30,18 @@ export class TransactionService {
registry = new Registry(environment.registryAddress); registry = new Registry(environment.registryAddress);
constructor( constructor(
private httpWrapperService: HttpWrapperService, private httpClient: HttpClient,
private authService: AuthService, private authService: AuthService,
private userService: UserService, private userService: UserService,
private loggingService: LoggingService private loggingService: LoggingService
) { } ) { }
getAllTransactions(offset: number, limit: number): Observable<any> { getAllTransactions(offset: number, limit: number): Observable<any> {
return this.httpWrapperService.get(`${environment.cicCacheUrl}/tx/${offset}/${limit}`); return this.httpClient.get(`${environment.cicCacheUrl}/tx/${offset}/${limit}`);
} }
getAddressTransactions(address: string, offset: number, limit: number): Observable<any> { getAddressTransactions(address: string, offset: number, limit: number): Observable<any> {
return this.httpWrapperService.get(`${environment.cicCacheUrl}/tx/${address}/${offset}/${limit}`); return this.httpClient.get(`${environment.cicCacheUrl}/tx/${address}/${offset}/${limit}`);
} }
async setTransaction(transaction, cacheSize: number): Promise<void> { async setTransaction(transaction, cacheSize: number): Promise<void> {

View File

@ -6,7 +6,6 @@ import {first} from 'rxjs/operators';
import {ArgPair, Envelope, Syncable, User} from 'cic-client-meta'; import {ArgPair, Envelope, Syncable, User} from 'cic-client-meta';
import {MetaResponse} from '@app/_models'; import {MetaResponse} from '@app/_models';
import {LoggingService} from '@app/_services/logging.service'; import {LoggingService} from '@app/_services/logging.service';
import {HttpWrapperService} from '@app/_services/http-wrapper.service';
import {TokenService} from '@app/_services/token.service'; import {TokenService} from '@app/_services/token.service';
import {AccountIndex, Registry} from '@app/_eth'; import {AccountIndex, Registry} from '@app/_eth';
import {MutableKeyStore, MutablePgpKeyStore, PGPSigner, Signer} from '@app/_pgp'; import {MutableKeyStore, MutablePgpKeyStore, PGPSigner, Signer} from '@app/_pgp';
@ -35,8 +34,7 @@ export class UserService {
staffSubject = this.staffList.asObservable(); staffSubject = this.staffList.asObservable();
constructor( constructor(
private http: HttpClient, private httpClient: HttpClient,
private httpWrapperService: HttpWrapperService,
private loggingService: LoggingService, private loggingService: LoggingService,
private tokenService: TokenService private tokenService: TokenService
) { ) {
@ -44,16 +42,16 @@ export class UserService {
resetPin(phone: string): Observable<any> { resetPin(phone: string): Observable<any> {
const params = new HttpParams().set('phoneNumber', phone); const params = new HttpParams().set('phoneNumber', phone);
return this.httpWrapperService.get(`${environment.cicUssdUrl}/pin`, {params}); return this.httpClient.get(`${environment.cicUssdUrl}/pin`, {params});
} }
getAccountStatus(phone: string): any { getAccountStatus(phone: string): any {
const params = new HttpParams().set('phoneNumber', phone); const params = new HttpParams().set('phoneNumber', phone);
return this.httpWrapperService.get(`${environment.cicUssdUrl}/pin`, {params}); return this.httpClient.get(`${environment.cicUssdUrl}/pin`, {params});
} }
getLockedAccounts(offset: number, limit: number): any { getLockedAccounts(offset: number, limit: number): any {
return this.httpWrapperService.get(`${environment.cicUssdUrl}/accounts/locked/${offset}/${limit}`); return this.httpClient.get(`${environment.cicUssdUrl}/accounts/locked/${offset}/${limit}`);
} }
async changeAccountInfo(address: string, name: string, phoneNumber: string, age: string, type: string, bio: string, gender: string, async changeAccountInfo(address: string, name: string, phoneNumber: string, age: string, type: string, bio: string, gender: string,
@ -75,8 +73,8 @@ export class UserService {
accountInfo.vcard = vCard.generate(accountInfo.vcard); accountInfo.vcard = vCard.generate(accountInfo.vcard);
reqBody.m.data = accountInfo; reqBody.m.data = accountInfo;
const accountKey = await User.toKey(address); const accountKey = await User.toKey(address);
this.httpWrapperService.get(`${environment.cicMetaUrl}/${accountKey}`, { headers: this.headers }).pipe(first()).subscribe(async res => { this.httpClient.get(`${environment.cicMetaUrl}/${accountKey}`, { headers: this.headers }).pipe(first()).subscribe(async res => {
const syncableAccount: Syncable = Envelope.fromJSON(JSON.stringify(res.body)).unwrap(); const syncableAccount: Syncable = Envelope.fromJSON(JSON.stringify(res)).unwrap();
let update = []; let update = [];
for (const prop in reqBody) { for (const prop in reqBody) {
update.push(new ArgPair(prop, reqBody[prop])); update.push(new ArgPair(prop, reqBody[prop]));
@ -94,67 +92,47 @@ export class UserService {
async updateMeta(syncableAccount: Syncable, accountKey: string, headers: HttpHeaders): Promise<any> { async updateMeta(syncableAccount: Syncable, accountKey: string, headers: HttpHeaders): Promise<any> {
const envelope = await this.wrap(syncableAccount , this.signer); const envelope = await this.wrap(syncableAccount , this.signer);
const reqBody = envelope.toJSON(); const reqBody = envelope.toJSON();
this.httpWrapperService.put(`${environment.cicMetaUrl}/${accountKey}`, reqBody , { headers }).pipe(first()).subscribe(res => { this.httpClient.put(`${environment.cicMetaUrl}/${accountKey}`, reqBody , { headers }).pipe(first()).subscribe(res => {
this.loggingService.sendInfoLevelMessage(`Response: ${res.body}`); this.loggingService.sendInfoLevelMessage(`Response: ${res}`);
}); });
} }
getAccounts(): void { getAccounts(): void {
this.httpWrapperService.get(`${environment.cicCacheUrl}/accounts`).pipe(first()).subscribe(res => this.accountsList.next(res.body)); this.httpClient.get(`${environment.cicCacheUrl}/accounts`).pipe(first()).subscribe(res => this.accountsList.next(res));
} }
getAccountById(id: number): Observable<any> { getAccountById(id: number): Observable<any> {
return this.httpWrapperService.get(`${environment.cicCacheUrl}/accounts/${id}`); return this.httpClient.get(`${environment.cicCacheUrl}/accounts/${id}`);
} }
getActions(): void { getActions(): void {
this.httpWrapperService.get(`${environment.cicCacheUrl}/actions`).pipe(first()).subscribe(res => this.actionsList.next(res.body)); this.httpClient.get(`${environment.cicCacheUrl}/actions`).pipe(first()).subscribe(res => this.actionsList.next(res));
} }
getActionById(id: string): any { getActionById(id: string): any {
return this.httpWrapperService.get(`${environment.cicCacheUrl}/actions/${id}`); return this.httpClient.get(`${environment.cicCacheUrl}/actions/${id}`);
} }
approveAction(id: string): Observable<any> { approveAction(id: string): Observable<any> {
return this.httpWrapperService.post(`${environment.cicCacheUrl}/actions/${id}`, { approval: true }); return this.httpClient.post(`${environment.cicCacheUrl}/actions/${id}`, { approval: true });
} }
revokeAction(id: string): Observable<any> { revokeAction(id: string): Observable<any> {
return this.httpWrapperService.post(`${environment.cicCacheUrl}/actions/${id}`, { approval: false }); return this.httpClient.post(`${environment.cicCacheUrl}/actions/${id}`, { approval: false });
} }
getHistoryByUser(id: string): Observable<any> { getHistoryByUser(id: string): Observable<any> {
return this.httpWrapperService.get(`${environment.cicCacheUrl}/history/${id}`); return this.httpClient.get(`${environment.cicCacheUrl}/history/${id}`);
}
getStaff(): void {
this.httpWrapperService.get(`${environment.cicCacheUrl}/staff`).pipe(first()).subscribe(res => this.staffList.next(res.body));
}
getStaffById(id: string): Observable<any> {
return this.httpWrapperService.get(`${environment.cicCacheUrl}/staff/${id}`);
}
activateStaff(id: string): Observable<any> {
return this.httpWrapperService.post(`${environment.cicCacheUrl}/staff/${id}`, {status: 'activated'});
}
deactivateStaff(id: string): Observable<any> {
return this.httpWrapperService.post(`${environment.cicCacheUrl}/staff/${id}`, {status: 'deactivated'});
}
changeStaffType(id: string, type: string): Observable<any> {
return this.httpWrapperService.post(`${environment.cicCacheUrl}/staff/${id}`, {accountType: type});
} }
getAccountDetailsFromMeta(userKey: string): Observable<any> { getAccountDetailsFromMeta(userKey: string): Observable<any> {
return this.http.get(`${environment.cicMetaUrl}/${userKey}`, { headers: this.headers }); return this.httpClient.get(`${environment.cicMetaUrl}/${userKey}`, { headers: this.headers });
} }
getUser(userKey: string): any { getUser(userKey: string): any {
return this.httpWrapperService.get(`${environment.cicMetaUrl}/${userKey}`, { headers: this.headers }) return this.httpClient.get(`${environment.cicMetaUrl}/${userKey}`, { headers: this.headers })
.pipe(first()).subscribe(async res => { .pipe(first()).subscribe(async res => {
return Envelope.fromJSON(JSON.stringify(res.body)).unwrap(); return Envelope.fromJSON(JSON.stringify(res)).unwrap();
}); });
} }

View File

@ -21,7 +21,7 @@ export class AppComponent {
) { ) {
(async () => { (async () => {
await this.authService.mutableKeyStore.loadKeyring(); await this.authService.mutableKeyStore.loadKeyring();
this.authService.getPublicKeys().subscribe(this.authService.mutableKeyStore.importPublicKey) this.authService.getPublicKeys().subscribe(this.authService.mutableKeyStore.importPublicKey);
// this.loggingService.sendInfoLevelMessage(await this.tokenService.getTokens()); // this.loggingService.sendInfoLevelMessage(await this.tokenService.getTokens());
})(); })();
this.mediaQuery.addListener(this.onResize); this.mediaQuery.addListener(this.onResize);

View File

@ -100,7 +100,7 @@ export class AccountDetailsComponent implements OnInit {
}); });
}); });
this.userService.getHistoryByUser(this.accountAddress).pipe(first()).subscribe(response => { this.userService.getHistoryByUser(this.accountAddress).pipe(first()).subscribe(response => {
this.historyDataSource = new MatTableDataSource<any>(response.body); this.historyDataSource = new MatTableDataSource<any>(response);
this.historyDataSource.paginator = this.historyTablePaginator; this.historyDataSource.paginator = this.historyTablePaginator;
this.historyDataSource.sort = this.historyTableSort; this.historyDataSource.sort = this.historyTableSort;
}); });
@ -203,7 +203,7 @@ export class AccountDetailsComponent implements OnInit {
resetPin(): void { resetPin(): void {
this.userService.resetPin(this.account.phone).pipe(first()).subscribe(res => { this.userService.resetPin(this.account.phone).pipe(first()).subscribe(res => {
this.loggingService.sendInfoLevelMessage(`Response: ${res.body}`); this.loggingService.sendInfoLevelMessage(`Response: ${res}`);
}); });
} }

View File

@ -40,6 +40,7 @@ export class AccountsComponent implements OnInit {
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;
this.paginator._changePageSize(this.paginator.pageSize);
this.dataSource.sort = this.sort; this.dataSource.sort = this.sort;
this.accounts = accounts; this.accounts = accounts;
}); });

View File

@ -51,12 +51,12 @@ export class AdminComponent implements OnInit {
} }
approveAction(action: any): void { approveAction(action: any): void {
this.userService.approveAction(action.id).pipe(first()).subscribe(res => this.loggingService.sendInfoLevelMessage(res.body)); this.userService.approveAction(action.id).pipe(first()).subscribe(res => this.loggingService.sendInfoLevelMessage(res));
this.userService.getActions(); this.userService.getActions();
} }
revertAction(action: any): void { revertAction(action: any): void {
this.userService.revokeAction(action.id).pipe(first()).subscribe(res => this.loggingService.sendInfoLevelMessage(res.body)); this.userService.revokeAction(action.id).pipe(first()).subscribe(res => this.loggingService.sendInfoLevelMessage(res));
this.userService.getActions(); this.userService.getActions();
} }

View File

@ -18,7 +18,7 @@ export class TokenDetailsComponent implements OnInit {
) { ) {
this.route.paramMap.subscribe((params: Params) => { this.route.paramMap.subscribe((params: Params) => {
this.tokenService.getTokenBySymbol(params.get('id')).pipe(first()).subscribe(res => { this.tokenService.getTokenBySymbol(params.get('id')).pipe(first()).subscribe(res => {
this.token = res.body; this.token = res;
}); });
}); });
} }