aboutsummaryrefslogtreecommitdiff
path: root/Timeline/ClientApp/src/app/user/auth.guard.ts
blob: 1fc7a7c086a7888fffe4c8b3e417002dad17ed53 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
import { Injectable } from '@angular/core';
import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot, UrlTree } from '@angular/router';
import { Observable } from 'rxjs';
import { take, map } from 'rxjs/operators';

import { InternalUserService } from './internal-user-service/internal-user.service';

export type AuthStrategy = 'all' | 'requirelogin' | 'requirenologin' | string[];

export abstract class AuthGuard implements CanActivate {

  constructor(protected internalUserService: InternalUserService) { }

  onAuthFailed() { }

  abstract get authStrategy(): AuthStrategy;

  canActivate(next: ActivatedRouteSnapshot, state: RouterStateSnapshot):
    Observable<boolean | UrlTree> | Promise<boolean | UrlTree> | boolean | UrlTree {

    const { authStrategy } = this;

    if (authStrategy === 'all') {
      return true;
    }

    return this.internalUserService.userInfo$.pipe(take(1), map(userInfo => {
      if (userInfo === null) {
        if (authStrategy === 'requirenologin') {
          return true;
        }
      } else {
        if (authStrategy === 'requirelogin') {
          return true;
        } else if (authStrategy instanceof Array) {
          const { roles } = userInfo;
          if (authStrategy.every(value => roles.includes(value))) {
            return true;
          }
        }
      }

      // reach here means auth fails
      this.onAuthFailed();
      return false;
    }));
  }
}

@Injectable({
  providedIn: 'root'
})
export class RequireLoginGuard extends AuthGuard {
  readonly authStrategy: AuthStrategy = 'requirelogin';

  // never remove this constructor or you will get an injection error.
  constructor(internalUserService: InternalUserService) {
    super(internalUserService);
  }

  onAuthFailed() {
    this.internalUserService.userRouteNavigate(['login']);
  }
}

@Injectable({
  providedIn: 'root'
})
export class RequireNoLoginGuard extends AuthGuard {
  readonly authStrategy: AuthStrategy = 'requirenologin';

  // never remove this constructor or you will get an injection error.
  constructor(internalUserService: InternalUserService) {
    super(internalUserService);
  }

  onAuthFailed() {
    this.internalUserService.userRouteNavigate(['success']);
  }
}