2023-04-25 22:19:23 -04:00
|
|
|
import { UserEntity, UserTokenEntity } from '@app/infra/entities';
|
2023-01-31 13:11:49 -05:00
|
|
|
import { Injectable, UnauthorizedException } from '@nestjs/common';
|
2023-04-25 22:19:23 -04:00
|
|
|
import { DateTime } from 'luxon';
|
|
|
|
|
import { LoginDetails } from '../auth';
|
2023-01-31 13:11:49 -05:00
|
|
|
import { ICryptoRepository } from '../crypto';
|
2023-01-27 20:50:07 +00:00
|
|
|
import { IUserTokenRepository } from './user-token.repository';
|
|
|
|
|
|
|
|
|
|
@Injectable()
|
|
|
|
|
export class UserTokenCore {
|
|
|
|
|
constructor(private crypto: ICryptoRepository, private repository: IUserTokenRepository) {}
|
|
|
|
|
|
2023-01-31 13:11:49 -05:00
|
|
|
async validate(tokenValue: string) {
|
|
|
|
|
const hashedToken = this.crypto.hashSha256(tokenValue);
|
2023-04-25 22:19:23 -04:00
|
|
|
let token = await this.repository.getByToken(hashedToken);
|
2023-02-05 23:31:16 -06:00
|
|
|
|
|
|
|
|
if (token?.user) {
|
2023-04-25 22:19:23 -04:00
|
|
|
const now = DateTime.now();
|
|
|
|
|
const updatedAt = DateTime.fromJSDate(token.updatedAt);
|
|
|
|
|
const diff = now.diff(updatedAt, ['hours']);
|
|
|
|
|
if (diff.hours > 1) {
|
|
|
|
|
token = await this.repository.save({ ...token, updatedAt: new Date() });
|
|
|
|
|
}
|
|
|
|
|
|
2023-01-31 13:11:49 -05:00
|
|
|
return {
|
2023-02-05 23:31:16 -06:00
|
|
|
...token.user,
|
2023-01-31 13:11:49 -05:00
|
|
|
isPublicUser: false,
|
|
|
|
|
isAllowUpload: true,
|
|
|
|
|
isAllowDownload: true,
|
|
|
|
|
isShowExif: true,
|
2023-02-05 23:31:16 -06:00
|
|
|
accessTokenId: token.id,
|
2023-01-31 13:11:49 -05:00
|
|
|
};
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
throw new UnauthorizedException('Invalid user token');
|
|
|
|
|
}
|
|
|
|
|
|
2023-04-25 22:19:23 -04:00
|
|
|
async create(user: UserEntity, loginDetails: LoginDetails): Promise<string> {
|
2023-01-27 20:50:07 +00:00
|
|
|
const key = this.crypto.randomBytes(32).toString('base64').replace(/\W/g, '');
|
|
|
|
|
const token = this.crypto.hashSha256(key);
|
|
|
|
|
await this.repository.create({
|
|
|
|
|
token,
|
|
|
|
|
user,
|
2023-04-25 22:19:23 -04:00
|
|
|
deviceOS: loginDetails.deviceOS,
|
|
|
|
|
deviceType: loginDetails.deviceType,
|
2023-01-27 20:50:07 +00:00
|
|
|
});
|
|
|
|
|
|
|
|
|
|
return key;
|
|
|
|
|
}
|
2023-02-05 23:31:16 -06:00
|
|
|
|
2023-04-25 22:19:23 -04:00
|
|
|
async delete(userId: string, id: string): Promise<void> {
|
|
|
|
|
await this.repository.delete(userId, id);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
getAll(userId: string): Promise<UserTokenEntity[]> {
|
|
|
|
|
return this.repository.getAll(userId);
|
2023-02-05 23:31:16 -06:00
|
|
|
}
|
2023-01-27 20:50:07 +00:00
|
|
|
}
|