How can I check if a user is already logged in? (everyauth, node.js)

4.9k Views Asked by At

Up until now I've been using client-side auth. I just set up server-side everyauth and it is working great but how can I do something like FB.getLoginStatus(what I did client-side) when the page loads?

If the user is already logged in I dont want to put them through the process again.

Thanks for explaining!

3

There are 3 best solutions below

0
Benny Tjia On

I would do something like this on node.js:

var userlogin = function () {
       var req = this.request
          ,res = this.response
          ,login = req.body
          ,username = login.username
          ,password = login.password;

      if(username === 'tester' && password === '12345'){
         req.session.user_id = xxxxxx;
         res.redirect('/');
      }else{
        res.redirect('/login');
      }

    }
    var checkAuth = function(fn_auth, fn_unauth){
      var req = this.request
          ,res = this.response
          ,unauthCallback;

      if(req.session.user_id){
        fn_auth(); //execute fn_auth if user is logged in. callback can be set to redirect to root path '/'
      }else{
          fn_unauth(); //execute fn_unauth calback which bring user to login path '/login'
        } 
      }
    }

Basically just redirect when the user is already logged in. Hope that helps?

3
Jesse Fulton On

From the documentation

everyauth also provides convenience methods on the ServerRequest instance req. From any scope that has access to req, you get the following convenience getters and methods:

req.loggedIn - a Boolean getter that tells you if the request is by a logged in user

req.user - the User document associated with the session

req.logout() - clears the sesion of your auth data

Within Express Views:

If you are using express, everyauth comes with some useful dynamic helpers. To enable them:

var express = require('express')
, everyauth = require('everyauth') 
, app = express.createServer();
everyauth.helpExpress(app); 

Then, from within your views, you will have access to the following helpers methods attached to the helper, everyauth:

everyauth.loggedIn
0
Anmol Saraf On

In case you are using Jade template, user's login status can be checked by following code inside a .jade file, for example - home.jade

if (!everyauth.loggedIn) // <-----
    a(href="/your_url_here/") log in with facebook
else
    p Welcome <username>