使用session_id从Mongo快速加载会话 [英] Express load Session from Mongo with session_id

查看:50
本文介绍了使用session_id从Mongo快速加载会话的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

嘿,

我正在构建一个(半)REST API,其背面为Nodejs/Express,而正面为Phonegap/Cordova.对于后端,我使用 express connect-mongo 猫鼬 如下:

I'm building a (semi) REST API with Nodejs/Express as back and Phonegap/Cordova as front. For backend i'm using express with connect-mongo and mongoose as following :

express.cookieParser(),
express.session({
    secret: nconf.get('session:salt'),
    store: new mongoStore({url: nconf.get('database').url})
}),

为了在节点上进行会话验证,我在我的 route.js 文件中创建了以下功能

for session validation on node i've create the following function inside my route.js file

var authenticate = function (req, res, next) {

if (req.session.user)
    next();
else
    res.error('access is not authentication');
}

不幸的是,PhoneGap和Cordova不支持现成的Cookie ,所以我使用了 localStorage 存储session_id并包装每个服务器调用,以将其聚集到url参数中.

Unfortunately PhoneGap and Cordova do not support cookies out of the box so i use localStorage to store session_id and wrap every server call to aggregate it to the url params.

是否有任何优雅的方法通过'session_id'参数从我的 authenticate 函数中的mongoDB中预加载会话,而无需为会话集合创建 Schema 并尝试用猫鼬查询吗?

Is there any elegant way to pre-load the session from mongoDB inside my authenticate function by the 'session_id' param without creating a Schema for the session collection and try querying it with mongoose?

干杯

-PK.

推荐答案

使用 mongoStore store.get 方法.尝试这样的事情:

Use the store.get method of your mongoStore. Try something like this:

var authenticate = function (req, res, next) {
  mongoStore.get(req.params.session_id, function (error, session) {
    if (error) {
      res.status(500).send(error);
      return;
    }
  }
  req.session = session;
  next();
}

这篇关于使用session_id从Mongo快速加载会话的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆