Secbone / koa-session2

Middleware for Koa2 to get/set session
MIT License
152 stars 30 forks source link

修改存在的session,不会自动同步到redis #38

Closed chaoxihailing closed 7 years ago

chaoxihailing commented 7 years ago

example.js

const Koa = require("koa");
const session = require("koa-session2");
const Store = require("./Store.js");
const Router = require('koa-router');
const fs = require('fs')
const captcha = require("trek-captcha")

const Redis = require('ioredis')
const redis = new Redis({
    port: 6379,          // Redis port
  host: '127.0.0.1',   // Redis host
  family: 4,           // 4 (IPv4) or 6 (IPv6)
  db: 0
    });

const app = new Koa();
// body parser
const bodyParser = require('koa-bodyparser')
app.use(bodyParser())

let router = new Router();
app.use(session({
    store: new Store(),
}));

async function run(){
    const {token, buffer} = await captcha();
    console.log(token, buffer)
}

// 请求表单
router.get('/', async (ctx, next) => {
    ctx.response.body = `<h1>Index</h1>
        <form action="/signin" method="post">
            <p>Name: <input name="name" value="koa"></p>
            <p>Password: <input name="password" type="password"></p>
            <p><input type="submit" value="Submit"></p>
        </form>`;
})

// 表单处理
let count = 1;

router.post('/signin', async (ctx, next) => {
     ctx.session = {
            count: count,
            name: "bob"
        }
    var
        name = ctx.request.body.name || '',
        password = ctx.request.body.password || '';
    console.log(`signin with name: ${name}, password: ${password}`);
    if (name === 'koa' && password === '12345') {
        ctx.response.body = `<h1>Welcome, ${name}!</h1>`;
    } else {
          redis.get('failcountuser:1234').then((result) => {
            let resultData = JSON.parse(result);
            ctx.session.user = "test1";
            let user = ctx.session.user;
            console.log(resultData.count);
            console.log(user);
            console.log(ctx.session);
        });
    }
})

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

app.listen(3000)
console.log('[demo] session is starting at port 3000')

Store.js

const Redis = require("ioredis");
const { Store } = require("koa-session2");
class RedisStore extends Store {
    constructor() {
        super();
        this.redis = new Redis({
            port: 6379,
            host: "127.0.0.1",
            family: 4,
            db: 0,
        }
        );
    }

    async get(sid) {
        let data = await this.redis.get(`SESSION:${sid}`);
        return JSON.parse(data);
    }

    async set(session, { sid =  this.getID(24), maxAge = 1000000 } = {}) {
        try {
            // Use redis set EX to automatically drop expired sessions
            // await this.redis.set(`SESSION:${sid}`, JSON.stringify(session), 'EX', maxAge / 1000);
            await this.redis.set(`failcountuser:1234`, JSON.stringify(session), 'EX', maxAge / 10);
        } catch (e) {}
        return sid;
    }

    async destroy(sid) {
        return await this.redis.del(`SESSION:${sid}`);
    }
}

module.exports = RedisStore;

然后我在redis-cli查看failcountuser:1234,没有看见user:test1这个字段