1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
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<Session>,
) {}
async findOne(key: string): Promise<Session | null> {
return await this.sessionRepository.findOneBy({ token: key });
}
async findValid(token: string): Promise<Session | null> {
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<Session | null> {
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<boolean> {
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;
}
}
|