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 {ActivatedRouteSnapshot, CanActivate, Router, RouterStateSnapshot} from '@angular/router';
import {Router, CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot} from '@angular/router';
import {AuthService} from './auth.service';
import {Observable} from 'rxjs/internal/Observable';
import {map} from 'rxjs/operators';
import {ToasterService} from '../core/toaster.service';
import {User} from '../core/user';
@Injectable({
providedIn: 'root'
})
@Injectable({providedIn: 'root'})
export class AuthGuard implements CanActivate {
constructor(private auth: AuthService, private router: Router, private toaster: ToasterService) {
constructor(
private router: Router,
private authService: AuthService,
private toaster: ToasterService
) {
}
static checkUser(permission: string, user: User, router: Router, state: RouterStateSnapshot, toaster: ToasterService): boolean {
if (!user.isAuthenticated) {
router.navigate(['login'], {queryParams: {returnUrl: state.url}});
toaster.show('Danger', 'User is not authenticated');
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
const user = this.authService.user;
const permission = route.data['permission'].replace(/ /g, '-').toLowerCase();
if (!user) {
// not logged in so redirect to login page with the return url
this.router.navigate(['/login'], {queryParams: {returnUrl: state.url}});
return false;
}
const hasPermission = permission === undefined || user.perms.indexOf(permission) !== -1;
if (!hasPermission) {
toaster.show('Danger', 'You do not have the permission to access this area.');
console.log(permission, user.perms.indexOf(permission));
if (permission !== undefined && user.perms.indexOf(permission) === -1) {
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 {HttpClient, HttpHeaders} from '@angular/common/http';
import {Observable} from 'rxjs/internal/Observable';
import {catchError, tap} from 'rxjs/operators';
import {Subject} from 'rxjs/internal/Subject';
import {ErrorLoggerService} from '../core/error-logger.service';
import {HttpClient} from '@angular/common/http';
import {BehaviorSubject, Observable} from 'rxjs';
import {map} from 'rxjs/operators';
import {User} from '../core/user';
const loginUrl = '/token';
const httpOptions = {
headers: new HttpHeaders({'Content-Type': 'application/json'})
};
const loginUrl = '/api/login';
const logoutUrl = '/api/logout';
const checkUrl = '/api/auth';
@Injectable({
providedIn: 'root'
})
@Injectable({providedIn: 'root'})
export class AuthService {
public userObservable = new Subject<User>();
private currentUserSubject: BehaviorSubject<User>;
public currentUser: Observable<User>;
constructor(private http: HttpClient, private log: ErrorLoggerService) {
this.check().subscribe();
constructor(private http: HttpClient) {
this.currentUserSubject = new BehaviorSubject<User>(JSON.parse(localStorage.getItem('currentUser')));
this.currentUser = this.currentUserSubject.asObservable();
}
private _user: User;
get user() {
return this._user;
public get user(): User {
return this.currentUserSubject.value;
}
set user(user: User) {
this._user = user;
this.userObservable.next(user);
login(username: string, password: string) {
const formData: FormData = new FormData();
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> {
const data = {name: name, password: password};
if (otp) {
data['otp'] = otp;
}
parseJwt(token): User {
const base64Url = token.split('.')[1];
const base64 = base64Url.replace(/-/g, '+').replace(/_/g, '/');
const jsonPayload = decodeURIComponent(atob(base64).split('').map(function (c) {
return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2);
}).join(''));
if (clientName) {
data['clientName'] = clientName;
}
return this.http.post(loginUrl, data, httpOptions)
.pipe(
tap((user: User) => this.user = user),
catchError(this.log.handleError('AuthService', 'login'))
);
const decoded = JSON.parse(jsonPayload);
return new User({
id: decoded.userId,
name: decoded.sub,
lockedOut: decoded.lockedOut,
perms: decoded.scopes,
access_token: token,
exp: decoded.exp
});
}
logout(): Observable<any> {
return this.http.post(logoutUrl, {}, httpOptions)
.pipe(
tap((user: User) => this.user = user),
catchError(this.log.handleError('AuthService', 'logout'))
);
logout() {
// remove user from local storage to log user out
localStorage.removeItem('currentUser');
this.currentUserSubject.next(null);
}
check(): Observable<any> {
return this.http.get(checkUrl, httpOptions)
.pipe(
tap((user: User) => this.user = user),
catchError(this.log.handleError('AuthService', 'check'))
);
}
}