1

I want to create session for my pages, when give a url like http://localhost:3000/pages/profile it will goes to that page without logged in. What should i do now to fix this problem.

node.js

module.exports = function(app, express, passport){
var router = express.Router();

passport.use(new LocalStrategy({
    usernameField: 'username', 
    passwordField: 'password'},
    function(username, password, done) {
        User.findOne({ name : username}, function(err, user) {
            if (!user){
                return done(null, false,{message: 'Incorrect username' });
            } 

            if(user){
                var validPassword = user.comparePassword(password);

                if(!validPassword){
                    return done(null, false,{message: 'Incorrect password' });
                }
            }
            return done(null, user);
        });       
    }
));


router.post('/pages/auth/login', function(req, res, next) {
    passport.authenticate('local', function(err, user, info) {
        if (user === false) {
            console.log("login error ");
            return res.json({
                success:false,
                message: info.message,
            });
        } else {
            console.log("login success");
            return res.json({
                success:true,
                //message: 'Login Success',
            });
        }
    })(req, res, next);
});
  }

controller

function LoginController($http, $location, Auth, $rootScope)
{
    var vm = this;

    vm.submitPost =  function(userData){
        $http({
            url: 'http://localhost:7200/api/pages/auth/login',
            method: 'POST',
            data: userData
        }).then(function(res) {
            if(res.data.success){
                $location.path('/pages/profile');
            } else {
                vm.message=res.data.message;
                $location.path('/pages/auth/login');
            }
        }, function(error) {
            console.log(error);
            alert(error.data);
        });
    };   
}

login.html

<form name="loginForm">
        <div class="alertmessage" >{{vm.message}}</div>
            <md-input-container flex md-no-float>
                <input ng-model="vm.form.username" placeholder="Username" translate
                       translate-attr-placeholder="LOGIN.USERNAME" name="username" required="true">
                       <div ng-messages="loginForm.username.$error" ng-show="loginForm.username.$touched">
                            <div ng-message="required">This field is required</div>
                        </div>
            </md-input-container>


            <md-input-container flex md-no-float>
                <input ng-model="vm.form.password" type="password" placeholder="Password" translate
                       translate-attr-placeholder="LOGIN.PASSWORD" name="password" required="true">
                       <div ng-messages="loginForm.password.$error" ng-show="loginForm.password.$touched">
                            <div ng-message="required">This field is required</div>
                        </div>
            </md-input-container>

            <div class="remember-forgot-password" layout="row" layout-sm="column"
                 layout-align="space-between center">
                <md-checkbox class="remember-me" ng-model="data.cb1" aria-label="Remember Me">
                    <span translate="LOGIN.REMEMBER_ME">Remember Me</span>
                </md-checkbox>

                <a ui-sref="app.pages_auth_forgot-password" class="forgot-password md-accent-color"
                   translate="LOGIN.FORGOT_PASSWORD">Forgot Password?</a>
            </div>

            <md-button class="md-raised md-accent" aria-label="LOG IN" translate="LOGIN.LOG_IN"
                       translate-attr-aria-label="LOGIN.LOG_IN"
                       ng-click="vm.submitPost(vm.form);">
                LOG IN
            </md-button>
        </form>
1
  • Do you use "express-session" in your app? Commented Feb 23, 2016 at 12:48

2 Answers 2

1

I have a Node.js project with sessions and in my index.js I have the following:

var session         = require('express-session');
var MongoStore      = require('connect-mongo')(session);

app.use(session({
  secret: config('session_secret'),
  store: new MongoStore({ mongooseConnection: mongoose.connection }),
  resave: true,
  saveUninitialized: true
}));
app.use(passport.initialize());
app.use(passport.session());

If you don't use MongoDB you can drop the "store" element. Then it uses the default store which is MemoryStore.

To prevent non-authenticated users accessing a page you can do this:

router.get('/secure-page', isLoggedIn, function(req, res) {
  res.json({secure: "page"});
});
function isLoggedIn(req, res, next) {
  // if user is authenticated in the session, carry on
  if (req.isAuthenticated()) {
    return next();
  }
  else {
    // redirect to login page.
    res.redirect('/login');
  }
}
Sign up to request clarification or add additional context in comments.

Comments

0

One way is storage values the session with express session, and then interceptade each route with middleware as verify if user is logged or not, somelike this...

Middleware autentic:

module.exports = function(req, res, next) {
  if(!req.session.user) {
    return res.redirect('/');
  }
  return next();
};

req.session.user is a variable create in session in login controller for storage username.

And intercept the route, verifying with user is logged:

...
app.get('pages/profile', autentic, controller.function);
...

If user is not logged will redirect to home page.

But, I suggest you to use passport.js:

Passport is authentication middleware for Node.js. Extremely flexible and modular, Passport can be unobtrusively dropped in to any Express-based web application. A comprehensive set of strategies support authentication using a username and password, Facebook, Twitter, and more.

See the docs for learn how to use and search here in the stack overflow too.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.