Click here to Skip to main content
15,886,578 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Say I have the routing app-routing.module.ts
onst appRoutes: Routes = [
  { path: 'login/:id', canActivate: [AuthGuard], children: [] },
  { path: '', canActivateChild: [AuthGuard], children: [
    { path: '', redirectTo: '/courses', pathMatch: 'full' },
    { path: 'courses', component: CourseListComponent,  pathMatch: 'full'},
    { path: 'courses/:courseId', component: CourseDetailComponent, pathMatch: 'full' },
    { path: 'courses/:courseId/unit/:unitId', component: CoursePlayComponent,
      children: [
        { path: '', component: CourseListComponent },
        { path: 'lesson/:lessonId', component: CourseLessonComponent, data:{ type: 'lesson'} },
        { path: 'quiz/:quizId', component: CourseQuizComponent, data: {type: 'quiz'} }
      ]}
    ]},
  { path: '**', component: PageNotFoundComponent, pathMatch: 'full' }];

And auth.guard.ts
export class AuthGuard implements CanActivate , CanActivateChild {

    constructor(private authUserService: AuthUserService, private router: Router) {   }

    canActivate(route: ActivatedRouteSnapshot, state:
    RouterStateSnapshot): boolean |
    Observable<boolean> | Promise<boolean> {
      // save the id from route snapshot
      const id = +route.params.id;

      // if you try to logging with id
      if (id) {
        this.router.navigate(["/courses"]);
           return this.authUserService.login(id);
      }

      // if you already logged and just navigate between pages
      else if (this.authUserService.isLoggedIn())
         return true;

      else {
        this.router.navigate(["/page_not_found"]);
        return false;
      }
     }

      canActivateChild(route: ActivatedRouteSnapshot,state: RouterStateSnapshot): boolean |
      Observable<boolean> | Promise<boolean> {
         return this.canActivate(route, state);
       }

}

auth-user.service.ts
import { catchError, groupBy } from 'rxjs/operators';

import { UserService } from './user.service';
import { IUser } from './user';

@Injectable()
export class AuthUserService implements OnDestroy {

  private user: IUser;
  private errorMessage: string;

  constructor(private userService: UserService) { }

  // store the session and call http get
  login(id: number) {
  return this.userService.getUser(id).pipe(
    map((user) => {
      this.user = user;
      localStorage.setItem('user', JSON.stringify(this.user));
      localStorage.setItem('token', 'JWT');
      return true;
    }),
    catchError((error) => {
      this.errorMessage = <any>error;
      return of(false);
    })
  );
}

  isLoggedIn() {
   return !!localStorage.getItem('token');
  }

  ngOnDestroy() {
    localStorage.removeItem('user');
    localStorage.removeItem('token');
  }
}

In my application there are many pages. Everybody need to login, but it only need to login one time. That is enough. My question is that if I am in the other page, how to retrieve the token to check if I already login?

What I have tried:

login(email:string, password:string) {
    return this.httpClient.post<{access_token:  string}>('http://www.your-server.com/auth/login', {email, password}).pipe(tap(res => {
    localStorage.setItem('access_token', res.access_token);
}))
}
Posted
Updated 13-Jul-19 13:50pm

1 solution

As I see, AuthUserService.isLoggedIn will give you whether you logged in or not in any page.

In AuthGuard, this code is not needed, i think. You are calling login method every time whenever param is passed.
JavaScript
// if you try to logging with id
      if (id) {
        this.router.navigate(["/courses"]);
           return this.authUserService.login(id);
      }

CanActivate method should be like this:
JavaScript
canActivate(route: ActivatedRouteSnapshot, state:
    RouterStateSnapshot): boolean |
    Observable<boolean> | Promise<boolean> {
      if (this.authUserService.isLoggedIn())
         return true;

      else {
        this.router.navigate(["/page_not_found"]);
        return false;
      }
     }

If you need custome canActivate, write your custom canActivate method more eligently.
 
Share this answer
 
Comments
Member 12658724 14-Jul-19 21:49pm    
So in any other page other than login page we inject AuthUserService than call the method AuthUserService.isLoggedIn?

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900