简体   繁体   中英

Disable AuthGuard and canActivate restrictions

I received a project where I need to work on for an internship, but there is a canActivate: [AuthGuard] and many others restriction, so every routes redirect me to login page, and I don't have any credentials to connect so I need a way to disable temporarily those restrictions if someone can help me, I tried to return false in the canActivate() funciton but without success. Here the route array, auth.guard.ts and auth.service.ts:

Routes array:

const routes: Routes = [
  { path: '', redirectTo: '/home/dashboard', pathMatch: 'full' },
  { path: 'home', component: HomeComponent, canActivate: [AuthGuard], children: [
    { path: '', redirectTo: '/home/dashboard', pathMatch: 'full' },
    { path: 'dashboard', component: DashboardComponent, canActivate: [CaseManagerDashboardGuard] },
    { path: 'messages_board', component: MessagesBoardComponent },
    { path: 'create_organization', component: CreateOrganizationComponent, canActivate: [CreateOrganizationGuard] },
    { path: 'my_profile/:id', component: MyProfileComponent },
    { path: 'profile/:id', component: MyProfileComponent, canActivate: [ProfileGuard] },
    { path: 'create_user', component: CreateUserComponent, canActivate: [CreateUserGuard] },
    { path: 'search_user', component: SearchUserComponent, canActivate: [SearchUserGuard] },
    { path: 'create_patient', component: CreatePatientComponent, canActivate: [CreatePatientGuard], canDeactivate: [CanDeactivateGuard] },
    { path: 'search_patient', component: SearchPatientComponent, canActivate: [SearchPatientGuard] },
    { path: 'patient/:id', component: ClientDashboardComponent, canActivate: [PatientGuard] },
    { path: 'patient_profile/:id', component: ClientProfileComponent, canActivate: [PatientGuard] },
    { path: 'reports', component: ReportsComponent }
  ]},
  { path: 'login', component: LoginComponent },
  { path: 'first-login', component: FirstLoginComponent },
  { path: 'reset-password', component: ResetPasswordComponent },
  { path: 'new-password', component: NewPasswordComponent },
  {
    path: 'chat-poc',
    loadChildren: () => import('./pages/poc/chat-poc.module').then(m => m.ChatPocModule)
  },

  // otherwise redirect to home
  { path: '**', redirectTo: '/home' }
];

auth.guard.ts:

import { Injectable } from '@angular/core';
import { Router, CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot, UrlTree } from '@angular/router';
import { Observable } from 'rxjs';
import { map, tap, take } from 'rxjs/operators';
import { AuthService } from './auth.service';

@Injectable({ providedIn: 'root' })
export class AuthGuard implements CanActivate {
  constructor(private authService: AuthService, private router: Router) {}


  canActivate(route: ActivatedRouteSnapshot, router: RouterStateSnapshot) {
    console.log('canActivate - AuthGuard 1');
    return this.authService.user.pipe(
      take(1),
      map(user => {
        console.log('canActivate - AuthGuard 2');
        // console.log(user, 14);
        const isAuth = !!user;
        if (isAuth) {
          console.log('canActivate - AuthGuard 3');
          return true;
        }
        console.log('canActivate - AuthGuard 4');
        return this.router.createUrlTree(['/login']);
      })
    );
  }
}

auth.service.ts (a bit tall)

import Swal from 'sweetalert2/dist/sweetalert2.js';
import {Injectable} from '@angular/core';
import {HttpClient, HttpErrorResponse, HttpHeaders} from '@angular/common/http';
import {catchError, tap, concatMap} from 'rxjs/operators';
import {BehaviorSubject, throwError, from} from 'rxjs';
import {Router} from '@angular/router';
import { User } from '../models/user.model';
import { environment } from 'src/environments/environment';
import { ChatThreadsService } from '../partials/chat/services/chat-threads.service';
import { TranslateService } from '@ngx-translate/core';

export interface AuthResponseData {
  kind: string;
  idToken: string;
  email: string;
  refreshToken: string;
  expiresIn: string;
  localId: string;
  registered?: boolean;
}

export interface FirstLoginResponseData {
  email: string;
}

export interface PasswordResetEmail {
  email: string;
}

@Injectable({ providedIn: 'root' })
export class AuthService {
  user = new BehaviorSubject<User>(null);
  userExtraData = new BehaviorSubject<any>(null);

  private tokenExpirationTimer: any;

  constructor(
    private http: HttpClient,
    private router: Router,
    private _chatThreadsService: ChatThreadsService,
    public translate: TranslateService
  ) {}

  firstLogin(password: string, oobCode: string) {
    return this.http.post<FirstLoginResponseData>(
      environment.identitytoolkit + 'accounts:resetPassword?key=' + environment.firebase.apiKey,
      {
        oobCode,
        newPassword: password
      }
    ).pipe(
      catchError(this.handleError),
      tap(resData => {
        this.login(resData.email, password).subscribe(
          respData => {
            this.translate.get('Change_Password_completed_alert').subscribe((res: string) => {
              Swal.fire({title: '', text: res, icon: 'success', showCancelButton: false, confirmButtonText: 'Ok'})
              .then((result) => {
                if (result.value) {
                  console.log(respData);
                  this.getUserExtData(respData.idToken).subscribe(
                    resp => {
                      this.router.navigate(['/home']);
                    }
                  );
                }
              });
            });
          },
          errorMessage => {
            console.log(errorMessage);
            this.translate.get('Change_Password_error_alert').subscribe((res: string) => {
              Swal.fire({title: '', text: res, icon: 'error', showCancelButton: false, confirmButtonText: 'Close'})
              .then((result) => {
                if (result.value) {
                    this.router.navigate(['/reset-password']);
                }
              });
            });
          }
        );
      })
    );
  }

  sendPasswordResetEmail(email: string) {
    return this.http.post<PasswordResetEmail>(
      environment.identitytoolkit + 'accounts:sendOobCode?key=' + environment.firebase.apiKey,
      {
        requestType: 'PASSWORD_RESET',
        email
      }
    ).pipe(
      catchError(this.handleError),
      tap(resData => {
        console.log('sendPasswordResetEmail Done');
      })
    );
  }

  login(email: string, password: string) {
    return this.http.post<AuthResponseData>(
      environment.identitytoolkit + 'accounts:signInWithPassword?key=' + environment.firebase.apiKey,
      {
        email,
        password,
        returnSecureToken: true
      }
    ).pipe(
      catchError(this.handleError),
      tap(resData => {
        this.handleAuthentication(resData.email, resData.localId, resData.idToken, +resData.expiresIn, resData.refreshToken);
      })
    );
  }

  autoLogin() {
    const userData: {
      email: string,
      id: string,
      _token: string,
      _tokenExpirationDate: string,
      refToken: string,
    } = JSON.parse(localStorage.getItem('userData'));

    if (!userData) {
      return;
    }

    const loadedUser = new User(userData.email, userData.id, userData._token, new Date(userData._tokenExpirationDate), userData.refToken);

    if (loadedUser.token) {
      this.user.next(loadedUser);
      const expirationDuration = new Date(userData._tokenExpirationDate).getTime() - new Date().getTime();
      this.autoLogout(expirationDuration);
      // this.refreshToken(expirationDuration, loadedUser.refreshToken);
    }
  }

  logout() {
    this._chatThreadsService.logout();
    this.user.next(null);
    this.userExtraData.next(null);
    this.router.navigate(['/login']);
    localStorage.removeItem('userData');
    localStorage.removeItem('userExtData');
    if (this.tokenExpirationTimer) {
      clearTimeout(this.tokenExpirationTimer);
    }
    this.tokenExpirationTimer = null;
  }

  autoLogout(expirationDuration: number) {
    this.tokenExpirationTimer = setTimeout(() => {
      this.logout();
    }, expirationDuration);
  }

  refreshToken(expirationDuration: number, refToken: string) {
    console.log(expirationDuration);
    this.tokenExpirationTimer = setTimeout(() => {
      this.http.post<any>(
        'https://securetoken.googleapis.com/v1/token?key=' + environment.firebase.apiKey,
        {
          refresh_token: refToken,
          grant_type: 'refresh_token'
        }
      ).pipe(
        // catchError(this.handleError),
        tap(resData => {
          this.refreshToken((+resData.expires_in) * 1000, refToken);
        })
      ).subscribe();
    }, expirationDuration);
  }

  getUserExtData(idToken) {
    const headers = { Authorization: 'Bearer ' + idToken };
    return this.http.get<any>(
      environment.apiURL + 'users/me', { headers }
    ).pipe(
      tap(resExtData => {
        this.userExtraData.next(resExtData);
        localStorage.setItem('userExtData', JSON.stringify(resExtData));
      })
    );
  }

  userExtDataUpdate(id: string, language: string, units: string, date_format: string, week_start_day: string, idToken: string) {
    const headers = { Authorization: 'Bearer ' + idToken };
    return this.http.post<any>(
      environment.apiURL + 'users/update',
      {
        id,
        settings: {
          language,
          date_format,
          units,
          week_start_day
        }
      },
      {
        headers
      }
    ).pipe(
      tap(resExtData => {
        this.getUserExtData(idToken).subscribe();
      })
    );
  }

  private handleAuthentication(email: string, userId: string, token: string, expiresIn: number, refreshToken: string) {
    const expirationDate = new Date(new Date().getTime() + expiresIn * 1000);
    const user = new User(email, userId, token, expirationDate, refreshToken);
    this.user.next(user);
    this.autoLogout(expiresIn * 1000);
    // this.refreshToken(expiresIn * 1000, refreshToken);
    localStorage.setItem('userData', JSON.stringify(user));
  }

  private handleError(errorRes: HttpErrorResponse) {
    let errorMessage = 'An unknown error occurred!';
    if (!errorRes.error || !errorRes.error.error) {
      return throwError(errorMessage);
    }
    switch (errorRes.error.error.message) {
      case 'EMAIL_EXISTS':
        errorMessage = 'This email exists already';
        break;
      case 'EMAIL_NOT_FOUND':
        // errorMessage = 'This email does not exist.';
        errorMessage = 'Invalid Email';
        break;
      case 'INVALID_PASSWORD':
        errorMessage = 'This password is not correct.';
        break;
    }
    console.log('handleError', errorMessage);
    return throwError(errorMessage);
  }
}

Change the line return this.router.createUrlTree(['/login']); to return true; in auth.guard.ts but keep in mind that being able to go to routes where authentication is required might be weird and you will get a lot of errors potentially.

remove

canActivate: []

temporarily for that purpose. so you can skip the authentication thing temporarily.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM