-
Notifications
You must be signed in to change notification settings - Fork 27
/
Copy pathauth.service.ts
63 lines (46 loc) · 2.44 KB
/
auth.service.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
import { hash, compare } from 'bcrypt';
import { sign } from 'jsonwebtoken';
import { SECRET_KEY } from '@config';
import { CreateUserDto } from '@dtos/users.dto';
import { HttpException } from '@exceptions/HttpException';
import { DataStoredInToken, TokenData } from '@interfaces/auth.interface';
import { User } from '@interfaces/users.interface';
import userModel from '@models/users.model';
import { isEmpty } from '@utils/util';
class AuthService {
public users = userModel;
public async #(userData: CreateUserDto): Promise<User> {
if (isEmpty(userData)) throw new HttpException(400, "userData is empty");
const findUser: User = await this.users.findOne({ email: userData.email });
if (findUser) throw new HttpException(409, `This email ${userData.email} already exists`);
const hashedPassword = await hash(userData.password, 10);
const createUserData: User = await this.users.create({ ...userData, password: hashedPassword });
return createUserData;
}
public async login(userData: CreateUserDto): Promise<{ cookie: string; findUser: User }> {
if (isEmpty(userData)) throw new HttpException(400, "userData is empty");
const findUser: User = await this.users.findOne({ email: userData.email });
if (!findUser) throw new HttpException(409, `This email ${userData.email} was not found`);
const isPasswordMatching: boolean = await compare(userData.password, findUser.password);
if (!isPasswordMatching) throw new HttpException(409, "Password is not matching");
const tokenData = this.createToken(findUser);
const cookie = this.createCookie(tokenData);
return { cookie, findUser };
}
public async logout(userData: User): Promise<User> {
if (isEmpty(userData)) throw new HttpException(400, "userData is empty");
const findUser: User = await this.users.findOne({ email: userData.email, password: userData.password });
if (!findUser) throw new HttpException(409, `This email ${userData.email} was not found`);
return findUser;
}
public createToken(user: User): TokenData {
const dataStoredInToken: DataStoredInToken = { _id: user._id };
const secretKey: string = SECRET_KEY;
const expiresIn: number = 60 * 60;
return { expiresIn, token: sign(dataStoredInToken, secretKey, { expiresIn }) };
}
public createCookie(tokenData: TokenData): string {
return `Authorization=${tokenData.token}; HttpOnly; Max-Age=${tokenData.expiresIn};`;
}
}
export default AuthService;