54 lines
1.3 KiB
TypeScript
54 lines
1.3 KiB
TypeScript
import { Inject, Injectable } from '@nestjs/common';
|
|
import { Repository } from 'typeorm';
|
|
import { UserToken, UserTokenType } from '../user-token/user-token.entity';
|
|
import { TokenService } from 'src/modules/utility/services/token.service';
|
|
import { User } from '../user/user.entity';
|
|
|
|
@Injectable()
|
|
export class UserTokenService {
|
|
constructor(
|
|
@Inject('USER_TOKEN_REPOSITORY')
|
|
private userTokenRepository: Repository<UserToken>,
|
|
private token: TokenService,
|
|
) {}
|
|
|
|
public async create(
|
|
user: User,
|
|
type: UserTokenType,
|
|
expiresAt?: Date,
|
|
): Promise<UserToken> {
|
|
const token = new UserToken();
|
|
token.token = this.token.generateString(64);
|
|
token.user = user;
|
|
token.type = type;
|
|
token.expires_at = expiresAt;
|
|
await this.userTokenRepository.save(token);
|
|
return token;
|
|
}
|
|
|
|
public async get(token: string, type: UserTokenType): Promise<UserToken> {
|
|
const foundOne = await this.userTokenRepository.findOne({
|
|
where: {
|
|
token,
|
|
type,
|
|
},
|
|
relations: ['user'],
|
|
});
|
|
|
|
if (!foundOne) {
|
|
return null;
|
|
}
|
|
|
|
if (foundOne.expires_at < new Date()) {
|
|
await this.userTokenRepository.remove(foundOne);
|
|
return null;
|
|
}
|
|
|
|
return foundOne;
|
|
}
|
|
|
|
public async delete(token: UserToken): Promise<void> {
|
|
await this.userTokenRepository.remove(token);
|
|
}
|
|
}
|