typestack / routing-controllers

Create structured, declarative and beautifully organized class-based controllers with heavy decorators usage in Express / Koa using TypeScript and Routing Controllers Framework.
MIT License
4.41k stars 394 forks source link

Can not save data in session when using @Session() #302

Closed aasailan closed 2 years ago

aasailan commented 7 years ago

I try to svae user info into session , and the code like this:

@Post('/login')
async login(@Session() session, @Req() req: Request, @Body({ required: true }) user: User) {
      const curUser = await this.userSev.login(user.username, user.password);
      return new Promise((resolve, reject) => {
            session.regenerate(() => {
                curUser.emptyPwd();
                session.user = curUser;
                session.success = 'Authenticated as ' + user.username + ' click to <a href="/auth/logout">logout</a>. ' + ' You may now access <a href="/auth/restricted">/restricted</a>.';
                resolve(new MyResponse('success', { user: session.user }));
            });
        });
    }

however, when i check my redis db, the user info is not save in th session. but when i use req,session to save the user info, it work, the code like this:

@Post('/login')
async login(@Req() req: Request, @Body({ required: true }) user: User) {
    const curUser = await this.userSev.login(user.username, user.password);
    return new Promise((resolve, reject) => {
        req.session.regenerate(() => {
            curUser.emptyPwd();
            req.session.user = curUser;
            req.session.success = 'Authenticated as ' + user.username + ' click to <a href="/auth/logout">logout</a>. ' + ' You may now access <a href="/auth/restricted">/restricted</a>.';
            resolve(new MyResponse('success', { user: req.session.user }));
        });
    });
}
MichalLytek commented 7 years ago

All what @Session do is:

case "session":
    if (param.name)
        return request.session[param.name];

    return request.session;

when i check my redis db, the user info is not save in th session

Please show more code, how you bootstrap the app, configure redis session, etc.

aasailan commented 7 years ago

thanks for your reply and this is how I bootstrap the app

import 'reflect-metadata';
import * as express from 'express';
import * as path from 'path';
import * as cookieParser from 'cookie-parser';
import * as bodyParser from 'body-parser';
import * as log4js from 'log4js';
import * as session from 'express-session';
import * as connectRedis from 'connect-redis'; // 针对express-session 和 redis存储的中间件
import { useExpressServer, useContainer } from 'routing-controllers';
import { Container } from 'typedi';

import { logger, sessionConfig, redisConfig } from './config/index';

const app = express();
const RedisStore = connectRedis(session);
sessionConfig.store = new RedisStore({
    host: '127.0.0.1',
    port: 6379,
    ttl: 86400, // 会话保存在redis的时间,单位s
    db: 4,
    pass: '',
    prefix: 'typescript-blog-2.0',
    logErrors: true
});

// 视图设置
app.set('views', path.resolve( 'built', 'client', 'views'));
app.set('view engine', 'jade');

// 挂载中间件
app.use(log4js.connectLogger(logger, {}));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));
app.use(cookieParser());
app.use(session({
    secret: 'peishan',
    name: 'blog.sid', // cookie name
    resave: true, // resave==true的时候,强迫每次链接都会重新设置会话的有效期。为什么不设置为true
    cookie: { // cookie 内容设置
        maxAge: 1000 * 60 * 24 // 一天过期 单位ms
    },
    saveUninitialized: true // stored 设置为true则,每次都为一个为初始化的会话创建一个会话对象
}));
app.use(express.static(path.resolve('built', 'client', 'public')));

useContainer(Container); // 需要设置Container 才能在Controller里面进行注入

const controllerPath = path.resolve('built', 'server', 'controllers', '*.js');
const middlewarePath = path.resolve('built', 'server', 'middlewares', '*.js');

logger.debug('controllerPath', controllerPath);
logger.debug('middlewarePath', middlewarePath);

useExpressServer(app, {
    controllers: [controllerPath],
    middlewares: [middlewarePath],
    defaultErrorHandler: false
});

export default app;
aasailan commented 7 years ago

@19majkel94 I am so sorry, my English is not good,(⁎˃ᴗ˂⁎)

github-actions[bot] commented 4 years ago

Stale issue message

attilaorosz commented 2 years ago

@aasailan This seems to be an issue with express-session itself. The same happens even if you do the following:

myRoute(@Req() req) {
  const session = req.session.
  session.regenerate(() => {
    session.myVar = 'test';
  })
}

So after you assign session to a variable and use regenerate you lose the ability to set session variables.

attilaorosz commented 2 years ago

Closing as stale

github-actions[bot] commented 2 years ago

This issue has been automatically locked since there has not been any recent activity after it was closed. Please open a new issue for related bugs.