Merge branch 'spencer/refactor-environments' into 'master'

Refactor environment variables.

See merge request grassrootseconomics/cic-staff-client!4
This commit is contained in:
Spencer Ofwiti 2021-03-19 14:18:01 +00:00
commit 0668abd62d
11 changed files with 444 additions and 354 deletions

11
.env.example Normal file
View File

@ -0,0 +1,11 @@
LOG_LEVEL=
SERVER_LEVEL=
CIC_CHAIN_ID=
CIC_LOGGING_URL=
CIC_META_URL=
CIC_KEYS_URL=
CIC_CACHE_URL=
CIC_WEB3_PROVIDER=
CIC_USSD_URL=
CIC_REGISTRY_ADDRESS=
CIC_TRUSTED_ADDRESS=

4
.gitignore vendored
View File

@ -44,3 +44,7 @@ testem.log
# System Files # System Files
.DS_Store .DS_Store
Thumbs.db Thumbs.db
# Configuration Files
.env
/src/environments

View File

@ -10,7 +10,7 @@ Run `npm install -g @angular/cli` to install the angular CLI.
## Development server ## Development server
Run `ng serve` for a dev server. Navigate to `http://localhost:4200/`. The app will automatically reload if you change any of the source files. Run `npm run start:dev` for a dev server. Navigate to `http://localhost:4200/`. The app will automatically reload if you change any of the source files.
## Code scaffolding ## Code scaffolding
@ -22,11 +22,11 @@ Run `ng generate module module-name --route module-name --module app.module` to
## Build ## Build
Run `ng build` to build the project. The build artifacts will be stored in the `dist/` directory. Use the `--prod` flag for a production build. Run `npm run build:dev` to build the project. The build artifacts will be stored in the `dist/` directory. Use the `build:prod` script for a production build.
## Running unit tests ## Running unit tests
Run `ng test` to execute the unit tests via [Karma](https://karma-runner.github.io). Run `npm run test:dev` to execute the unit tests via [Karma](https://karma-runner.github.io).
## Running end-to-end tests ## Running end-to-end tests
@ -34,8 +34,10 @@ Run `ng e2e` to execute the end-to-end tests via [Protractor](http://www.protrac
## Environment variables ## Environment variables
Environment variables are contained in the directory `src/environments/` Environment variables are contained in the `.env` file. See `.env.example` for a template.
Default environment variables are set in the `set-env.ts` file.
Once loaded they will be populated in the directory `src/environments/`.
It contains environment variables for development on `environment.ts` and production on `environment.prod.ts`. It contains environment variables for development on `environment.ts` and production on `environment.prod.ts`.
## Further help ## Further help

629
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@ -3,9 +3,14 @@
"version": "0.0.0", "version": "0.0.0",
"scripts": { "scripts": {
"ng": "ng", "ng": "ng",
"start": "ng serve", "config:dev": "ts-node set-env.ts --environment=dev",
"build": "ng build", "config:prod": "ts-node set-env.ts --environment=prod",
"test": "ng test", "start:dev": "npm run config:dev && ng serve",
"start:prod": "npm run config:prod && ng serve",
"build:dev": "npm run config:dev && ng build",
"build:prod": "npm run config:prod && ng build --prod",
"test:dev": "npm run config:dev && ng test",
"test:prod": "npm run config:prod && ng test",
"lint": "ng lint", "lint": "ng lint",
"e2e": "ng e2e", "e2e": "ng e2e",
"postinstall": "node patch-webpack.js" "postinstall": "node patch-webpack.js"
@ -55,8 +60,9 @@
"@types/jasmine": "~3.5.0", "@types/jasmine": "~3.5.0",
"@types/jasminewd2": "~2.0.3", "@types/jasminewd2": "~2.0.3",
"@types/jquery": "^3.5.4", "@types/jquery": "^3.5.4",
"@types/node": "^12.19.14", "@types/node": "^12.20.6",
"codelyzer": "^6.0.0", "codelyzer": "^6.0.0",
"dotenv": "^8.2.0",
"jasmine-core": "~3.6.0", "jasmine-core": "~3.6.0",
"jasmine-spec-reporter": "~5.0.0", "jasmine-spec-reporter": "~5.0.0",
"karma": "~5.0.0", "karma": "~5.0.0",
@ -69,6 +75,7 @@
"secp256k1": "^4.0.2", "secp256k1": "^4.0.2",
"ts-node": "~8.3.0", "ts-node": "~8.3.0",
"tslint": "~6.1.0", "tslint": "~6.1.0",
"typescript": "~4.0.2" "typescript": "~4.0.2",
"yargs": "^13.3.2"
} }
} }

51
set-env.ts Normal file
View File

@ -0,0 +1,51 @@
const { writeFile } = require('fs');
const { argv } = require('yargs');
const colors = require('colors');
require('dotenv').config();
const environment = argv.environment;
const isProduction = environment === 'prod';
const targetPath = isProduction ? `./src/environments/environment.prod.ts` : `./src/environments/environment.ts`;
const environmentVars = `import {NgxLoggerLevel} from 'ngx-logger';
export const environment = {
production: ${isProduction},
bloxbergChainId: ${process.env.CIC_CHAIN_ID || 8996},
level: ${process.env.LOG_LEVEL || 'NgxLoggerLevel.OFF'},
serverLogLevel: ${process.env.SERVER_LEVEL || 'NgxLoggerLevel.OFF'},
loggingUrl: '${process.env.CIC_LOGGING_URL || 'http://localhost:8000'}',
cicMetaUrl: '${process.env.CIC_META_URL || 'https://meta.dev.grassrootseconomics.net'}',
publicKeysUrl: '${process.env.CIC_KEYS_URL || 'http://localhost:8000/keys.asc'}',
cicCacheUrl: '${process.env.CIC_CACHE_URL || 'https://cache.dev.grassrootseconomics.net'}',
web3Provider: '${process.env.CIC_WEB3_PROVIDER || 'ws://localhost:63546'}',
cicUssdUrl: '${process.env.CIC_USSD_URL || 'https://ussd.dev.grassrootseconomics.net'}',
registryAddress: '${process.env.CIC_REGISTRY_ADDRESS || '0x6Ca3cB14aA6F761712E1C18646AfBA4d5Ae249E8'}',
trustedDeclaratorAddress: '${process.env.CIC_TRUSTED_ADDRESS || '0xEb3907eCad74a0013c259D5874AE7f22DcBcC95C'}'
};
`;
function setConfigs(configs): void {
writeFile(targetPath, configs, err => {
if (err) {
throw console.error(err);
} else {
console.log(colors.green(`Wrote variables to '${targetPath}`));
}
});
}
if (!process.env.CIC_REGISTRY_ADDRESS) {
console.error(colors.red('All the required environment variables were not provided!'));
process.exit(-1);
}
if (isProduction) {
console.log(colors.cyan('Running in production environment!'));
setConfigs(environmentVars);
} else {
console.log(colors.cyan('Running in development environment!'));
setConfigs(environmentVars);
}

View File

@ -1,4 +1,4 @@
import { Injectable } from '@angular/core'; import {Injectable, isDevMode} from '@angular/core';
import { import {
HttpRequest, HttpRequest,
HttpHandler, HttpHandler,
@ -16,10 +16,12 @@ export class ErrorInterceptor implements HttpInterceptor {
intercept(request: HttpRequest<unknown>, next: HttpHandler): Observable<HttpEvent<unknown>> { intercept(request: HttpRequest<unknown>, next: HttpHandler): Observable<HttpEvent<unknown>> {
return next.handle(request).pipe(catchError((err: HttpErrorResponse) => { return next.handle(request).pipe(catchError((err: HttpErrorResponse) => {
this.errorDialogService.openDialog({ if (isDevMode()) {
message: err.error.message || err.statusText, this.errorDialogService.openDialog({
status: err.status message: err.error.message || err.statusText || 'Unknown Error',
}); status: err.status || 0
});
}
if ([401, 403].indexOf(err.status) !== -1) { if ([401, 403].indexOf(err.status) !== -1) {
location.reload(true); location.reload(true);
} }

View File

@ -37,7 +37,7 @@ export class AuthService {
getWithToken(): void { getWithToken(): void {
const xhr = new XMLHttpRequest(); const xhr = new XMLHttpRequest();
xhr.responseType = 'text'; xhr.responseType = 'text';
xhr.open('GET', environment.cicAuthUrl + window.location.search.substring(1)); xhr.open('GET', environment.cicMetaUrl + window.location.search.substring(1));
xhr.setRequestHeader('Authorization', 'Bearer ' + this.sessionToken); xhr.setRequestHeader('Authorization', 'Bearer ' + this.sessionToken);
xhr.setRequestHeader('Content-Type', 'application/json'); xhr.setRequestHeader('Content-Type', 'application/json');
xhr.setRequestHeader('x-cic-automerge', 'none'); xhr.setRequestHeader('x-cic-automerge', 'none');
@ -55,7 +55,7 @@ export class AuthService {
sendResponse(hobaResponseEncoded): void { sendResponse(hobaResponseEncoded): void {
const xhr = new XMLHttpRequest(); const xhr = new XMLHttpRequest();
xhr.responseType = 'text'; xhr.responseType = 'text';
xhr.open('GET', environment.cicAuthUrl + window.location.search.substring(1)); xhr.open('GET', environment.cicMetaUrl + window.location.search.substring(1));
xhr.setRequestHeader('Authorization', 'HOBA ' + hobaResponseEncoded); xhr.setRequestHeader('Authorization', 'HOBA ' + hobaResponseEncoded);
xhr.setRequestHeader('Content-Type', 'application/json'); xhr.setRequestHeader('Content-Type', 'application/json');
xhr.setRequestHeader('x-cic-automerge', 'none'); xhr.setRequestHeader('x-cic-automerge', 'none');
@ -75,7 +75,7 @@ export class AuthService {
getChallenge(): void { getChallenge(): void {
const xhr = new XMLHttpRequest(); const xhr = new XMLHttpRequest();
xhr.responseType = 'arraybuffer'; xhr.responseType = 'arraybuffer';
xhr.open('GET', environment.cicAuthUrl + window.location.search.substring(1)); xhr.open('GET', environment.cicMetaUrl + window.location.search.substring(1));
xhr.onload = async (e) => { xhr.onload = async (e) => {
if (xhr.status === 401) { if (xhr.status === 401) {
const authHeader = xhr.getResponseHeader('WWW-Authenticate'); const authHeader = xhr.getResponseHeader('WWW-Authenticate');
@ -107,7 +107,7 @@ export class AuthService {
async loginResponse(o): Promise<any> { async loginResponse(o): Promise<any> {
const r = await signChallenge(o.challenge, o.realm, environment.cicAuthUrl, this.mutableKeyStore); const r = await signChallenge(o.challenge, o.realm, environment.cicMetaUrl, this.mutableKeyStore);
this.sendResponse(r); this.sendResponse(r);
} }

View File

@ -1,6 +1,5 @@
import {Injectable} from '@angular/core'; import {Injectable, isDevMode} from '@angular/core';
import {NGXLogger} from 'ngx-logger'; import {NGXLogger} from 'ngx-logger';
import {environment} from '@src/environments/environment';
@Injectable({ @Injectable({
providedIn: 'root' providedIn: 'root'
@ -11,9 +10,7 @@ export class LoggingService {
constructor(private logger: NGXLogger) { constructor(private logger: NGXLogger) {
// TRACE|DEBUG|INFO|LOG|WARN|ERROR|FATAL|OFF // TRACE|DEBUG|INFO|LOG|WARN|ERROR|FATAL|OFF
this.env = environment.production ? 'Production' : 'Development'; if (isDevMode()) {
if (this.env === 'Development') {
this.sendInfoLevelMessage('Dropping into debug mode'); this.sendInfoLevelMessage('Dropping into debug mode');
} }
} }

View File

@ -1,19 +1,3 @@
import {NgxLoggerLevel} from 'ngx-logger';
export const environment = { export const environment = {
production: true, production: true
bloxbergChainId: 8996,
level: NgxLoggerLevel.OFF,
serverLogLevel: NgxLoggerLevel.ERROR,
loggingUrl: 'http://localhost:8000',
cicAuthUrl: 'https://meta.dev.grassrootseconomics.net:80',
cicMetaUrl: 'http://localhost:63380',
publicKeysUrl: 'http://localhost:8000/keys.asc',
cicCacheUrl: 'http://localhost:63313',
cicScriptsUrl: 'http://localhost:9999',
web3Provider: 'ws://localhost:63546',
cicUssdUrl: 'http://localhost:63315',
cicEthUrl: 'http://localhost:63314',
registryAddress: '0x6Ca3cB14aA6F761712E1C18646AfBA4d5Ae249E8',
trustedDeclaratorAddress: '0xEb3907eCad74a0013c259D5874AE7f22DcBcC95C'
}; };

View File

@ -1,32 +1,3 @@
// This file can be replaced during build by using the `fileReplacements` array.
// `ng build --prod` replaces `environment.ts` with `environment.prod.ts`.
// The list of file replacements can be found in `angular.json`.
import {NgxLoggerLevel} from 'ngx-logger';
export const environment = { export const environment = {
production: false, production: false
bloxbergChainId: 8996,
level: NgxLoggerLevel.TRACE,
serverLogLevel: NgxLoggerLevel.ERROR,
loggingUrl: 'http://localhost:8000',
cicAuthUrl: 'https://meta.dev.grassrootseconomics.net:80',
cicMetaUrl: 'http://localhost:63380',
publicKeysUrl: 'http://localhost:8000/keys.asc',
cicCacheUrl: 'http://localhost:63313',
cicScriptsUrl: 'http://localhost:9999',
web3Provider: 'ws://localhost:63546',
cicUssdUrl: 'http://localhost:63315',
cicEthUrl: 'http://localhost:63314',
registryAddress: '0x6Ca3cB14aA6F761712E1C18646AfBA4d5Ae249E8',
trustedDeclaratorAddress: '0xEb3907eCad74a0013c259D5874AE7f22DcBcC95C'
}; };
/*
* For easier debugging in development mode, you can import the following file
* to ignore zone related error stack frames such as `zone.run`, `zoneDelegate.invokeTask`.
*
* This import should be commented out in production mode because it will have a negative impact
* on performance if an error is thrown.
*/
// import 'zone.js/dist/zone-error'; // Included with Angular CLI.