Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to restrict access to Login Route if user is already logged in in Angular 4?

I have successfully implement AuthGuardService which restrict access to a protected route if user is not logged in.

What I am trying to achieve is, if user is already logged in and accessed the Login Route, I want it to redirect to another route like homepage.

like image 488
Daniel Chikaka Avatar asked Nov 02 '17 14:11

Daniel Chikaka


People also ask

How would I restrict access to routes in angular?

Angular is completely independent of the server. We are using stateless REST API to get data. So use AuthGuard to protect the routes from unauthorized access.

What is AuthGuard angular?

AuthGuard is used to protect the routes from unauthorized access in angular. How AuthGuard Works? Auth guard provide lifecycle event called canActivate. The canActivate is like a constructor. It will be called before accessing the routes.

How do I restrict the URL of a user in AngularJS?

How do I restrict the url for user in Angularjs? You can use ‘Route Guard’ for this. Route Guards are basically service (as they are injectable), where you define various cases in which a route must be hit. Like, for example, if there are two types of user -> Admin and normal user.

How to manage the user authentication permission for the angular path?

Manage the user authentication permission for the Angular path. Angular Auth Guard This Angular function helps a lot when it comes to handling authentication. This is an interface that instructs the router whether or not to enable navigation to a specific route. We're using the 'canActivate' guard form in this case. Angular localStorage

How to manage redirects in angular?

With Angular, we can implement this flow using route guards and the router to help manage redirects. Imagine we’re building a forum, and we want to ensure that a user is logged in before they can post a new message.

What is the difference between logout() and isloggedin() in Angular 2?

logout () function removes the user's information about login from local storage. isLoggedIn () function inform us whether the user is logged into the system. getRole () function gives us the user's role from local storage. To create a guard you should use angular-cli command. This can be like below.


Video Answer


2 Answers

You can create two CanActivate guard:
- For restricting routes for already loggedIn users (eg: /login, /register etc)
- For restricting routes for not loggedIn users (eg: /dashboard)

Auth Service

loggedIn() {
    //return boolean for loggedIn user logic
}

Guard for not loggedIn Users

import { Injectable } from "@angular/core";
import { CanActivate, Router } from "@angular/router";
import { AuthService } from './auth.service';

@Injectable()
export class AuthGuard implements CanActivate {

    constructor(private _authService: AuthService, private _router: Router) { }

    canActivate(): boolean {
        if (this._authService.loggedIn()) {
            return true;
        } else {
            this._router.navigate(['/login'])
            return false
        }
    }
}

Guard for loggedIn Users

import { Injectable } from "@angular/core";
import { CanActivate, Router } from "@angular/router";
import { AuthService } from './auth.service';

@Injectable()
export class LoggedInAuthGuard implements CanActivate {

    constructor(private _authService: AuthService, private _router: Router) { }

    canActivate(): boolean {
        if (this._authService.loggedIn()) {
            this._router.navigate(['/dashboard'])
            return false
        } else {
            return true
        }
    }
}

Register AuthGuard in App Module

...
providers:[AuthGuard,LoggedInAuthGuard]
...

Add AuthGuard in Routing Module

const routes: Route[] = [
  { path: "/login", component: LoginComponent, canActivate:[LoggedInAuthGuard] },
  { path: "/dashboard, component: DashboardComponent, canActivate: [AuthGuard]}
]
like image 138
Priyanka Jalan Avatar answered Sep 21 '22 16:09

Priyanka Jalan


You could perform a simple check in the ngOnInit of the login component like so and redirect to another page of your choice if they are authenticated already:

ngOnInit() {
   if (this._authService.isLoggedIn) {
      this._router.navigate(['/apps']);
   }
}

That worked for me!

like image 36
Daniel Chikaka Avatar answered Sep 21 '22 16:09

Daniel Chikaka