immich/server/libs/domain/src/user-token/user-token.core.ts
Jason Rasmussen b8313abfa8
feat(web,server): manage authorized devices (#2329)
* feat: manage authorized devices

* chore: open api

* get header from mobile app

* write header from mobile app

* styling

* fix unit test

* feat: use relative time

* feat: update access time

* fix: tests

* chore: confirm wording

* chore: bump test coverage thresholds

* feat: add some icons

* chore: icon tweaks

---------

Co-authored-by: Alex Tran <alex.tran1502@gmail.com>
2023-04-25 21:19:23 -05:00

57 lines
1.7 KiB
TypeScript

import { UserEntity, UserTokenEntity } from '@app/infra/entities';
import { Injectable, UnauthorizedException } from '@nestjs/common';
import { DateTime } from 'luxon';
import { LoginDetails } from '../auth';
import { ICryptoRepository } from '../crypto';
import { IUserTokenRepository } from './user-token.repository';
@Injectable()
export class UserTokenCore {
constructor(private crypto: ICryptoRepository, private repository: IUserTokenRepository) {}
async validate(tokenValue: string) {
const hashedToken = this.crypto.hashSha256(tokenValue);
let token = await this.repository.getByToken(hashedToken);
if (token?.user) {
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() });
}
return {
...token.user,
isPublicUser: false,
isAllowUpload: true,
isAllowDownload: true,
isShowExif: true,
accessTokenId: token.id,
};
}
throw new UnauthorizedException('Invalid user token');
}
async create(user: UserEntity, loginDetails: LoginDetails): Promise<string> {
const key = this.crypto.randomBytes(32).toString('base64').replace(/\W/g, '');
const token = this.crypto.hashSha256(key);
await this.repository.create({
token,
user,
deviceOS: loginDetails.deviceOS,
deviceType: loginDetails.deviceType,
});
return key;
}
async delete(userId: string, id: string): Promise<void> {
await this.repository.delete(userId, id);
}
getAll(userId: string): Promise<UserTokenEntity[]> {
return this.repository.getAll(userId);
}
}