From aeb8b66375335e8c9d6cb9cb0d8d7da3d8b79628 Mon Sep 17 00:00:00 2001 From: Leonardo Bishop Date: Fri, 15 Mar 2024 20:23:41 +0000 Subject: Initial commit --- src/session/service/session.service.ts | 70 ++++++++++++++++++++++++++++++++++ 1 file changed, 70 insertions(+) create mode 100644 src/session/service/session.service.ts (limited to 'src/session/service/session.service.ts') diff --git a/src/session/service/session.service.ts b/src/session/service/session.service.ts new file mode 100644 index 0000000..0712fb0 --- /dev/null +++ b/src/session/service/session.service.ts @@ -0,0 +1,70 @@ +import { Injectable } from '@nestjs/common'; +import { InjectRepository } from '@nestjs/typeorm'; +import { Session } from '../entity/session.entity'; +import { Repository } from 'typeorm'; + +@Injectable() +export class SessionService { + constructor( + @InjectRepository(Session) + private sessionRepository: Repository, + ) {} + + async findOne(key: string): Promise { + return await this.sessionRepository.findOneBy({ token: key }); + } + + async findValid(token: string): Promise { + return await this.sessionRepository + .createQueryBuilder('session') + .where('session.validUntil > :date', { + date: new Date(Date.now()), + }) + .andWhere({ + token: token, + used: false, + }) + .getOne(); + } + + async createSession(validTo: Date): Promise { + const session = new Session(); + session.validUntil = validTo; + + await this.sessionRepository.save(session); + return session; + } + + async isValidSession(token: string) { + return ( + (await this.sessionRepository + .createQueryBuilder('session') + .where('session.validUntil > :date', { + date: new Date(Date.now()), + }) + .andWhere({ + token: token, + used: false, + }) + .getCount()) > 0 + ); + } + + async markSessionAsUsed(token: string): Promise { + const update = await this.sessionRepository + .createQueryBuilder() + .update({ + used: true, + }) + .where('validUntil > :date', { + date: new Date(Date.now()), + }) + .andWhere({ + token: token, + used: false, + }) + .execute(); + + return update.affected > 0; + } +} -- cgit v1.2.3-70-g09d2