initial
This commit is contained in:
@@ -0,0 +1,53 @@
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import { InjectRepository } from '@nestjs/typeorm';
|
||||
import { IsNull, LessThan, Repository } from 'typeorm';
|
||||
import { SessionEntity } from '../entities/session.entity';
|
||||
|
||||
@Injectable()
|
||||
export class SessionsRepository {
|
||||
constructor(
|
||||
@InjectRepository(SessionEntity)
|
||||
private readonly repo: Repository<SessionEntity>,
|
||||
) {}
|
||||
|
||||
findActiveById(id: string): Promise<SessionEntity | null> {
|
||||
return this.repo.findOne({
|
||||
where: { id, revokedAt: IsNull() },
|
||||
relations: { user: { roles: { permissions: true }, settings: true } },
|
||||
});
|
||||
}
|
||||
|
||||
listForUser(userId: string): Promise<SessionEntity[]> {
|
||||
return this.repo.find({ where: { userId }, order: { createdAt: 'DESC' } });
|
||||
}
|
||||
|
||||
save(session: SessionEntity): Promise<SessionEntity> {
|
||||
return this.repo.save(session);
|
||||
}
|
||||
|
||||
async revoke(sessionId: string): Promise<void> {
|
||||
await this.repo.update({ id: sessionId }, { revokedAt: new Date() });
|
||||
}
|
||||
|
||||
async revokeAllForUser(
|
||||
userId: string,
|
||||
exceptSessionId?: string,
|
||||
): Promise<void> {
|
||||
const sessions = await this.repo.find({
|
||||
where: { userId, revokedAt: IsNull() },
|
||||
});
|
||||
const now = new Date();
|
||||
await this.repo.save(
|
||||
sessions
|
||||
.filter((session) => session.id !== exceptSessionId)
|
||||
.map((session) => ({ ...session, revokedAt: now })),
|
||||
);
|
||||
}
|
||||
|
||||
async cleanupExpired(now = new Date()): Promise<void> {
|
||||
await this.repo.delete([
|
||||
{ expiresAt: LessThan(now) },
|
||||
{ absoluteExpiresAt: LessThan(now) },
|
||||
]);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user