48 lines
1.9 KiB
TypeScript
48 lines
1.9 KiB
TypeScript
import * as argon2 from "argon2";
|
|
import { IsEmail, IsOptional, IsString } from 'class-validator';
|
|
import { getConnectionManager } from 'typeorm';
|
|
import { InvalidCredentialsError, PasswordNeededError, UserNotFoundError } from '../../errors/AuthError';
|
|
import { UsernameOrEmailNeededError } from '../../errors/UserErrors';
|
|
import { JwtCreator } from '../../JwtCreator';
|
|
import { User } from '../entities/User';
|
|
import { Auth } from '../responses/ResponseAuth';
|
|
|
|
export class CreateAuth {
|
|
@IsOptional()
|
|
@IsString()
|
|
username?: string;
|
|
@IsString()
|
|
password: string;
|
|
@IsOptional()
|
|
@IsEmail()
|
|
@IsString()
|
|
email?: string;
|
|
|
|
public async toAuth(): Promise<Auth> {
|
|
let newAuth: Auth = new Auth();
|
|
|
|
if (this.email === undefined && this.username === undefined) {
|
|
throw new UsernameOrEmailNeededError();
|
|
}
|
|
if (!this.password) {
|
|
throw new PasswordNeededError();
|
|
}
|
|
const found_user = await getConnectionManager().get().getRepository(User).findOne({ relations: ['groups', 'permissions'], where: [{ username: this.username }, { email: this.email }] });
|
|
if (!found_user) {
|
|
throw new UserNotFoundError();
|
|
}
|
|
if (!(await argon2.verify(found_user.password, this.password + found_user.uuid))) {
|
|
throw new InvalidCredentialsError();
|
|
}
|
|
|
|
//Create the access token
|
|
const timestamp_accesstoken_expiry = Math.floor(Date.now() / 1000) + 5 * 60
|
|
newAuth.access_token = JwtCreator.createAccess(found_user, timestamp_accesstoken_expiry);
|
|
newAuth.access_token_expires_at = timestamp_accesstoken_expiry
|
|
//Create the refresh token
|
|
const timestamp_refresh_expiry = Math.floor(Date.now() / 1000) + 10 * 36000
|
|
newAuth.refresh_token = JwtCreator.createRefresh(found_user, timestamp_refresh_expiry);
|
|
newAuth.refresh_token_expires_at = timestamp_refresh_expiry
|
|
return newAuth;
|
|
}
|
|
} |