1
|
|
|
import { Injectable } from "@angular/core"; |
2
|
|
|
import { |
3
|
|
|
ActivatedRouteSnapshot, |
4
|
|
|
CanActivate, |
5
|
|
|
CanActivateChild, |
6
|
|
|
Router, |
7
|
|
|
RouterStateSnapshot, |
8
|
|
|
} from "@angular/router"; |
9
|
|
|
import { map, take, tap } from "rxjs/operators"; |
10
|
|
|
import { UniFirebaseLoginConfig } from "../config/uni-firebase-login-config"; |
11
|
|
|
import { UserModel } from "../model/user-model"; |
12
|
|
|
import { BaseAuthService } from "../services/base-auth-service"; |
13
|
|
|
|
14
|
|
|
@Injectable({ |
15
|
|
|
providedIn: "root", |
16
|
|
|
}) |
17
|
|
|
export class AuthGuard<User extends UserModel = UserModel> |
18
|
|
|
implements CanActivate, CanActivateChild { |
19
|
|
|
public constructor( |
20
|
|
|
protected auth: BaseAuthService<User>, |
21
|
|
|
protected router: Router, |
22
|
|
|
protected config: UniFirebaseLoginConfig, |
23
|
|
|
) {} |
24
|
|
|
|
25
|
|
|
public async canActivate( |
26
|
|
|
next: ActivatedRouteSnapshot, |
27
|
|
|
state: RouterStateSnapshot, |
28
|
|
|
): Promise<boolean> { |
29
|
|
|
const user$ = this.auth.getUser(); |
30
|
|
|
|
31
|
|
|
return user$ |
32
|
|
|
.pipe( |
33
|
|
|
take(1), |
34
|
|
|
map(user => !!user), // Map to boolean |
35
|
|
|
tap(loggedIn => { |
36
|
|
|
if (!loggedIn) { |
37
|
|
|
// Access denied |
38
|
|
|
const redirectTo = this.config.signInPage; |
39
|
|
|
console.log( |
40
|
|
|
`Insufficient permissions, redirecting to: ${redirectTo}`, |
41
|
|
|
); |
42
|
|
|
return this.router.navigate([redirectTo]); |
43
|
|
|
} |
44
|
|
|
}), |
45
|
|
|
) |
46
|
|
|
.toPromise(); |
47
|
|
|
} |
48
|
|
|
|
49
|
|
|
public canActivateChild( |
50
|
|
|
next: ActivatedRouteSnapshot, |
51
|
|
|
state: RouterStateSnapshot, |
52
|
|
|
): Promise<boolean> { |
53
|
|
|
return this.canActivate(next, state); |
54
|
|
|
} |
55
|
|
|
} |
56
|
|
|
|