koa,会话,redis:如何使其发挥作用?

时间:2018-10-22 18:03:56

标签: session redis koa

我正在尝试使用koa,koa-session,koa-redis与服务器端会话实施Firebase身份验证。

我无法理解。在阅读koa会话自述文件时,这对我来说尤其晦涩(link):

  

您可以通过以下三种方法(需要异步功能)传递options.store,将会话内容存储在外部存储(Redis,MongoDB或其他DB)中:

     

get(key,maxAge,{rolling}):按键获取会话对象

     

set(key,sess,maxAge,{滚动,已更改}):使用maxAge(以毫秒为单位)设置密钥的会话对象

     

destroy(key):销毁密钥会话

询问后,我这样做了:

//  middleware/installSession.js
const session = require('koa-session');
const RedisStore = require('koa-redis');
const ONE_DAY = 1000 * 60 * 60 * 24;

module.exports = function installSession(app) {
  app.keys = [process.env.SECRET];

  app.use(session({
    store: new RedisStore({
      url: process.env.REDIS_URL,
      key: process.env.REDIS_STORE_KEY,
      async get(key) {
        const res = await redis.get(key);
        if (!res) return null;
        return JSON.parse(res);
      },

      async set(key, value, maxAge) {
        maxAge = typeof maxAge === 'number' ? maxAge : ONE_DAY;
        value = JSON.stringify(value);
        await redis.set(key, value, 'PX', maxAge);
      },

      async destroy(key) {
        await redis.del(key);
      },
    })
  }, app));
};

然后在我的主要server.js文件中:

// server.js
...
const middleware = require('./middleware');

const app = new Koa();
const server = http.createServer(app.callback());

// session middleware
middleware.installSession(app);

// other middleware, which also get app as a parameter
middleware.installFirebaseAuth(app);
...
const PORT = parseInt(process.env.PORT, 10) || 3000;
server.listen(PORT);
console.log(`Listening on port ${PORT}`);

但是,我如何从其他中间件内部访问会话及其方法?像在installFirebaseAuth中间件中一样,我最终希望获取/设置会话值:

// installFirebaseAuth.js
...

module.exports = function installFirebaseAuth(app) {
  ...
  const verifyAccessToken = async (ctx, next) => {
      ...

      // trying to access the session, none work
      console.log('ctx.session', ctx.session);
      console.log('ctx.session.get():'
      ctx.session.get(process.env.REDIS_STORE_KEY));
      console.log('ctx.req.session', ctx.req.session);
      const redisValue = await ctx.req.session.get(process.env.REDIS_STORE_KEY);
      ...
   }
}

ctx.session返回{}

ctx.session.get()返回ctx.session.get is not a function

ctx.req.session返回undefined

有任何线索吗? 谢谢!

1 个答案:

答案 0 :(得分:1)

对于我来说,它可以工作,希望对您有帮助

const Koa = require('koa')
const app = new Koa()

const Router = require('koa-router')
const router = new Router()

const static = require('koa-static')
const session = require('koa-session')
// const ioredis = require('ioredis')
// const redisStore = new ioredis()
const redisStore = require('koa-redis')
const bodyparser = require('koa-bodyparser')

app.use(static('.'))
app.use(bodyparser())
app.keys = ['ohkeydoekey']
app.use(session({
  key: 'yokiijay:sess',
  maxAge: 1000*20,
  store: redisStore()
}, app))

app.use(router.routes(), router.allowedMethods())

router.post('/login', async ctx=>{
  const {username} = ctx.request.body
  if(username == 'yokiijay'){
    ctx.session.user = username
    const count = ctx.session.count || 0
    ctx.session.code = count
    ctx.body = `wellcome ${username} logged in`
  }else {
    ctx.body = `sorry, you can't login`
  }
})

router.get('/iflogin', async ctx=>{
  if(ctx.session.user){
    ctx.body = ctx.session
  }else {
    ctx.body = 'you need login'
  }
})

app.listen(3000, ()=>{
  console.log( 'app running' )
})