Working as a drop-in replacement for the last

This commit is contained in:
tanshu
2020-05-11 23:45:52 +05:30
parent 37b4faabf4
commit ae8c46084c
5 changed files with 117 additions and 112 deletions

View File

@ -1,41 +1,33 @@
import {Injectable} from '@angular/core'; import {Injectable} from '@angular/core';
import {ActivatedRouteSnapshot, CanActivate, Router, RouterStateSnapshot} from '@angular/router'; import {Router, CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot} from '@angular/router';
import {AuthService} from './auth.service'; import {AuthService} from './auth.service';
import {Observable} from 'rxjs/internal/Observable';
import {map} from 'rxjs/operators';
import {ToasterService} from '../core/toaster.service'; import {ToasterService} from '../core/toaster.service';
import {User} from '../core/user';
@Injectable({ @Injectable({providedIn: 'root'})
providedIn: 'root'
})
export class AuthGuard implements CanActivate { export class AuthGuard implements CanActivate {
constructor(
constructor(private auth: AuthService, private router: Router, private toaster: ToasterService) { private router: Router,
private authService: AuthService,
private toaster: ToasterService
) {
} }
static checkUser(permission: string, user: User, router: Router, state: RouterStateSnapshot, toaster: ToasterService): boolean { canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
if (!user.isAuthenticated) { const user = this.authService.user;
router.navigate(['login'], {queryParams: {returnUrl: state.url}}); const permission = route.data['permission'].replace(/ /g, '-').toLowerCase();
toaster.show('Danger', 'User is not authenticated'); if (!user) {
// not logged in so redirect to login page with the return url
this.router.navigate(['/login'], {queryParams: {returnUrl: state.url}});
return false; return false;
} }
const hasPermission = permission === undefined || user.perms.indexOf(permission) !== -1; console.log(permission, user.perms.indexOf(permission));
if (!hasPermission) { if (permission !== undefined && user.perms.indexOf(permission) === -1) {
toaster.show('Danger', 'You do not have the permission to access this area.'); this.toaster.show('Danger', 'You do not have the permission to access this area.');
return false;
} }
return hasPermission; // logged in so return true
} return true;
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> | boolean {
if (this.auth.user === undefined) {
return this.auth.userObservable
.pipe(
map<User, boolean>((value: User) => AuthGuard.checkUser(
route.data['permission'], value, this.router, state, this.toaster
))
);
}
return AuthGuard.checkUser(route.data['permission'], this.auth.user, this.router, state, this.toaster);
} }
} }

View File

@ -1,72 +1,63 @@
import {Injectable} from '@angular/core'; import {Injectable} from '@angular/core';
import {HttpClient, HttpHeaders} from '@angular/common/http'; import {HttpClient} from '@angular/common/http';
import {Observable} from 'rxjs/internal/Observable'; import {BehaviorSubject, Observable} from 'rxjs';
import {catchError, tap} from 'rxjs/operators'; import {map} from 'rxjs/operators';
import {Subject} from 'rxjs/internal/Subject';
import {ErrorLoggerService} from '../core/error-logger.service';
import {User} from '../core/user'; import {User} from '../core/user';
const loginUrl = '/token';
const httpOptions = { @Injectable({providedIn: 'root'})
headers: new HttpHeaders({'Content-Type': 'application/json'})
};
const loginUrl = '/api/login';
const logoutUrl = '/api/logout';
const checkUrl = '/api/auth';
@Injectable({
providedIn: 'root'
})
export class AuthService { export class AuthService {
public userObservable = new Subject<User>(); private currentUserSubject: BehaviorSubject<User>;
public currentUser: Observable<User>;
constructor(private http: HttpClient, private log: ErrorLoggerService) { constructor(private http: HttpClient) {
this.check().subscribe(); this.currentUserSubject = new BehaviorSubject<User>(JSON.parse(localStorage.getItem('currentUser')));
this.currentUser = this.currentUserSubject.asObservable();
} }
private _user: User; public get user(): User {
return this.currentUserSubject.value;
get user() {
return this._user;
} }
set user(user: User) { login(username: string, password: string) {
this._user = user; const formData: FormData = new FormData();
this.userObservable.next(user); formData.append('username', username);
formData.append('password', password);
formData.append('grant_type', 'password');
return this.http.post<any>(loginUrl, formData)
.pipe(map(u => u.access_token))
.pipe(map(u => this.parseJwt(u)))
.pipe(map(user => {
// store user details and jwt token in local storage to keep user logged in between page refreshes
localStorage.setItem('currentUser', JSON.stringify(user));
this.currentUserSubject.next(user);
return user;
}));
} }
login(name: string, password: string, otp?: string, clientName?: string): Observable<any> { parseJwt(token): User {
const data = {name: name, password: password}; const base64Url = token.split('.')[1];
if (otp) { const base64 = base64Url.replace(/-/g, '+').replace(/_/g, '/');
data['otp'] = otp; const jsonPayload = decodeURIComponent(atob(base64).split('').map(function (c) {
} return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2);
}).join(''));
if (clientName) { const decoded = JSON.parse(jsonPayload);
data['clientName'] = clientName; return new User({
} id: decoded.userId,
name: decoded.sub,
return this.http.post(loginUrl, data, httpOptions) lockedOut: decoded.lockedOut,
.pipe( perms: decoded.scopes,
tap((user: User) => this.user = user), access_token: token,
catchError(this.log.handleError('AuthService', 'login')) exp: decoded.exp
); });
} }
logout(): Observable<any> { logout() {
return this.http.post(logoutUrl, {}, httpOptions) // remove user from local storage to log user out
.pipe( localStorage.removeItem('currentUser');
tap((user: User) => this.user = user), this.currentUserSubject.next(null);
catchError(this.log.handleError('AuthService', 'logout'))
);
} }
check(): Observable<any> {
return this.http.get(checkUrl, httpOptions)
.pipe(
tap((user: User) => this.user = user),
catchError(this.log.handleError('AuthService', 'check'))
);
}
} }

View File

@ -7,9 +7,10 @@ import { MatMenuModule } from '@angular/material/menu';
import { MatToolbarModule } from '@angular/material/toolbar'; import { MatToolbarModule } from '@angular/material/toolbar';
import {RouterModule} from '@angular/router'; import {RouterModule} from '@angular/router';
import {HTTP_INTERCEPTORS} from '@angular/common/http'; import {HTTP_INTERCEPTORS} from '@angular/common/http';
import {HttpAuthInterceptor} from './http-auth-interceptor';
import {LoadingBarHttpClientModule} from '@ngx-loading-bar/http-client'; import {LoadingBarHttpClientModule} from '@ngx-loading-bar/http-client';
import {LoadingBarRouterModule} from '@ngx-loading-bar/router'; import {LoadingBarRouterModule} from '@ngx-loading-bar/router';
import {JwtInterceptor} from './jwt.interceptor';
import {ErrorInterceptor} from './http-auth-interceptor';
@NgModule({ @NgModule({
imports: [ imports: [
@ -30,11 +31,10 @@ import {LoadingBarRouterModule} from '@ngx-loading-bar/router';
LoadingBarHttpClientModule, LoadingBarHttpClientModule,
LoadingBarRouterModule LoadingBarRouterModule
], ],
providers: [[{ providers: [
provide: HTTP_INTERCEPTORS, {provide: HTTP_INTERCEPTORS, useClass: JwtInterceptor, multi: true},
useClass: HttpAuthInterceptor, {provide: HTTP_INTERCEPTORS, useClass: ErrorInterceptor, multi: true},
multi: true ]
}]]
}) })
export class CoreModule { export class CoreModule {
} }

View File

@ -1,26 +1,24 @@
import {Injectable} from '@angular/core'; import { Observable, throwError } from 'rxjs';
import {HttpEvent, HttpHandler, HttpInterceptor, HttpRequest} from '@angular/common/http'; import { catchError } from 'rxjs/operators';
import { Injectable } from '@angular/core';
import {Observable, throwError} from 'rxjs'; import { HttpRequest, HttpHandler, HttpEvent, HttpInterceptor } from '@angular/common/http';
import {catchError} from 'rxjs/operators'; import { Router } from '@angular/router';
import {ToasterService} from './toaster.service';
import {Router} from '@angular/router';
import {ConfirmDialogComponent} from '../shared/confirm-dialog/confirm-dialog.component';
import { MatDialog } from '@angular/material/dialog'; import { MatDialog } from '@angular/material/dialog';
import { AuthService } from '../auth/auth.service';
import { ToasterService } from './toaster.service';
import { ConfirmDialogComponent } from '../shared/confirm-dialog/confirm-dialog.component';
@Injectable() @Injectable()
export class HttpAuthInterceptor implements HttpInterceptor { export class ErrorInterceptor implements HttpInterceptor {
constructor(private authService: AuthService, private router: Router, private dialog: MatDialog, private toaster: ToasterService) { }
constructor(private router: Router, private dialog: MatDialog, private toaster: ToasterService) { intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
} return next.handle(request).pipe(catchError(err => {
if (err.status === 401) {
intercept(req: HttpRequest<any>, next: HttpHandler): console.log('caught 401 in error interceptor');
Observable<HttpEvent<any>> { // auto logout if 401 response returned from api
return next.handle(req) this.authService.logout();
.pipe( this.toaster.show('Danger', 'User has been logged out');
catchError((error: any) => {
if (error.status === 401) {
this.toaster.show('Danger', 'User has been logged out');
const dialogRef = this.dialog.open(ConfirmDialogComponent, { const dialogRef = this.dialog.open(ConfirmDialogComponent, {
width: '250px', width: '250px',
data: { data: {
@ -34,9 +32,8 @@ export class HttpAuthInterceptor implements HttpInterceptor {
} }
}); });
} }
const error = err.error.message || err.statusText;
return throwError(error); return throwError(error);
} }));
) }
);
}
} }

View File

@ -0,0 +1,25 @@
import {Injectable} from '@angular/core';
import {HttpRequest, HttpHandler, HttpEvent, HttpInterceptor} from '@angular/common/http';
import {Observable} from 'rxjs';
import {AuthService} from '../auth/auth.service';
@Injectable()
export class JwtInterceptor implements HttpInterceptor {
constructor(private authService: AuthService) {
}
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
// add authorization header with jwt token if available
const currentUser = this.authService.user;
if (currentUser && currentUser.access_token) {
request = request.clone({
setHeaders: {
Authorization: `Bearer ${currentUser.access_token}`
}
});
}
return next.handle(request);
}
}