简体   繁体   English

如何使用node.js创建会话?

[英]how to create session using node.js?

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. 我想为我的页面创建会话,当提供类似http:// localhost:3000 / pages / profile的URL时,它将无需登录即转到该页面。我现在应该怎么做才能解决此问题。

node.js 的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 的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>

I have a Node.js project with sessions and in my index.js I have the following: 我有一个带有会话的Node.js项目,在我的index.js中,我有以下内容:

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. 如果您不使用MongoDB,则可以删除“ store”元素。 Then it uses the default store which is MemoryStore. 然后,它使用默认存储为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');
  }
}

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... 一种方法是使用express session来存储会话的值,然后使用中间件拦截每条路由,以验证用户是否已登录,就像这样...

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.js

Passport is authentication middleware for Node.js. Passport是Node.js的身份验证中间件。 Extremely flexible and modular, Passport can be unobtrusively dropped in to any Express-based web application. Passport非常灵活和模块化,可以毫不费力地放入任何基于Express的Web应用程序中。 A comprehensive set of strategies support authentication using a username and password, Facebook, Twitter, and more. 一套全面的策略支持使用用户名和密码,Facebook,Twitter等进行身份验证。

See the docs for learn how to use and search here in the stack overflow too. 请参阅文档以了解如何在堆栈溢出中使用和搜索。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM