I'm new to AngularJS, and now I'm trying to build my first system with authentication. Everything works, except, when a user refreshes the page, all the user info is gone...
I followed this tutorial:
http://www.sitepoint.com/implementing-authentication-angular-applications/
Now this is how I tend to make sure the user data stays where its supposed to be:
When a user logs in, my API returns his/hers details in JSON, which then is dropped into both a $rootScope variable for use in the site, and also in a session. Next to that, I have a variable in the rootscope that returns true when signed in, and false when not, like this:
$rootScope.loggedin = true;
$rootScope.user = data;
$window.sessionStorage["info"] = data;
// console.log($window.sessionStorage["info"]);
This all happens in the Authentication factory.
Then when a user refreshes, and that same factory is ran once again, the following function will start to work:
function init() {
if ($window.sessionStorage["info"]) {
$rootScope.loggedin = true;
$rootScope.user = $window.sessionStorage["info"];
info = $window.sessionStorage["info"];
}
}
init();
(I think this will work because that article and various other sources on the web said so.)
Then in my HTML, I use the loggedin variable to determine if a user is logged in:
<div ng-show="!loggedin">
<a href="/login" class="btn btn-default btn-flat sidebar-toggle" style="position:relative;top:-3px; right: 5px;">Log in </a>
<a class="btn btn-default btn-raised" style="background: #03A9F4; color:#fff; position:relative;top:-3px; right: 5px;">Registreer</a>
</div>
<div ng-show="loggedin">
<ul class="nav navbar-nav">
<li class="drop">
<a href="bootstrap-elements.html" data-target="#" class="dropdown-toggle" data-toggle="dropdown">{{user.username}} <b class="caret"></b></a>
<ul class="" style="z-index:99999999999;">
<li><a href="javascript:void(0)">Some log-in only stuff</a></li>
</ul>
</li>
</ul>
</div>
Now all of this works nicely when I log myself in, but when I refresh the page, it detects that I'm logged in, but my name just stays blank, since I guess that $rootScope.user is undefined.
Why is this, and how do I fix it?
Thanks.
useris definitely not a string. You should not guess the value ofuserbut check it.