【发布时间】:2017-06-17 07:22:43
【问题描述】:
我有这个单页应用程序,当用户成功通过身份验证并重定向到仪表板时,它会发出 7 个 ajax http 请求。当用户登录护照进行身份验证并创建会话时,将重定向到仪表板。当仪表板加载时,它会对服务器进行 7 次 ajax 调用以获取用户数据。在本地主机上它工作正常,但是当这个应用程序部署在远程云上时服务器,如果我使用智能平板或 Windows 10 等 Android 设备访问该站点,它仍然可以按预期工作,但是在成功验证并重定向到仪表板后使用 Windows 7 和 8,那些假设获取用户数据的 ajax 调用不起作用。当我在远程服务器上控制 req.user 时,它在该端点内显示未定义。似乎会话未设置或已销毁。
这里是代码
'use strict';
require('dotenv').config();
var express = require('express');
var path = require("path");
var multer = require('multer');
var bodyParser = require('body-parser');
var router = express.Router();
var session = require('express-session');
var passport = require('passport');
var flash = require('connect-flash');
var cookieParser = require("cookie-parser");
var MongoDBStore = require('connect-mongodb-session')(session);
var configuration = function (app,model) {
//config
var storeDB = process.env.MONGODB_ADDON_URI || "mongodb://127.0.0.1:27017/mydb";
var store = new MongoDBStore(
{
uri: storeDB,
collection: 'mySessions'
});
app.use('/assets',express.static(__dirname + '/public'));
//middleware
app.use(cookieParser('anything'));
app.use(session({
secret: 'anything',
store: store,
resave: true,
saveUninitialized: true,
cookie: {
httpOnly: true,
originalMaxAge: 35999998,
path: "/",
}
}));
app.use(passport.initialize());
app.use(passport.session());
app.use(flash());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use(multer({dest: './uploads'}).any());
app.use(function(req, res, next) {
res.header('Access-Control-Allow-Credentials', true);
res.header('Access-Control-Allow-Origin', req.headers.host);
res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
res.header('Access-Control-Allow-Headers', 'X-Requested-With, X-
HTTP-Method-Override, Content-Type, Accept');
if ('OPTIONS' == req.method) {
res.send(200);
} else {
next();
}
});
passport.serializeUser(function(user, done) {
done(null, user._id);
});
passport.deserializeUser(function(id, done) {
model.user.findById(id, function(err, user) {
done(err, user);
});
});
app.set('view engine', 'ejs');
app.set('views', __dirname + '/views');
app.use('/',router);
}
module.exports = {
configuration: configuration,
router: router,
passport: passport
}
//the login strategy
"use strict";
var LocalStrategy = require("passport-local").Strategy;
var path = require('path');
var config = require('./config');
var salt = require('./salt');
var router = config.router;
var passport = config.passport;
passport.use('user-login', new LocalStrategy({
usernameField : 'email',
passwordField : 'password',
passReqToCallback : true
},
function (req, email, password, done) {
// find a user whose email is the same as the forms email
// we are checking to see if the user trying to login already exists
model.user.findOne({ email : email }, function(err, user) {
// if there are any errors, return the error before anything else
if (err) {
return done(err);
}
// if no user is found, return the message
if (!user) {
return done(null, false, req.flash('loginMessage', 'No user found.'));
// req.flash is the way to set flashdata using connect-flash
}
// if the user is found but the password is wrong
if (!salt.isValidPassword(user,password)) {
return done(null, false, req.flash('loginMessage', 'Oops! Wrong password.')); // create the loginMessage and save it to session as flashdata
}
return done(null, user);
});
}));
router.post('/user/login', passport.authenticate('user-login', {
successRedirect : '/dashboard', // redirect to the secure profile section
failureRedirect : '/failed', // redirect back to the signup page if there is an error
failureFlash : true // allow flash messages
}));
router.get('/dashboard',function(req,res){
if(req.user){
model.user.findOne({user_id: req.user.user_id},
{presence:1,set_presence:1}).exec(function(err,data){
data.presence = true;
data.set_presence.general = true;
data.save(function(err,info){
console.log("presence is true");
});
});
res.json({
isLoggedIn: true,
typeOfUser: req.user.type,
firstname: req.user.firstname,
lastname:req.user.lastname,
phone: req.user.phone,
email: req.user.email,
title: req.user.title,
user_id: req.user.user_id,
balance: req.user.ewallet.available_amount,
profile_pic_url: req.user.profile_pic_url
});
} else {
res.redirect("/login");
}
});
router.get("/dashboard/patient",function(req,res){
if(req.user){
res.render("patient",{"userInfo": req.user});
} else {
res.redirect('/login');
}
});
router.get('/failed',function(req,res){
res.send(false);
})
//route
//user getting the available on the dashboard balance route.
router.get('/dashboard/:userId/get-balance',function(req,res){
console.log(req.user) //undefined
if(req.user){
model.user.findOne({user_id: req.params.userId},{ewallet:1},function(err,wallet){
if(err) throw err;
res.send({balance: wallet.ewallet.available_amount})
})
} else {
res.send("Unauthorized access!!!")
}
});
//Angular code
app.controller('loginController',["$scope","$http","$location","$window","$resource","ModalService","templateService","localManager",
"$rootScope","mySocket",function($scope,$http,$location,$window,$resource,ModalService,templateService,localManager,$rootScope,mySocket) {
$scope.login = {};
$scope.error = "";
$scope.send = function(){
var login = $resource('/user/login',null,{logPerson:{method:"POST",headers:{withCredentials: true}}});
login.logPerson($scope.login,function(data){
console.log(data)
localManager.setValue("resolveUser",data);
//$rootScope.balance = data.balance;
if (data.isLoggedIn) {
//user joins a room in socket.io and intantiayes his own socket
switch(data.typeOfUser) {
case "Patient":
createAwareness(data)
$window.location.href = '/dashboard/patient';
break;
case "Doctor":
createAwareness(data)
$window.location.href = "/dashboard/doctor";
break;
case "Pharmacy":
$window.location.href = "/medical-center/pharmacy";
break;
default:
$window.location.href = "/medical-center/view";
break;
}
} else {
$scope.error = "Email or Password incorrect!";
}
});
}
//this updates the current availability of user in real time.
function createAwareness(data) {
mySocket.emit("set presence",{status:"online",userId:data.user_id},function(response){
if(response.status === true){
if(data.typeOfUser === "Doctor"){
mySocket.emit("doctor connect",{userId:data.user_id});
} else if(data.typeOfUser === "Patient") {
mySocket.emit("patient connect",data);
}
}
});
}
}]);
//one of the ajax get requests made from within dashboard as the page loads.
app.controller("balanceController",["$rootScope","$resource","localManager",function($rootScope,$resource,localManager){
var user = localManager.getValue("resolveUser");//this was set in the login controller
var amount = $resource('/dashboard/:userId/get-balance',{userId: user.user_id});
var wallet = amount.get(null,function(data){
console.log(data) //"unauthorized access !!!"
var format = "N" + data.balance.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
$rootScope.balance = format;
})
}]);
<!-- login form -->
<form>
<input type="text" placeholder="Email" ng-model = "login.email" style="border: 1px solid rgba(0,255,0,0.8)">
<input type="password" placeholder="Password" ng-model = "login.password" style="border: 1px solid rgba(0,255,0,0.8);margin: 10px 0px">
<div style="text-align: center">
<button class="btn btn-login" ng-click="send()" style="color: #fff;">LOGIN</button>
</div>
</form>
【问题讨论】:
标签: angularjs node.js socket.io passport.js express-session