Commit 66b4166e authored by Dhiraj Shrivastava's avatar Dhiraj Shrivastava
Browse files

First commit

parents
# Editor configuration, see https://editorconfig.org
root = true
[*]
charset = utf-8
indent_style = space
indent_size = 2
insert_final_newline = true
trim_trailing_whitespace = true
[*.md]
max_line_length = off
trim_trailing_whitespace = false
# See http://help.github.com/ignore-files/ for more about ignoring files.
# compiled output
/dist
/tmp
/out-tsc
# Only exists if Bazel was run
/bazel-out
# dependencies
/node_modules
# profiling files
chrome-profiler-events.json
speed-measure-plugin.json
# IDEs and editors
/.idea
.project
.classpath
.c9/
*.launch
.settings/
*.sublime-workspace
# IDE - VSCode
.vscode/*
!.vscode/settings.json
!.vscode/tasks.json
!.vscode/launch.json
!.vscode/extensions.json
.history/*
# misc
/.sass-cache
/connect.lock
/coverage
/libpeerconnection.log
npm-debug.log
yarn-error.log
testem.log
/typings
# System Files
.DS_Store
Thumbs.db
FROM node as node
WORKDIR /usr/src/app
COPY package.json ./
RUN npm install --no-cache git
RUN npm install
COPY . .
RUN npm run build
FROM twalter/openshift-nginx:stable
COPY --from=node /usr/src/app/dist /usr/share/nginx/html
\ No newline at end of file
# POC1
This project was generated with [Angular CLI](https://github.com/angular/angular-cli) version 7.3.2.
## 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.
## Code scaffolding
Run `ng generate component component-name` to generate a new component. You can also use `ng generate directive|pipe|service|class|guard|interface|enum|module`.
## 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.
## Running unit tests
Run `ng test` to execute the unit tests via [Karma](https://karma-runner.github.io).
## Running end-to-end tests
Run `ng e2e` to execute the end-to-end tests via [Protractor](http://www.protractortest.org/).
## Further help
To get more help on the Angular CLI use `ng help` or go check out the [Angular CLI README](https://github.com/angular/angular-cli/blob/master/README.md).
{
"$schema": "./node_modules/@angular/cli/lib/config/schema.json",
"version": 1,
"newProjectRoot": "projects",
"projects": {
"POC1": {
"root": "",
"sourceRoot": "src",
"projectType": "application",
"prefix": "app",
"schematics": {
"@schematics/angular:component": {
"style": "sass"
}
},
"architect": {
"build": {
"builder": "@angular-devkit/build-angular:browser",
"options": {
"outputPath": "dist/POC1",
"index": "src/index.html",
"main": "src/main.ts",
"polyfills": "src/polyfills.ts",
"tsConfig": "src/tsconfig.app.json",
"assets": [
"src/favicon.ico",
"src/assets"
],
"styles": [
"src/styles.scss"
],
"scripts": [],
"es5BrowserSupport": true
},
"configurations": {
"production": {
"fileReplacements": [
{
"replace": "src/environments/environment.ts",
"with": "src/environments/environment.prod.ts"
}
],
"optimization": true,
"outputHashing": "all",
"sourceMap": false,
"extractCss": true,
"namedChunks": false,
"aot": true,
"extractLicenses": true,
"vendorChunk": false,
"buildOptimizer": true,
"budgets": [
{
"type": "initial",
"maximumWarning": "2mb",
"maximumError": "5mb"
}
]
}
}
},
"serve": {
"builder": "@angular-devkit/build-angular:dev-server",
"options": {
"browserTarget": "POC1:build"
},
"configurations": {
"production": {
"browserTarget": "POC1:build:production"
}
}
},
"extract-i18n": {
"builder": "@angular-devkit/build-angular:extract-i18n",
"options": {
"browserTarget": "POC1:build"
}
},
"test": {
"builder": "@angular-devkit/build-angular:karma",
"options": {
"main": "src/test.ts",
"polyfills": "src/polyfills.ts",
"tsConfig": "src/tsconfig.spec.json",
"karmaConfig": "src/karma.conf.js",
"styles": [
"src/styles.scss"
],
"scripts": [],
"assets": [
"src/favicon.ico",
"src/assets"
]
}
},
"lint": {
"builder": "@angular-devkit/build-angular:tslint",
"options": {
"tsConfig": [
"src/tsconfig.app.json",
"src/tsconfig.spec.json"
],
"exclude": [
"**/node_modules/**"
]
}
}
}
},
"POC1-e2e": {
"root": "e2e/",
"projectType": "application",
"prefix": "",
"architect": {
"e2e": {
"builder": "@angular-devkit/build-angular:protractor",
"options": {
"protractorConfig": "e2e/protractor.conf.js",
"devServerTarget": "POC1:serve"
},
"configurations": {
"production": {
"devServerTarget": "POC1:serve:production"
}
}
},
"lint": {
"builder": "@angular-devkit/build-angular:tslint",
"options": {
"tsConfig": "e2e/tsconfig.e2e.json",
"exclude": [
"**/node_modules/**"
]
}
}
}
}
},
"defaultProject": "POC1"
}
\ No newline at end of file
// Protractor configuration file, see link for more information
// https://github.com/angular/protractor/blob/master/lib/config.ts
const { SpecReporter } = require('jasmine-spec-reporter');
exports.config = {
allScriptsTimeout: 11000,
specs: [
'./src/**/*.e2e-spec.ts'
],
capabilities: {
'browserName': 'chrome'
},
directConnect: true,
baseUrl: 'http://localhost:4200/',
framework: 'jasmine',
jasmineNodeOpts: {
showColors: true,
defaultTimeoutInterval: 30000,
print: function() {}
},
onPrepare() {
require('ts-node').register({
project: require('path').join(__dirname, './tsconfig.e2e.json')
});
jasmine.getEnv().addReporter(new SpecReporter({ spec: { displayStacktrace: true } }));
}
};
\ No newline at end of file
import { AppPage } from './app.po';
import { browser, logging } from 'protractor';
describe('workspace-project App', () => {
let page: AppPage;
beforeEach(() => {
page = new AppPage();
});
it('should display welcome message', () => {
page.navigateTo();
expect(page.getTitleText()).toEqual('Welcome to POC1!');
});
afterEach(async () => {
// Assert that there are no errors emitted from the browser
const logs = await browser.manage().logs().get(logging.Type.BROWSER);
expect(logs).not.toContain(jasmine.objectContaining({
level: logging.Level.SEVERE,
} as logging.Entry));
});
});
import { browser, by, element } from 'protractor';
export class AppPage {
navigateTo() {
return browser.get(browser.baseUrl) as Promise<any>;
}
getTitleText() {
return element(by.css('app-root h1')).getText() as Promise<string>;
}
}
{
"extends": "../tsconfig.json",
"compilerOptions": {
"outDir": "../out-tsc/app",
"module": "commonjs",
"target": "es5",
"types": [
"jasmine",
"jasminewd2",
"node"
]
}
}
\ No newline at end of file
This diff is collapsed.
<div style="margin-top: 10px;;" *ngIf="message"
[ngClass]="{ 'alert': message, 'alert-success': message.type === 'success',
'alert-danger': message.type === 'error' }">
{{message.text}}</div>
\ No newline at end of file
import { Component, OnInit, OnDestroy } from '@angular/core';
import { Subscription } from 'rxjs';
import { AlertService } from '../_services';
@Component({
selector: 'alert',
templateUrl: 'alert.component.html'
})
export class AlertComponent implements OnInit, OnDestroy {
private subscription: Subscription;
message: any;
constructor(private alertService: AlertService) { }
ngOnInit() {
this.subscription = this.alertService.getMessage().subscribe(message => {
this.message = message;
});
}
ngOnDestroy() {
this.subscription.unsubscribe();
}
}
\ No newline at end of file
export * from './alert.component';
\ No newline at end of file
import { Injectable } from '@angular/core';
import { Router, CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';
import { AuthenticationService } from '../_services';
@Injectable({ providedIn: 'root' })
export class AuthGuard implements CanActivate {
constructor(
private router: Router,
private authenticationService: AuthenticationService
) {}
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
const currentUser = this.authenticationService.currentUserValue;
// const current_admin =this.authenticationService.currentAdminvalue;
if (currentUser || currentUser.Fqtv === 'admin') {
// authorised so return true
return true;
}
// if(current_admin){
// return true;
// }
// not logged in so redirect to login page with the return url
this.router.navigate(['/login'], { queryParams: { returnUrl: state.url }});
return false;
}
}
\ No newline at end of file
export * from './auth.guard';
\ No newline at end of file
import { Injectable } from '@angular/core';
import { HttpRequest, HttpHandler, HttpEvent, HttpInterceptor } from '@angular/common/http';
import { Observable, throwError } from 'rxjs';
import { catchError } from 'rxjs/operators';
import { AuthenticationService } from '../_services';
@Injectable()
export class ErrorInterceptor implements HttpInterceptor {
constructor(private authenticationService: AuthenticationService) {}
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
return next.handle(request).pipe(catchError(err => {
if (err.status === 401) {
// auto logout if 401 response returned from api
this.authenticationService.logout();
location.reload(true);
}
const error = err.error.message || err.statusText;
return throwError(error);
}))
}
}
\ No newline at end of file
import { Injectable } from '@angular/core';
import { HttpRequest, HttpResponse, HttpHandler, HttpEvent, HttpInterceptor, HTTP_INTERCEPTORS } from '@angular/common/http';
import { Observable, of, throwError } from 'rxjs';
import { delay, mergeMap, materialize, dematerialize } from 'rxjs/operators';
@Injectable()
export class FakeBackendInterceptor implements HttpInterceptor {
constructor() { }
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
// array in local storage for registered users
let users: any[] = JSON.parse(localStorage.getItem('users')) || [];
// wrap in delayed observable to simulate server api call
return of(null).pipe(mergeMap(() => {
// authenticate
if (request.url.endsWith('/users/authenticate') && request.method === 'POST') {
// find if any user matches login credentials
let filteredUsers = users.filter(user => {
return user.username === request.body.username && user.passcode === request.body.password;
});
if (filteredUsers.length) {
// if login details are valid return 200 OK with user details and fake jwt token
let user = filteredUsers[0];
let body = {
firstName: user.firstName,
phone: user.phone,
lastemailName: user.email,
dob: user.dob,
doa: user.doa,
password:user.password
};
return of(new HttpResponse({ status: 200, body: body }));
} else {
// else return 400 bad request
return throwError({ error: { message: 'Username or password is incorrect' } });
}
}
// get users
if (request.url.endsWith('/users') && request.method === 'GET') {
// check for fake auth token in header and return users if valid, this security is implemented server side in a real application
if (request.headers.get('Authorization') === 'Bearer fake-jwt-token') {
return of(new HttpResponse({ status: 200, body: users }));
} else {
// return 401 not authorised if token is null or invalid
return throwError({ status: 401, error: { message: 'Unauthorised' } });
}
}
// get user by id
if (request.url.match(/\/users\/\d+$/) && request.method === 'GET') {
// check for fake auth token in header and return user if valid, this security is implemented server side in a real application
if (request.headers.get('Authorization') === 'Bearer fake-jwt-token') {
// find user by id in users array
let urlParts = request.url.split('/');
let id = parseInt(urlParts[urlParts.length - 1]);
let matchedUsers = users.filter(user => { return user.id === id; });
let user = matchedUsers.length ? matchedUsers[0] : null;
return of(new HttpResponse({ status: 200, body: user }));
} else {
// return 401 not authorised if token is null or invalid
return throwError({ status: 401, error: { message: 'Unauthorised' } });
}
}
// register user
if (request.url.endsWith('/users/register') && request.method === 'POST') {
// get new user object from post body
let newUser = request.body;
// validation
let duplicateUser = users.filter(user => { return user.username === newUser.username; }).length;
if (duplicateUser) {
return throwError({ error: { message: 'Username "' + newUser.username + '" is already taken' } });
}
// save new user
newUser.id = users.length + 1;
users.push(newUser);
localStorage.setItem('users', JSON.stringify(users));
// respond 200 OK
return of(new HttpResponse({ status: 200 }));
}
// delete user
if (request.url.match(/\/users\/\d+$/) && request.method === 'DELETE') {
// check for fake auth token in header and return user if valid, this security is implemented server side in a real application
if (request.headers.get('Authorization') === 'Bearer fake-jwt-token') {
// find user by id in users array
let urlParts = request.url.split('/');
let id = parseInt(urlParts[urlParts.length - 1]);
for (let i = 0; i < users.length; i++) {
let user = users[i];
if (user.id === id) {
// delete user
users.splice(i, 1);
localStorage.setItem('users', JSON.stringify(users));
break;
}
}
// respond 200 OK
return of(new HttpResponse({ status: 200 }));
} else {
// return 401 not authorised if token is null or invalid
return throwError({ status: 401, error: { message: 'Unauthorised' } });
}
}
// pass through any requests not handled above
return next.handle(request);
}))
// call materialize and dematerialize to ensure delay event if an error is thrown (https://github.com/Reactive-Extensions/RxJS/issues/648)
.pipe(materialize())
.pipe(delay(500))
.pipe(dematerialize());
}
}
export let fakeBackendProvider = {
// use fake backend in place of Http service for backend-less development
provide: HTTP_INTERCEPTORS,