2024-10-02 10:54:35 -04:00
|
|
|
import { Injectable } from '@nestjs/common';
|
2024-04-27 16:45:16 -04:00
|
|
|
import { DateTime } from 'luxon';
|
2024-10-31 13:42:58 -04:00
|
|
|
import { OnJob } from 'src/decorators';
|
2024-04-19 06:47:29 -04:00
|
|
|
import { AuthDto } from 'src/dtos/auth.dto';
|
|
|
|
|
import { SessionResponseDto, mapSession } from 'src/dtos/session.dto';
|
2025-02-11 17:15:56 -05:00
|
|
|
import { JobName, JobStatus, Permission, QueueName } from 'src/enum';
|
2024-10-02 10:54:35 -04:00
|
|
|
import { BaseService } from 'src/services/base.service';
|
2024-04-19 06:47:29 -04:00
|
|
|
|
|
|
|
|
@Injectable()
|
2024-10-02 10:54:35 -04:00
|
|
|
export class SessionService extends BaseService {
|
2024-10-31 13:42:58 -04:00
|
|
|
@OnJob({ name: JobName.CLEAN_OLD_SESSION_TOKENS, queue: QueueName.BACKGROUND_TASK })
|
|
|
|
|
async handleCleanup(): Promise<JobStatus> {
|
2024-04-27 16:45:16 -04:00
|
|
|
const sessions = await this.sessionRepository.search({
|
|
|
|
|
updatedBefore: DateTime.now().minus({ days: 90 }).toJSDate(),
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
if (sessions.length === 0) {
|
|
|
|
|
return JobStatus.SKIPPED;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
for (const session of sessions) {
|
|
|
|
|
await this.sessionRepository.delete(session.id);
|
|
|
|
|
this.logger.verbose(`Deleted expired session token: ${session.deviceOS}/${session.deviceType}`);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
this.logger.log(`Deleted ${sessions.length} expired session tokens`);
|
|
|
|
|
|
|
|
|
|
return JobStatus.SUCCESS;
|
|
|
|
|
}
|
|
|
|
|
|
2024-04-19 06:47:29 -04:00
|
|
|
async getAll(auth: AuthDto): Promise<SessionResponseDto[]> {
|
|
|
|
|
const sessions = await this.sessionRepository.getByUserId(auth.user.id);
|
|
|
|
|
return sessions.map((session) => mapSession(session, auth.session?.id));
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
async delete(auth: AuthDto, id: string): Promise<void> {
|
2024-10-10 11:53:53 -04:00
|
|
|
await this.requireAccess({ auth, permission: Permission.AUTH_DEVICE_DELETE, ids: [id] });
|
2024-04-19 06:47:29 -04:00
|
|
|
await this.sessionRepository.delete(id);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
async deleteAll(auth: AuthDto): Promise<void> {
|
|
|
|
|
const sessions = await this.sessionRepository.getByUserId(auth.user.id);
|
|
|
|
|
for (const session of sessions) {
|
|
|
|
|
if (session.id === auth.session?.id) {
|
|
|
|
|
continue;
|
|
|
|
|
}
|
|
|
|
|
await this.sessionRepository.delete(session.id);
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|