我想在环回中使用redis进行会话,但是代码中没有req。
服务器/ server.js
var redis = require("redis");
var session = require('express-session');
var redisStore = require('connect-redis')(session);
var client = redis.createClient();
var app = module.exports = loopback();
app.use(session({
secret: '0`3VTw;hQ|3/`:95ZYu{0J82O>{}7JC/',
// create new redis store.
store: new redisStore({ host: 'localhost', port: 6379, client: client,ttl : 260}),
saveUninitialized: false,
resave: false
}));
我想在环回应用程序上实现基于Redis的快速会话,但是我无法在不自己编写整个路由控制器的情况下找到方法。
我正在扩展模型并创建一个remoteMethod(),但我无法访问" req"以任何方式。
这是我的TrmptUsers模型代码(见第3行)
公共/模型/ trmpt-users.js
module.exports = function(TrmptUsers) {
TrmptUsers.login = function(username, password, cb) {
console.log(TrmptUsers.app.session); //i want access to req variable to work with redis here.
var ursalt = security.gen_salt(username);
password = security.decrypt256(password, ursalt);
TrmptUsers.findOne({fields:{usrPwd:true,usrAccessToken:true},where:{and:[{usr_username:username}]}},function(err,result){
security.verifyPassword(password, result.usrPwd, function(err, verify) {
if (verify) {
User.generateVerificationToken(username, cb)
cb(null,result.usrAccessToken);
}
else {
cb({status:401,message:"Invalid Username/Password"},null);
}
});
});
}
TrmptUsers.remoteMethod(
'login',
{
accepts: [
{arg: 'username', type: 'string', required: 'true'},
{arg: 'password', type: 'string', required: 'true'},
],
returns: {arg: 'accesstoken', type: 'string'}
}
);
};
答案 0 :(得分:7)
我很久以前找到了解决我所有问题的方法,因为有人投了票,我想他们可能想要答案,所以我在这里发帖。
服务器/ server.js
var redis = require("redis");
var session = require('express-session');
var redisStore = require('connect-redis')(session);
app.use(session({
secret: 'hello',
store: new redisStore({ host: 'localhost', port: 6379, client: client,ttl : 3600}),//1 hour
saveUninitialized: false,
resave: false
}));
然后在创建模型slc:loopback model
时,您可以选择将req对象添加到参数中。
模型specific.json
...
"methods": {
"userLogin": {
"isStatic": true,
"accepts": [
{
"arg": "req",
"type": "object",
"required": true,
"description": "",
"http": {
"source": "req"
}
},
{
"arg": "username",
"type": "string",
"required": true,
"description": "Username"
},
{
"arg": "password",
"type": "string",
"required": true,
"description": "Password"
}
],
"returns": [
{
"arg": "accessToken",
"type": "string",
"root": false,
"description": ""
}
],
...
然后以您想要的任何方式使用req.session,并记住首先安装redis-server。