javascriptangulartypescript

Angular Auth Guard - users can access the login page only when they are not logged in and can access other pages only when they are logged in


Auth Guard


    export const AuthGuard: CanActivateFn = (
            route: ActivatedRouteSnapshot,
            state: RouterStateSnapshot,
          ): Observable<boolean | UrlTree> | Promise<boolean | UrlTree> | boolean | UrlTree => {
            const router = inject(Router);
            if (localStorage.getItem('userdata')) {
              return true;
            } else {
              return router.navigate(['login']);
              /** no need to return 'false', just return the promise */
            }
          };

I want users to access the login page only when they are not logged in and other pages only when they are logged in.

If in localstorage there is no data, then it can access the login page, and if localstorage has data, then it can access the dashboard. In the above code, if localstorage has data, then not only does it give access to the dashboard page, but it also gives access to the login page.

If local storage has no data, then only give access to the login page that I want. "What am I doing wrong?


Solution

  • Is this what you need?

    See this example on stackblitz

    AuthGuard:

    export const authGuard: CanMatchFn = () =>
      !!inject(AuthService).loggedIn() ||
      inject(Router).navigate(['auth', 'login']);
    

    PublicGuard:

    export const publicGuard: CanMatchFn = () =>
      !inject(AuthService).loggedIn() ||
      inject(Router).navigate(['app', 'dasboard']);
    

    AuthService

    @Injectable({
      providedIn: 'root',
    })
    export class AuthService {
      router = inject(Router);
    
      login() {
        localStorage.setItem('__d54563__token', 'the-token');
        this.router.navigate(['']);
      }
    
      logout() {
        localStorage.removeItem('__d54563__token');
        this.router.navigate(['']);
      }
    
      loggedIn() {
        return !!localStorage.getItem('__d54563__token');
      }
    }
    

    Routes

    const routes: Route[] = [
      {
        path: '',
        pathMatch: 'full',
        redirectTo: 'app/dashboard',
      },
      {
        path: 'app',
        canMatch: [authGuard],
        loadComponent: () =>
          import('./app/app-container.component').then(
            (m) => m.AppContainerComponent
          ),
        children: [
          {
            path: 'dashboard',
            loadComponent: () =>
              import('./app/dashboard.component').then((m) => m.DashboardComponent),
          },
          {
            path: 'another-page',
            loadComponent: () =>
              import('./app/another-page.component').then(
                (m) => m.AnotherPageComponent
              ),
          },
          /** other app routes */
        ],
      },
      {
        path: 'auth',
        canMatch: [publicGuard],
        loadComponent: () =>
          import('./app/auth/auth-container.component').then(
            (m) => m.AuthContainerComponent
          ),
        children: [
          {
            path: 'login',
            loadComponent: () =>
              import('./app/auth/login.component').then((m) => m.LoginComponent),
          },
          {
            path: 'register',
            loadComponent: () =>
              import('./app/auth/register.component').then(
                (m) => m.RegisterComponent
              ),
          },
        ],
      },
    ];