Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Redirect on all routes to login if not authenticated

How can I redirect to the login page if someone tries to hit any other route when they are not authenticated? Is there a "best" way to do this in AngularJS?

Seems like a common problem but I can't seem to find a way to do this. Thank you in advance for your help.

like image 780
sturoid Avatar asked Oct 01 '14 16:10

sturoid


People also ask

How do I redirect to login page if not logged in in React?

Path: /src/_components/PrivateRoute.jsx If the user is logged in the Component prop is rendered, otherwise if the user is not logged in the React Router Redirect component is rendered which redirects the user to the /login page. The requested path ( props. location ) is passed with the redirect in the state.

How do I redirect a user to login page in React?

Redirect User to Login Page Using Navigateimport { Navigate } from "react-router-dom"; To redirect unauthenticated users, use it as follows. The Navigate component is a declarative API. It relies on a user event, which in this case is authentication to cause a state change and consequently cause a component re-render.

How do you prevent a browser from going back to login form page once user is logged in React JS?

I succeeded in preventing my website from going back to the login page by pressing the back button using history.


1 Answers

The best way to do this is to set up a '$routeChangeStart' listener which checks an 'authProvider' service function to verify that there is a user logged in. In our 'app.js' or in a separate file:

angular.module('myApp')
     .run(['$rootScope', '$location', 'authProvider', function ($rootScope, $location,     authProvider) {
        $rootScope.$on('$routeChangeStart', function (event) {

        if (!authProvider.isLoggedIn()) {
          console.log('DENY : Redirecting to Login');
          event.preventDefault();
          $location.path('/login');
        }
        else {
          console.log('ALLOW');
        }
  });
}])

Then for our 'authProvider' service:

angular.module('myApp')
  .factory('authProvider', function() {
    var user;
      return {
        setUser : function(aUser){
          user = aUser;
        },
        isLoggedIn : function(){
          return(user)? user : false;
        }
      };
  });

This solution was created from an answer here on stack overflow.

Thank you @MohammadAwwaad

like image 127
Rorschach120 Avatar answered Oct 10 '22 07:10

Rorschach120