gpt4 book ai didi

node.js - 如何使用node.js创建 session ?

转载 作者:太空宇宙 更新时间:2023-11-04 00:44:02 27 4
gpt4 key购买 nike

当给出像 http://localhost:3000/pages/profile 这样的 url 时,我想为我的页面创建 session 。它会在没有登录的情况下进入该页面。我现在应该做什么来解决这个问题。

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);
});
};
}

登录.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>

最佳答案

我有一个带有 session 的 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());

如果您不使用 MongoDB,您可以删除“store”元素。然后它使用默认存储MemoryStore。

要防止未经身份验证的用户访问页面,您可以这样做:

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');
}
}

关于node.js - 如何使用node.js创建 session ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35577862/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com