3

I am configuring a guard for my angular app and it happens that when I run the application and log in the first time it works fine, but I configure an error interceptor where I have a condition that when the user receives a 401 error from the api it returns it at login. and well up to there it works as I want but after sending myself to the login I try to start the session again and the guard fails me This only happens in this case, if I log out and log in again it works correctly it is only when after receiving the 401 error and I send the user to login that the guard fails me.

Guard

canActivate(){
  if(localStorage.getItem("token")){
    return true;
  }else{
    this.router.navigate(['login']);
    return false;
  }
}

Login component

onLogin(form: Login) {
    this.api.loginUser(form).subscribe(data => {
      if (data) {
        this.router.navigate(['dashboard']);
      }
    }, (err => {
      this.alertMessageService.getMessageError(err.message);
    }));
  }

Service

loginUser(form: Login): Observable<LoginResponse | void> {
let uri = environment.baseUrl + 'authenticate/login';

return this.http.post<LoginResponse>(uri, form, this.httpOptions).pipe(
  map(resp => {
    this.saveToken(resp);
    return resp;
  }),
  catchError(err => {
    return throwError(err);
  })
);
}

public saveToken(data: any): void {
  localStorage.setItem('token', data.token);
  localStorage.setItem('expiration', data.expiration);
  localStorage.setItem('user', data.user);
  localStorage.setItem('userId', data.userId);
  localStorage.setItem('role', data.role);
}

Interceptor Errors

intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        return next.handle(req).pipe(
            catchError((err)=> this.managementError(err))
        );
    }

    managementError(err : HttpErrorResponse){
        if(err.status == 401){
            localStorage.clear();
            this.router.navigate(['login']);
        }else if(err.status == 500){
            this.router.navigate(['500']);
        }else if(err.status == 404){
            this.router.navigate(['404']);
        }else{
            return throwError(err);
        }
    }

App Routing

export const routes: Routes = [
  {
    path: '',
    redirectTo: 'dashboard',
    pathMatch: 'full',
  },
  {
    path: '404',
    component: P404Component,
    data: {
      title: 'Page 404'
    }
  },
  {
    path: '500',
    component: P500Component,
    data: {
      title: 'Page 500'
    }
  },
  {
    path: 'login',
    component: LoginComponent,
    data: {
      title: 'Login Page'
    }
  },
  {
    path: 'register',
    component: RegisterComponent,
    data: {
      title: 'Register Page'
    }
  },
  {
    path: 'forgot-password',
    component: ForgotPasswordComponent,
    data: {
      title: 'Forgot Password Page'
    }
  },
  {
    path: '',
    component: DefaultLayoutComponent,
    data: {
      title: 'Home'
    },canActivate:[CheckLoginGuard],
    children: [
      {
        path: 'dashboard',
        loadChildren: () => import('./views/dashboard/dashboard.module').then(m => m.DashboardModule),
      },
      {
        path: 'user',
        loadChildren: () => import('./views/user/user.module').then(m => m.UserModule)
      },
      {
        path: 'company',
        loadChildren: () => import('./views/company/company.module').then(m => m.CompanyModule)
      },
      {
        path: 'project',
        loadChildren: () => import('./views/project/project.module').then(m => m.ProjectModule)
      },
      {
        path: 'blog',
        loadChildren: () => import('./views/blog/blog.module').then(m => m.BlogModule)
      },
      {
        path: 'category',
        loadChildren: () => import('./views/category/category.module').then(m => m.CategoryModule)
      },
      {
        path: 'opportunity-request',
        loadChildren: () => import('./views/opportunity-request/opportunity-request.module').then(m => m.OpportunityRequestModule)
      },
      {
        path: 'department',
        loadChildren: () => import('./views/department/department.module').then(m => m.DepartmentModule)
      },
      {
        path: 'job-opportunity',
        loadChildren: () => import('./views/job-opportunity/job-opportunity.module').then(m => m.JobOpportunityModule)
      },
      {
        path: 'job-request',
        loadChildren: () => import('./views/job-request/job-request.module').then(m => m.JobRequestModule)
      },
      {
        path: 'status',
        loadChildren: () => import('./views/status/status.module').then(m => m.StatusModule)
      },
      {
        path: 'suggestion',
        loadChildren: () => import('./views/suggestion/suggestion.module').then(m => m.SuggestionModule)
      },
      {
        path: 'type-request',
        loadChildren: () => import('./views/type-request/type-request.module').then(m => m.TypeRequestModule)
      },
      { 
        path: 'social', loadChildren: () => import('./views/social/social.module').then(m => m.SocialModule) 
      }
    ]
  },
  { path: '**', component: P404Component }
];
Deybi Tabora Paz
  • 171
  • 3
  • 11

1 Answers1

0

To debug the issue, I think you can do:

Have the developer tools open for the debugger to be triggered.

canActivate(){
  // Understand why the 2nd time there is a token in localStorage
  // I am thinking maybe the login page sets a token
  console.log(`[Guard] localStorage.getItem('token'): ${localStorage.getItem('token')}`);
  debugger;
  if(localStorage.getItem("token")){
    return true;
  }else{
    this.router.navigate(['login']);
    return false;
  }
}
AliF50
  • 16,947
  • 1
  • 21
  • 37
  • Yes, in fact I already debugged the code and it seems very strange that the problem persists, I will edit my question and add the login function – Deybi Tabora Paz Dec 08 '21 at 04:02