backend/src/models/creation/CreateAuth.ts

56 lines
2.0 KiB
TypeScript

import * as argon2 from "argon2";
import { IsEmail, IsOptional, IsString } from 'class-validator';
import * as jsonwebtoken from 'jsonwebtoken';
import { getConnectionManager } from 'typeorm';
import { InvalidCredentialsError, PasswordNeededError, UserNotFoundError } from '../../errors/AuthError';
import { UsernameOrEmailNeededError } from '../../errors/UserErrors';
import { Auth } from '../entities/Auth';
import { User } from '../entities/User';
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_users = await getConnectionManager().get().getRepository(User).find({ where: [{ username: this.username }, { email: this.email }] });
if (found_users.length === 0) {
throw new UserNotFoundError()
} else {
const found_user = found_users[0]
console.log(found_user.password);
// try {
if (await argon2.verify(found_user.password, this.password + found_user.uuid)) {
// password match
// TODO: proper jwt creation
const token = jsonwebtoken.sign({}, "securekey")
newAuth.access_token = token
newAuth.refresh_token = token
newAuth.access_token_expires_at = 1587349200
newAuth.refresh_token_expires_at = 1587349200
} else {
// password did not match
throw new InvalidCredentialsError()
}
// } catch (err) {
// // internal failure
// }
}
return newAuth;
}
}