我认为一个可能的解决方案是在LocalAuthGuard的canActivate方法中使用REQUEST.session.save(),以确保在更改maxAge和ttl后正确保存会话。您可以尝试以下更改:
@Injectable()
export class LocalAuthGuard extends AuthGuard('local'){
async canActivate(context: ExecutionContext){
const REQUEST = context.switchToHttp().getRequest()
const RESPONSE = context.switchToHttp().getResponse()
const BODY = plainToClass(LoginBody, REQUEST.body)
const ERRORS = await validate(BODY)
const ERR_MESSAGES = ERRORS.flatMap(({ constraints }) =>
Object.values(constraints),
);
if(ERR_MESSAGES.length > 0)
RESPONSE.status(404).send(buildResponse(404, 'There are some errors', ERR_MESSAGES))
REQUEST.sessionStore.ttl = BODY.rememberMe ? 60 * 60 : 60
REQUEST.session.cookie.maxAge = BODY.rememberMe ? 60 * 60 * 1000 : 60 * 1000
// Save the session after modifying ttl and maxAge
REQUEST.session.save(err => {
if (err) {
console.error(err);
}
});
// return 3600 as expected
console.log( REQUEST.sessionStore.ttl)
/**
return as expected
cookie: {
path: '/',
',
_expires: 2023-06-20T00:24:26.712Z,
originalMaxAge: 3600000,
httpOnly: true,
secure: false,
sameSite: true
}
*/
console.log( REQUEST.session.cookie)
const RESULT = (await super.canActivate(context)) as boolean
await super.logIn(REQUEST)
return RESULT
}
}
另一种解决方案是,在调用super.logIn(REQUEST)后尝试设置maxAge和ttl。:
@Injectable()
export class LocalAuthGuard extends AuthGuard('local'){
async canActivate(context: ExecutionContext){
const REQUEST = context.switchToHttp().getRequest()
const RESPONSE = context.switchToHttp().getResponse()
const BODY = plainToClass(LoginBody, REQUEST.body)
const ERRORS = await validate(BODY)
const ERR_MESSAGES = ERRORS.flatMap(({ constraints }) =>
Object.values(constraints),
);
if(ERR_MESSAGES.length > 0)
RESPONSE.status(404).send(buildResponse(404, 'There is some errors', ERR_MESSAGES))
const RESULT = (await super.canActivate(context)) as boolean
await super.logIn(REQUEST)
REQUEST.sessionStore.ttl = BODY.rememberMe ? 60 * 60 : 60
REQUEST.session.cookie.maxAge = BODY.rememberMe ? 60 * 60 * 1000 : 60 * 1000
// Save the session after modifying ttl and maxAge
REQUEST.session.save(err => {
if (err) {
console.error(err);
}
});
// return 3600 as expected
console.log( REQUEST.sessionStore.ttl)
/**
return as expected
cookie: {
path: '/',
_expires: 2023-06-20T00:24:26.712Z,
originalMaxAge: 3600000,
httpOnly: true,
secure: false,
sameSite: true
}
*/
console.log( REQUEST.session.cookie)
return RESULT
}
}