Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

reloading the page signs the user out #18

Open
ali-web opened this issue Feb 12, 2016 · 17 comments
Open

reloading the page signs the user out #18

ali-web opened this issue Feb 12, 2016 · 17 comments

Comments

@ali-web
Copy link

ali-web commented Feb 12, 2016

@hwz
It seems that the sessions created in this app are not persistent and every time I reload the page, the user automatically becomes signed out. Also tried this suggestion of using connect-mongo module, but didn't work:
http://stackoverflow.com/questions/29721225/staying-authenticated-after-the-page-is-refreshed-using-passportjs

@Beatusvir
Copy link

@aliwebir yeah I've been trying to get session working but there are so many implementations I'm still finding ways how is not done ;)

@Beatusvir
Copy link

@aliwebir
So after really discovering all the wrong ways to do this, I finally got a solution using cookies.

angular.module('yourApp')
  .controller('authController', function ($scope, $http, $rootScope, $location, $cookies) {
...
$scope.login = function () {
      $http.post('/auth/login', $scope.user).success(function (data) {
        if (data.state == 'success') {
          $cookies.put('user', JSON.stringify(data.user))
          $rootScope.authenticated = true
          $rootScope.current_user = data.user
          $location.path('/')
        } else {
          $scope.error_message = data.message
        }
      })
    }
...
  • Add a routeChangeStart listener to the module to check if the cookie has user information
var app = angular.module('yourApp', ['ngRoute', 'ngResource', 'ngCookies'])
.run(function ($rootScope, $http, $location, $cookies) {
...
$rootScope.$on('$routeChangeStart', function (event, next, current) {
      var user = JSON.parse($cookies.get('user'))
      if (user === null) {
        if (next.templateUrl === 'views/auth/login.html') {
        } else {
          $location.path('/login')
        }
      } else {
        $rootScope.authenticated = true
        $rootScope.current_user = user
      }
    })
...
}

Hope this helps, can't believe all the time it took to do this hahaha, later!

@ryand626
Copy link

This helps a lot, but I think you still need to edit the cookie when the user logs out.

@Beatusvir
Copy link

@ryand626 Oh of course! I noticed that after I posted here but forgot to edit this xD

@kunalnaik
Copy link

@Beatusvir thanks for the solution! However I believe you are bypassing the register page. How does the next.templateUrl === 'views/auth/login.html' conditional work? Is that a path we set somewhere? I am trying to recreate it with register.html but cannot get it to work.

@Beatusvir
Copy link

Beatusvir commented Jul 26, 2016

@kunalnaik Let me check it out. I should have the code somewhere to see what I did (and if I did something about it hahahah)

Edit. mmm nothing here on github, thought I forked it 😞, I'll check @ home later see what I can find.

@kunalnaik
Copy link

Hey @Beatusvir, did you find anything?

@Beatusvir
Copy link

@kunalnaik I forgot 😞 ... I added an alarm now! I'm about to head home, I should respond in about 3 hours (need to get something to eat 😄)

@Beatusvir
Copy link

@kunalnaik I can't find my modified code. All I see is some incomplete chirp code 😭.
FWIR the (next.templateUrl === 'views/auth/login.html') (notice is after user cookie is null). What I mean with that is, if the user cookie is null it means the user is not authenticated, so, unless the next route is login (so he can actually, login) I will redirect to login. If user is not null I set rootscope variable of user so I can in other routes just check for that rootscope value. I'm not sure if I made myself clear.

@kunalnaik
Copy link

Darn. And yep I understood your logic, and it does work! However my thinking is that it doesn't really matter if the user is going to the login page since we are redirecting them there anyways, and rather that it is important to check if the user is attempting to go the the Register page so they can create a new account. Here is my code:

`// checks for authentication on page refresh
$rootScope.$on('$locationChangeStart', function (event, next, current) {
// var for user stored in session cookie
var user = '';
if(typeof $cookies.get('user') == 'string') {
user = JSON.parse($cookies.get('user'));
}

    console.log("tried to grab cookie");
    // no logged in user, we should be going to #login
    if (user == '') {
        console.log("not auth'd");
        $rootScope.authenticated = false;
        $rootScope.current_user = '';
        if (next.templateUrl === 'views/auth/register.html') {
            // if link is to register page, allow
            console.log("directing to register");
        }
        else {  // otherwise redirect to login
            console.log("redirecting to login");
            $location.path('/login');
        }
    }
    // logged in session exists, set current user as authenticated
    else {
        console.log("yes, auth'd");
        $rootScope.authenticated = true;
        $rootScope.current_user = user;
        // $location.path('/');
    }
});`

With this, I get redirected to the login page if not auth'd. However this also applies to the register page so i am never able to create a new account :( . Any ideas? (also apologies for the weird formatting, couldn't get it right)

@Beatusvir
Copy link

Mmm can't recall, I may have done something about it but not sure. Or maybe I just got cookies working for auth and didn't even notice register wasn't working lol. It wasn't for a project or anything so not sure how far I got it.

@kunalnaik
Copy link

Oh ok, thanks for checking it out though! Do you know what the 'views/auth/login.html' path points to? Is that where you placed your login.html partial or is it something related to the authentication.js api? That's where I am most confused and don't know how to replicate it for the Register page.

@Beatusvir
Copy link

Yes that was for the login.html page. I remember I did something similar @ work for a custom login controller (C# MVC). Every time the URL changes, if it's not for login / register I redirect. Here is a screenshot:
mvc-auth

In short: If the controller where the user is trying to redirect is not Account, where both login and register are, I'll check if he's authenticated with a session value and redirect accordingly. There is another validation there but is related to some permission for an admin page.

@kunalnaik
Copy link

OK I figured it out. The issue was that next.templateUrl was undefined for me, and instead simply next provided the URL we wanted. So I just checked the next for 'register' instead of checking if next.templatUrl equaled the url for register. Here is my code (in case anyone else needs it):
`
$rootScope.$on('$locationChangeStart', function (event, next, current) {
// var for user stored in session cookie
var user = '';
if(typeof $cookies.get('user') == 'string') {
user = JSON.parse($cookies.get('user'));
}

    console.log("tried to grab cookie");
    // no logged in user, we should be going to #login
    if (user == '') {
        $rootScope.authenticated = false;
        $rootScope.current_user = '';
        if (next.includes('register')) {
            // if link is to register page, allow
            console.log("not auth'd, directing to register");
        }
        else {  // otherwise redirect to login
            console.log("not auth'd, redirecting to login");
            $location.path('/login');
        }
    }
    // logged in session exists, set current user as authenticated
    else {
        console.log("yes, auth'd");
        $rootScope.authenticated = true;
        $rootScope.current_user = user;
        // $location.path('/');
    }
});`

Again, apologies for the formatting. Cheers.

@Beatusvir
Copy link

Great! 👍 Hopefully people will be able to fully implement this system because these guys just dropped that half baked code here and didn't look back.

@sidharth016
Copy link

Good Thread..!! I initially encountered it.
The above code works..
Just a small change
declare
$rootScope.current_user = user.username;

@INHUMANEprimate
Copy link

kunalnaik solution is spot on... except I couldn't get my user to ever logout. So I add some code to the sign out function to remove the cookie. After that, everything worked as intended.

$rootScope.signout = function(){
    console.log('Got into signout');
    if(typeof($cookies.get('user')) == 'string') {
      $http.get('auth/signout');
      $rootScope.authenticated = false;
      $rootScope.current_user = '';
      $cookies.remove('user'); //, { path:'/', domain:'localhost'} this object may be necessary in some situations
      console.log('Got into signout & removed cookie');
    }
  };

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

6 participants