Added: Alembic for migrations
Moving from Pyramid to FastAPI
This commit is contained in:
@ -1,39 +1,34 @@
|
||||
import { Injectable } from '@angular/core';
|
||||
import { ActivatedRouteSnapshot, CanActivate, Router, RouterStateSnapshot } from '@angular/router';
|
||||
import { Observable } from 'rxjs/internal/Observable';
|
||||
import { map } from 'rxjs/operators';
|
||||
import { Router, CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';
|
||||
|
||||
import { AuthService } from './auth.service';
|
||||
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
|
||||
) {
|
||||
}
|
||||
|
||||
checkUser(permission: string, user: User, state: RouterStateSnapshot): boolean {
|
||||
if (!user.isAuthenticated) {
|
||||
this.router.navigate(['login'], {queryParams: {returnUrl: state.url}});
|
||||
this.toaster.show('Danger', 'User is not authenticated');
|
||||
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
|
||||
const user = this.authService.user;
|
||||
const permission = (route.data['permission'] === undefined) ? route.data['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 = this.auth.hasPermission(permission);
|
||||
if (!hasPermission) {
|
||||
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(next: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> | boolean {
|
||||
return this.auth.userObservable
|
||||
.pipe(
|
||||
map<User, boolean>((value: User) => this.checkUser(
|
||||
next.data['permission'], value, state
|
||||
))
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@ -1,64 +1,97 @@
|
||||
import { Injectable } from '@angular/core';
|
||||
import { HttpClient, HttpHeaders } from '@angular/common/http';
|
||||
import { Observable } from 'rxjs/internal/Observable';
|
||||
import { catchError, map, tap } from 'rxjs/operators';
|
||||
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';
|
||||
import { merge, Subject } from 'rxjs';
|
||||
import { environment } from '../../environments/environment';
|
||||
|
||||
const loginUrl = '/token';
|
||||
const refreshUrl = '/refresh';
|
||||
const JWT_USER = 'JWT_USER';
|
||||
|
||||
const httpOptions = {
|
||||
headers: new HttpHeaders({'Content-Type': 'application/json'})
|
||||
};
|
||||
|
||||
const loginUrl = '/v1/login';
|
||||
const logoutUrl = '/logout';
|
||||
const checkUrl = '/v1/auth';
|
||||
|
||||
@Injectable({
|
||||
providedIn: 'root'
|
||||
})
|
||||
@Injectable({providedIn: 'root'})
|
||||
export class AuthService {
|
||||
private readonly userSubject: Subject<User>;
|
||||
private user: User;
|
||||
public userObservable: Observable<User>;
|
||||
constructor(private http: HttpClient, private log: ErrorLoggerService) {
|
||||
this.userSubject = new Subject<User>();
|
||||
this.userObservable = merge(this.checkObserver(), this.userSubject).pipe(
|
||||
tap(x => this.user = x)
|
||||
);
|
||||
private currentUserSubject: BehaviorSubject<User>;
|
||||
public currentUser: Observable<User>;
|
||||
|
||||
constructor(private http: HttpClient) {
|
||||
this.currentUserSubject = new BehaviorSubject<User>(JSON.parse(localStorage.getItem(JWT_USER)));
|
||||
this.currentUser = this.currentUserSubject.asObservable();
|
||||
}
|
||||
|
||||
checkObserver(): Observable<User> {
|
||||
return <Observable<User>>this.http.get<User>(checkUrl, httpOptions);
|
||||
}
|
||||
|
||||
login(name: string, password: string, otp?: string, clientName?: string): Observable<any> {
|
||||
const data = {name: name, password: password};
|
||||
if (otp) {
|
||||
data['otp'] = otp;
|
||||
public get user(): User {
|
||||
const val = this.currentUserSubject.value;
|
||||
if (val == null) {
|
||||
return val;
|
||||
}
|
||||
|
||||
if (clientName) {
|
||||
data['clientName'] = clientName;
|
||||
const expired = Date.now() > val.exp * 1000;
|
||||
if (expired) {
|
||||
this.logout();
|
||||
return null;
|
||||
} else {
|
||||
return this.currentUserSubject.value;
|
||||
}
|
||||
|
||||
return this.http.post(loginUrl, data, httpOptions)
|
||||
.pipe(
|
||||
tap((user: User) => this.userSubject.next(user)),
|
||||
catchError(this.log.handleError('AuthService', 'login'))
|
||||
);
|
||||
}
|
||||
|
||||
logout(): Observable<boolean> {
|
||||
return <Observable<boolean>>this.http.post<User>(logoutUrl, {}, httpOptions)
|
||||
.pipe(
|
||||
tap((user: User) => this.userSubject.next(user)),
|
||||
map(() => true)
|
||||
);
|
||||
login(username: string, password: string, otp: string) {
|
||||
const formData: FormData = new FormData();
|
||||
formData.append('username', username);
|
||||
formData.append('password', password);
|
||||
formData.append('otp', otp);
|
||||
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(JWT_USER, JSON.stringify(user));
|
||||
this.currentUserSubject.next(user);
|
||||
return user;
|
||||
}));
|
||||
}
|
||||
|
||||
hasPermission(permission: string): boolean {
|
||||
return this.user !== undefined && this.user.isAuthenticated && this.user.perms.indexOf(permission) !== -1;
|
||||
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(''));
|
||||
|
||||
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
|
||||
});
|
||||
}
|
||||
|
||||
needsRefreshing(): boolean {
|
||||
return Date.now() > (this.user.exp - (environment.ACCESS_TOKEN_REFRESH_MINUTES * 60)) * 1000;
|
||||
}
|
||||
|
||||
expired(): boolean {
|
||||
return Date.now() > this.user.exp * 1000;
|
||||
}
|
||||
|
||||
logout() {
|
||||
// remove user from local storage to log user out
|
||||
localStorage.removeItem(JWT_USER);
|
||||
this.currentUserSubject.next(null);
|
||||
}
|
||||
|
||||
refreshToken() {
|
||||
return this.http.post<any>(refreshUrl, {})
|
||||
.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(JWT_USER, JSON.stringify(user));
|
||||
this.currentUserSubject.next(user);
|
||||
return user;
|
||||
}));
|
||||
}
|
||||
}
|
||||
|
||||
@ -1,9 +1,9 @@
|
||||
import {AfterViewInit, Component, ElementRef, OnInit, ViewChild} from '@angular/core';
|
||||
import {AuthService} from '../auth.service';
|
||||
import {ActivatedRoute, Router} from '@angular/router';
|
||||
import {ToasterService} from '../../core/toaster.service';
|
||||
import {FormBuilder, FormGroup} from '@angular/forms';
|
||||
import {CookieService} from '../../shared/cookie.service';
|
||||
import { AfterViewInit, Component, ElementRef, OnInit, ViewChild } from '@angular/core';
|
||||
import { AuthService } from '../auth.service';
|
||||
import { ActivatedRoute, Router } from '@angular/router';
|
||||
import { ToasterService } from '../../core/toaster.service';
|
||||
import { FormBuilder, FormGroup } from '@angular/forms';
|
||||
import { CookieService } from '../../shared/cookie.service';
|
||||
|
||||
@Component({
|
||||
selector: 'app-login',
|
||||
@ -15,7 +15,7 @@ export class LoginComponent implements OnInit, AfterViewInit {
|
||||
form: FormGroup;
|
||||
hide: boolean;
|
||||
showOtp: boolean;
|
||||
clientID: string;
|
||||
clientId: string;
|
||||
private returnUrl: string;
|
||||
|
||||
constructor(private route: ActivatedRoute,
|
||||
@ -34,8 +34,7 @@ export class LoginComponent implements OnInit, AfterViewInit {
|
||||
this.form = this.fb.group({
|
||||
username: '',
|
||||
password: '',
|
||||
otp: '',
|
||||
clientName: ''
|
||||
otp: ''
|
||||
});
|
||||
}
|
||||
|
||||
@ -53,17 +52,20 @@ export class LoginComponent implements OnInit, AfterViewInit {
|
||||
const formModel = this.form.value;
|
||||
const username = formModel.username;
|
||||
const password = formModel.password;
|
||||
this.auth.login(username, password).subscribe(
|
||||
(result) => {
|
||||
this.router.navigateByUrl(this.returnUrl);
|
||||
},
|
||||
(error) => {
|
||||
if (error.status === 403 && ['Unknown Client', 'OTP not supplied', 'OTP is wrong'].indexOf(error.error) !== -1) {
|
||||
this.showOtp = true;
|
||||
this.clientID = this.cs.getCookie('ClientID');
|
||||
}
|
||||
this.toaster.show('Danger', error.error);
|
||||
}
|
||||
);
|
||||
const otp = formModel.otp;
|
||||
this.auth.login(username, password, otp)
|
||||
// .pipe(first())
|
||||
.subscribe(
|
||||
data => {
|
||||
this.router.navigate([this.returnUrl]);
|
||||
},
|
||||
(error) => {
|
||||
if (error.status === 401 && 'Client is not registered' === error.error.detail) {
|
||||
this.showOtp = true;
|
||||
this.clientId = this.cs.getCookie('client_id');
|
||||
}
|
||||
this.toaster.show('Danger', error.error.details);
|
||||
}
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@ -1,7 +1,7 @@
|
||||
import {Component, OnInit} from '@angular/core';
|
||||
import {Router} from '@angular/router';
|
||||
import {AuthService} from '../auth.service';
|
||||
import {ToasterService} from '../../core/toaster.service';
|
||||
import { Component, OnInit } from '@angular/core';
|
||||
import { Router } from '@angular/router';
|
||||
import { AuthService } from '../auth.service';
|
||||
import { ToasterService } from '../../core/toaster.service';
|
||||
|
||||
@Component({
|
||||
selector: 'app-logout',
|
||||
@ -9,17 +9,11 @@ import {ToasterService} from '../../core/toaster.service';
|
||||
})
|
||||
export class LogoutComponent implements OnInit {
|
||||
|
||||
constructor(private auth: AuthService, private router: Router, private toaster: ToasterService) {
|
||||
constructor(private auth: AuthService) {
|
||||
}
|
||||
|
||||
ngOnInit() {
|
||||
this.auth.logout().subscribe(
|
||||
(result) => {
|
||||
this.toaster.show('Success', 'Logged Out');
|
||||
this.router.navigateByUrl('/');
|
||||
},
|
||||
(error) => this.toaster.show('Danger', error.error)
|
||||
);
|
||||
this.auth.logout();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user