我想为我的网页创建会话,当提供类似http://localhost:3000/pages/profile的网址时,它会在没有登录的情况下进入该网页。我现在应该怎么做才能解决这个问题。
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);
});
}
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);
});
};
}
<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>
答案 0 :(得分:1)
我有一个带有会话的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');
}
}
答案 1 :(得分:0)
一种方式是使用express session的会话存储值,然后使用中间件拦截每条路由作为验证用户是否已记录,有些像这样......
中间件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.
拦截路线,记录用户验证:
...
app.get('pages/profile', autentic, controller.function);
...
如果未登录用户,将重定向到主页。
但是,我建议您使用passport.js:
Passport是Node.js的身份验证中间件。非常灵活 和模块化,Passport可以不引人注目地投入任何 基于Express的Web应用程序。一套全面的战略 使用用户名和密码支持身份验证,Facebook, Twitter等等。
请参阅文档以了解如何在堆栈溢出中使用和搜索。