0

I have implemented an Authentication system for my app. I use $routeChangeStart (in run) to check if the user is logged in and redirect him to login if not. This works fine. But, I can access the login page via the url, I want to send the user to the dashboard if he's already logged in. What is the proper way to do this?

Rutwick Gangurde
  • 4,772
  • 11
  • 53
  • 87
  • Check if the user is already logged inside the $routeChangeStart and redirect it if necessary – originof Sep 24 '14 at 08:33
  • I'm already using that! But how do I check if I'm loading up the login page itself? – Rutwick Gangurde Sep 24 '14 at 08:34
  • Okay, $locationChangeStart works, thanks! But if this the standard way of doing what I'm trying? – Rutwick Gangurde Sep 24 '14 at 08:49
  • Possible duplicate of [How to avoid showing login page if already logged on with angularjs?](http://stackoverflow.com/questions/23876817/how-to-avoid-showing-login-page-if-already-logged-on-with-angularjs) – T J Nov 25 '15 at 17:59

2 Answers2

1

Guys try this elegant solution:

.run(function ($rootScope, $location, authService) {
        $rootScope.$on('$stateChangeStart', function (ev, to, toParams, from, fromParams) {
            if (to.requireAuth && !authService.isAuthed()) {
                $location.path("/login");
            }
            else if (to.name == 'login' && authService.isAuthed()) {
                ev.preventDefault();
                $location.path("/dashboard");
            }
        });
    })
  • if the user is not logged in and login is required it redirect to login.
  • if the user try to get to login and he already logged in, prevent him from doing it.
  • mark every path as "requireAuth" and it will work.
  • place your code in app.js
Liad Livnat
  • 7,435
  • 16
  • 60
  • 98
0

Try

$rootScope.$on('$locationChangeStart', function(event, newUrl, oldUrl) {}); 

Details here https://docs.angularjs.org/api/ng/service/$location

originof
  • 795
  • 1
  • 7
  • 24