Direct to mainpage after login?


#1

I make login with my own API.
When user open the app for the first time, they have to login then direct to mainpage.
How to make user always direct to mainpage after login when they open the app again?
I use

$urlRouterProvider.otherwise('/app/login');

in my app.js.
And how could system know that user aleady login? Did i have to save username or token and check it using localStorage or sessionStorage?

Thank you


#2

Store the state in localstorage --> add a BaseCtrl which is around all our content and other controllers and views.
There you can listen on $stateChangeStart --> if user is already loggedin and the user tries to open a state, which needs no authorization --> make event.preventDefault() and go to your mainpage.

I add custom data to my states, so i can check easily if auth is required.

state('noauthState', {
 url: '/noauth',
 noAuth: true
});

you also can put this on the data object of a state:

state('noauthState', {
 url: '/noauth',
 data: {
   noAuth: true
 }
});

Another approach --> you can work with resolves in your app

So you could execute a api-request like “checkIfuserIsLoggedIn” in you base-state and if he is --> resolve the user objec in other cases resolve nothingt. In the base controller you can handle if the user is loggedIn or not.


#3

Thank you for your reply. I’ll try.
But i have a question. When i use localstorage, why i cant remove it?
It’s still shown on my Chrome console.


#4

try to call window.localStorage.clear() in your chrome javascript console (use the F12 key --> click on console)
refresh the page an the localstorage should be gone.

For working with the localstorage i am using:


#5

How about when i use on device?
Is the localstorage must be gone with window.localStorage.clear()? Or will happen like on browser?


#6

on device it should work like in the browser (and for me it works).


#7

Is it ok if i did not use $stateChangeStart? I try to simplest that i could in my mainpage controller like this. I try on device and it works fine.

//GET USERNAME
$scope.username = localStorage.getItem("display_name");
        if ($scope.username == null) {
            $state.go("app.login");
        };

//LOGOUT
$scope.logout = function(){
            window.localStorage.clear();
            loginService.logout();
        };

#8

yep but i have multiple views where you do not need authentication. And if you manipulate the url you should not be able to access those states.

But it should be okay for your purposes.


#9

When user logout, then they want to login again, why data from old user still shown?

But when the user logout then close the app from multitask, and open the app again then login again, data from old user is gone.

How could to delet old data without close the app? I still using window.localStorage.clear()