more login work

This commit is contained in:
2018-05-01 08:20:56 -04:00
parent 8884d1df83
commit cd10c7aaad
22 changed files with 403 additions and 2775 deletions

View File

@@ -0,0 +1,17 @@
<?php
define('dbhost', 'localhost');
define('dbuser', 'lazyp_workadmin');
define('dbpass', 'GH5fZF0iCtLnHLrz');
define('dbname', 'LudosData');
try {
$connect = new PDO("mysql:host=".dbhost."; dbname=".dbname, dbuser, dbpass);
$connect->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e) {
echo $e->getMessage();
}
?>

File diff suppressed because it is too large Load Diff

View File

@@ -1513,7 +1513,7 @@ class PHP_CRUD_API {
$passwordSalt = "2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824";
$hashedPassword = crypt( $password, $passwordSalt );
$hashedPassword = crypt( $input['password'], $passwordSalt );
$hashedId = crypt( $id, $passwordSalt );
$input['password'] = $hashedPassword;

View File

@@ -0,0 +1 @@
<div *ngIf="message" [ngClass]="{ 'alert': message, 'alert-success': message.type === 'success', 'alert-danger': message.type === 'error' }">{{message.text}}</div>

View File

@@ -0,0 +1,25 @@
import { Component, OnDestroy } from '@angular/core';
import { Subscription } from 'rxjs/Subscription';
import { AlertService } from '../_services/index';
@Component({
moduleId: module.id,
selector: 'alert',
templateUrl: 'alert.component.html'
})
export class AlertComponent implements OnDestroy {
private subscription: Subscription;
message: any;
constructor(private alertService: AlertService) {
// subscribe to alert messages
this.subscription = alertService.getMessage().subscribe(message => { this.message = message; });
}
ngOnDestroy(): void {
// unsubscribe on destroy to prevent memory leaks
this.subscription.unsubscribe();
}
}

View File

@@ -0,0 +1 @@
export * from './alert.component';

View File

@@ -0,0 +1,19 @@
import { Injectable } from '@angular/core';
import { Router, CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';
@Injectable()
export class AuthGuard implements CanActivate {
constructor(private router: Router) { }
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
if (localStorage.getItem('currentUser')) {
// logged in 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;
}
}

1
src/app/_guards/index.ts Normal file
View File

@@ -0,0 +1 @@
export * from './auth.guard';

View File

@@ -0,0 +1,138 @@
import { Injectable } from '@angular/core';
import { HttpRequest, HttpResponse, HttpHandler, HttpEvent, HttpInterceptor, HTTP_INTERCEPTORS } from '@angular/common/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/observable/of';
import 'rxjs/add/observable/throw';
import 'rxjs/add/operator/delay';
import 'rxjs/add/operator/mergeMap';
import 'rxjs/add/operator/materialize';
import 'rxjs/add/operator/dematerialize';
@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 Observable.of(null).mergeMap(() => {
// authenticate
if (request.url.endsWith('/api/authenticate') && request.method === 'POST') {
// find if any user matches login credentials
let filteredUsers = users.filter(user => {
return user.username === request.body.username && user.password === 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 = {
id: user.id,
username: user.username,
firstName: user.firstName,
lastName: user.lastName,
token: 'fake-jwt-token'
};
return Observable.of(new HttpResponse({ status: 200, body: body }));
} else {
// else return 400 bad request
return Observable.throw('Username or password is incorrect');
}
}
// get users
if (request.url.endsWith('/api/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 Observable.of(new HttpResponse({ status: 200, body: users }));
} else {
// return 401 not authorised if token is null or invalid
return Observable.throw('Unauthorised');
}
}
// get user by id
if (request.url.match(/\/api\/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 Observable.of(new HttpResponse({ status: 200, body: user }));
} else {
// return 401 not authorised if token is null or invalid
return Observable.throw('Unauthorised');
}
}
// create user
if (request.url.endsWith('/api/users') && 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 Observable.throw('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 Observable.of(new HttpResponse({ status: 200 }));
}
// delete user
if (request.url.match(/\/api\/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 Observable.of(new HttpResponse({ status: 200 }));
} else {
// return 401 not authorised if token is null or invalid
return Observable.throw('Unauthorised');
}
}
// pass through any requests not handled above
return next.handle(request);
})
// call materialize and dematerialize to ensure delay even if an error is thrown (https://github.com/Reactive-Extensions/RxJS/issues/648)
.materialize()
.delay(500)
.dematerialize();
}
}
export let fakeBackendProvider = {
// use fake backend in place of Http service for backend-less development
provide: HTTP_INTERCEPTORS,
useClass: FakeBackendInterceptor,
multi: true
};

View File

@@ -0,0 +1,2 @@
export * from './jwt.interceptor';
export * from './fake-backend';

View File

@@ -0,0 +1,20 @@
import { Injectable } from '@angular/core';
import { HttpRequest, HttpHandler, HttpEvent, HttpInterceptor } from '@angular/common/http';
import { Observable } from 'rxjs/Observable';
@Injectable()
export class JwtInterceptor implements HttpInterceptor {
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
// add authorization header with jwt token if available
let currentUser = JSON.parse(localStorage.getItem('currentUser'));
if (currentUser && currentUser.token) {
request = request.clone({
setHeaders: {
Authorization: `Bearer ${currentUser.token}`
}
});
}
return next.handle(request);
}
}

1
src/app/_models/index.ts Normal file
View File

@@ -0,0 +1 @@
export * from './user';

7
src/app/_models/user.ts Normal file
View File

@@ -0,0 +1,7 @@
export class User {
id: number;
username: string;
password: string;
firstName: string;
lastName: string;
}

View File

@@ -0,0 +1,39 @@
import { Injectable } from '@angular/core';
import { Router, NavigationStart } from '@angular/router';
import { Observable } from 'rxjs';
import { Subject } from 'rxjs/Subject';
@Injectable()
export class AlertService {
private subject = new Subject<any>();
private keepAfterNavigationChange = false;
constructor(private router: Router) {
// clear alert message on route change
router.events.subscribe(event => {
if (event instanceof NavigationStart) {
if (this.keepAfterNavigationChange) {
// only keep for a single location change
this.keepAfterNavigationChange = false;
} else {
// clear alert
this.subject.next();
}
}
});
}
success(message: string, keepAfterNavigationChange = false) {
this.keepAfterNavigationChange = keepAfterNavigationChange;
this.subject.next({ type: 'success', text: message });
}
error(message: string, keepAfterNavigationChange = false) {
this.keepAfterNavigationChange = keepAfterNavigationChange;
this.subject.next({ type: 'error', text: message });
}
getMessage(): Observable<any> {
return this.subject.asObservable();
}
}

View File

@@ -0,0 +1,27 @@
import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map'
@Injectable()
export class AuthenticationService {
constructor(private http: HttpClient) { }
login(username: string, password: string) {
return this.http.post<any>('/api/authenticate', { username: username, password: password })
.map(user => {
// login successful if there's a jwt token in the response
if (user && user.token) {
// store user details and jwt token in local storage to keep user logged in between page refreshes
localStorage.setItem('currentUser', JSON.stringify(user));
}
return user;
});
}
logout() {
// remove user from local storage to log user out
localStorage.removeItem('currentUser');
}
}

View File

@@ -0,0 +1,3 @@
export * from './alert.service';
export * from './authentication.service';
export * from './user.service';

View File

@@ -0,0 +1,29 @@
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { User } from '../_models/index';
@Injectable()
export class UserService {
constructor(private http: HttpClient) { }
getAll() {
return this.http.get<User[]>('/api/users');
}
getById(id: number) {
return this.http.get('/api/users/' + id);
}
create(user: User) {
return this.http.post('/api/users', user);
}
update(user: User) {
return this.http.put('/api/users/' + user.id, user);
}
delete(id: number) {
return this.http.delete('/api/users/' + id);
}
}

View File

@@ -1 +1,2 @@
<alert></alert>
<router-outlet></router-outlet>

View File

@@ -1,6 +1,6 @@
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import {HttpClientModule} from '@angular/common/http';
import {HttpClientModule, HTTP_INTERCEPTORS } from '@angular/common/http';
import { ReactiveFormsModule } from '@angular/forms';
import { GamesService } from './games.service';
@@ -29,6 +29,14 @@ import { RegistrationService } from './registration.service';
import { UsernameValidator } from './validators/username.validator'
import { EmailValidator } from './validators/email.validator'
// used to create fake backend
import { fakeBackendProvider } from './_helpers/index';
import { AlertComponent } from './_directives/index';
import { AuthGuard } from './_guards/index';
import { JwtInterceptor } from './_helpers/index';
import { AlertService, AuthenticationService, UserService } from './_services/index';
@NgModule({
@@ -37,7 +45,8 @@ import { EmailValidator } from './validators/email.validator'
GameGridComponent,
ViewCardComponent,
LoginComponent,
RegisterComponent
RegisterComponent,
AlertComponent,
],
imports: [
BrowserModule,
@@ -54,7 +63,25 @@ import { EmailValidator } from './validators/email.validator'
MatPaginatorModule,
MatFormFieldModule
],
providers: [GamesService, RegistrationService, UsernameValidator, EmailValidator],
providers: [
GamesService,
RegistrationService,
UsernameValidator,
EmailValidator,
AuthGuard,
AlertService,
AuthenticationService,
UserService,
{
provide: HTTP_INTERCEPTORS,
useClass: JwtInterceptor,
multi: true
},
// provider used to create fake backend
fakeBackendProvider
],
bootstrap: [AppComponent]
})
export class AppModule { }

View File

@@ -1,4 +1,4 @@
<form novalidate (ngSubmit)="onSubmit(form.value)" [formGroup]="form" >
<form novalidate (ngSubmit)="login(form.value)" [formGroup]="form" >
<div class="lrContainer">
<mat-card class="lrCard">

View File

@@ -3,6 +3,8 @@ import { ActivatedRoute, Router } from '@angular/router';
import { FormBuilder, FormGroup, FormControl, Validators } from '@angular/forms';
import { RegistrationService } from '../registration.service';
import { AlertService, AuthenticationService } from '../_services/index';
@Component({
selector: 'app-login',
@@ -12,21 +14,28 @@ import { RegistrationService } from '../registration.service';
export class LoginComponent implements OnInit {
form: any;
model: any = {};
loading = false;
returnUrl: string;
constructor(
private route: ActivatedRoute,
private router: Router,
private registrationService: RegistrationService
private registrationService: RegistrationService,
private authenticationService: AuthenticationService,
private alertService: AlertService
) { }
ngOnInit() {
// reset login status
//this.authenticationService.logout();
this.authenticationService.logout();
// get return url from route parameters or default to '/'
//this.returnUrl = this.route.snapshot.queryParams['returnUrl'] || '/';
this.returnUrl = this.route.snapshot.queryParams['returnUrl'] || '/';
this.buildForm();
}
@@ -68,8 +77,7 @@ export class LoginComponent implements OnInit {
}
login() {
/*
this.loading = true;
this.loading = true;
this.authenticationService.login(this.model.username, this.model.password)
.subscribe(
data => {
@@ -79,7 +87,6 @@ export class LoginComponent implements OnInit {
this.alertService.error(error);
this.loading = false;
});
*/
}
}

View File

@@ -13,7 +13,7 @@ export class RegistrationService {
APIURL = "http://192.241.155.78/api.php";
registrationUrl = "http://192.241.155.78/interfaceServices/registrationInterface.php/users/";
login Url = "http://192.241.155.78/interfaceServices/loginInterface.php/users/";
loginUrl = "http://192.241.155.78/interfaceServices/loginInterface.php";
params;
constructor(
@@ -58,7 +58,7 @@ export class RegistrationService {
fromObject: userData
});
return this.http.get( this.loginUrl, this.params, httpOptions )
return this.http.post( this.loginUrl, this.params, httpOptions )
.map(res => {
return(
res