Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
41 changes: 41 additions & 0 deletions frontend/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
# Logs
logs
*.log
npm-debug.log*

# Runtime data
pids
*.pid
*.seed

# Directory for instrumented libs generated by jscoverage/JSCover
lib-cov

# Coverage directory used by tools like istanbul
coverage

# nyc test coverage
.nyc_output

# Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files)
.grunt

# node-waf configuration
.lock-wscript

# Compiled binary addons (http://nodejs.org/api/addons.html)
build/Release

# Dependency directories
node_modules
jspm_packages
typings

# Optional npm cache directory
.npm

# Optional REPL history
.node_repl_history

# Generated files
dist
21 changes: 21 additions & 0 deletions frontend/LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
The MIT License (MIT)

Copyright (c) 2019 Jason Watmore

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
5 changes: 5 additions & 0 deletions frontend/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
# angular-8-registration-login-example

Angular 8 User Registration and Login Example with Webpack 4

Full tutorial with example available at https://jasonwatmore.com/post/2019/06/10/angular-8-user-registration-and-login-example-tutorial
8,003 changes: 8,003 additions & 0 deletions frontend/package-lock.json

Large diffs are not rendered by default.

40 changes: 40 additions & 0 deletions frontend/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
{
"name": "angular-8-registration-login-example",
"version": "1.0.0",
"repository": {
"type": "git",
"url": "https://github.com/cornflourblue/angular-8-registration-login-example.git"
},
"scripts": {
"build": "webpack --mode production",
"start": "webpack-dev-server --mode development --open"
},
"license": "MIT",
"dependencies": {
"@angular/common": "^8.0.0",
"@angular/compiler": "^8.0.0",
"@angular/core": "^8.0.0",
"@angular/forms": "^8.0.0",
"@angular/platform-browser": "^8.0.0",
"@angular/platform-browser-dynamic": "^8.0.0",
"@angular/router": "^8.0.0",
"core-js": "^3.1.3",
"rxjs": "^6.3.3",
"zone.js": "^0.9.1"
},
"devDependencies": {
"@types/node": "^12.0.7",
"angular2-template-loader": "^0.6.2",
"css-loader": "^2.1.1",
"html-loader": "^0.5.5",
"html-webpack-plugin": "^3.2.0",
"less": "^3.0.4",
"less-loader": "^5.0.0",
"style-loader": "^0.23.1",
"ts-loader": "^6.0.1",
"typescript": "^3.1.3",
"webpack": "^4.32.2",
"webpack-cli": "^3.1.2",
"webpack-dev-server": "^3.7.0"
}
}
1 change: 1 addition & 0 deletions frontend/src/app/_components/alert.component.html
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
<div *ngIf="message" [ngClass]="message.cssClass">{{message.text}}</div>
32 changes: 32 additions & 0 deletions frontend/src/app/_components/alert.component.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
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.getAlert()
.subscribe(message => {
switch (message && message.type) {
case 'success':
message.cssClass = 'alert alert-success';
break;
case 'error':
message.cssClass = 'alert alert-danger';
break;
}

this.message = message;
});
}

ngOnDestroy() {
this.subscription.unsubscribe();
}
}
1 change: 1 addition & 0 deletions frontend/src/app/_components/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export * from './alert.component';
4 changes: 4 additions & 0 deletions frontend/src/app/_content/app.less
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
// global application styles
a {
cursor: pointer;
}
24 changes: 24 additions & 0 deletions frontend/src/app/_helpers/auth.guard.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
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;
if (currentUser) {
// authorised so return true
return true;
}

// not logged in so redirect to login page with the return url
this.router.navigate(['/login'], { queryParams: { returnUrl: state.url }});
return false;
}
}
24 changes: 24 additions & 0 deletions frontend/src/app/_helpers/error.interceptor.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
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);
}))
}
}
109 changes: 109 additions & 0 deletions frontend/src/app/_helpers/fake-backend.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,109 @@
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';

// array in local storage for registered users
let users = JSON.parse(localStorage.getItem('users')) || [];

@Injectable()
export class FakeBackendInterceptor implements HttpInterceptor {
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
const { url, method, headers, body } = request;

// wrap in delayed observable to simulate server api call
return of(null)
.pipe(mergeMap(handleRoute))
.pipe(materialize()) // call materialize and dematerialize to ensure delay even if an error is thrown (https://github.com/Reactive-Extensions/RxJS/issues/648)
.pipe(delay(500))
.pipe(dematerialize());

function handleRoute() {
switch (true) {
case url.endsWith('/users/authenticate') && method === 'POST':
return authenticate();
case url.endsWith('/users/register') && method === 'POST':
return register();
case url.endsWith('/users') && method === 'GET':
return getUsers();
case url.match(/\/users\/\d+$/) && method === 'DELETE':
return deleteUser();
default:
// pass through any requests not handled above
return next.handle(request);
}
}

// route functions

function authenticate() {
const { username, password } = body;
const user = users.find(x => x.username === username && x.password === password);
if (!user) return error('Username or password is incorrect');
return ok({
id: user.id,
username: user.username,
firstName: user.firstName,
lastName: user.lastName,
token: 'fake-jwt-token'
})
}

function register() {
const user = body

if (users.find(x => x.username === user.username)) {
return error('Username "' + user.username + '" is already taken')
}

user.id = users.length ? Math.max(...users.map(x => x.id)) + 1 : 1;
users.push(user);
localStorage.setItem('users', JSON.stringify(users));

return ok();
}

function getUsers() {
if (!isLoggedIn()) return unauthorized();
return ok(users);
}

function deleteUser() {
if (!isLoggedIn()) return unauthorized();

users = users.filter(x => x.id !== idFromUrl());
localStorage.setItem('users', JSON.stringify(users));
return ok();
}

// helper functions

function ok(body?) {
return of(new HttpResponse({ status: 200, body }))
}

function error(message) {
return throwError({ error: { message } });
}

function unauthorized() {
return throwError({ status: 401, error: { message: 'Unauthorised' } });
}

function isLoggedIn() {
return headers.get('Authorization') === 'Bearer fake-jwt-token';
}

function idFromUrl() {
const urlParts = url.split('/');
return parseInt(urlParts[urlParts.length - 1]);
}
}
}

export const fakeBackendProvider = {
// use fake backend in place of Http service for backend-less development
provide: HTTP_INTERCEPTORS,
useClass: FakeBackendInterceptor,
multi: true
};
4 changes: 4 additions & 0 deletions frontend/src/app/_helpers/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
export * from './auth.guard';
export * from './error.interceptor';
export * from './jwt.interceptor';
export * from './fake-backend';
24 changes: 24 additions & 0 deletions frontend/src/app/_helpers/jwt.interceptor.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
import { Injectable } from '@angular/core';
import { HttpRequest, HttpHandler, HttpEvent, HttpInterceptor } from '@angular/common/http';
import { Observable } from 'rxjs';

import { AuthenticationService } from '@/_services';

@Injectable()
export class JwtInterceptor implements HttpInterceptor {
constructor(private authenticationService: AuthenticationService) {}

intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
// add authorization header with jwt token if available
let currentUser = this.authenticationService.currentUserValue;
if (currentUser && currentUser.token) {
request = request.clone({
setHeaders: {
Authorization: `Bearer ${currentUser.token}`
}
});
}

return next.handle(request);
}
}
1 change: 1 addition & 0 deletions frontend/src/app/_models/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export * from './user';
8 changes: 8 additions & 0 deletions frontend/src/app/_models/user.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
export class User {
id: number;
username: string;
password: string;
firstName: string;
lastName: string;
token: string;
}
Loading