-
Notifications
You must be signed in to change notification settings - Fork 169
/
auth.provider.ts
89 lines (71 loc) · 2.15 KB
/
auth.provider.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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
import { Injectable, Inject, ProviderScope } from '@graphql-modules/di';
import { ModuleSessionInfo } from '@graphql-modules/core';
import { Response } from 'express';
import bcrypt from 'bcrypt';
import jwt from 'jsonwebtoken';
import { secret, expiration } from '../../env';
import { validateLength, validatePassword } from '../../validators';
import { Users } from './users.provider';
import { User } from '../../db';
@Injectable({
scope: ProviderScope.Session,
})
export class Auth {
@Inject() private users: Users;
@Inject() private module: ModuleSessionInfo;
private get req() {
return this.module.session.req || this.module.session.request;
}
private get res(): Response {
return this.module.session.res;
}
async signIn({ username, password }: { username: string; password: string }) {
const user = await this.users.findByUsername(username);
if (!user) {
throw new Error('user not found');
}
const passwordsMatch = bcrypt.compareSync(password, user.password);
if (!passwordsMatch) {
throw new Error('password is incorrect');
}
const authToken = jwt.sign(username, secret);
this.res.cookie('authToken', authToken, { maxAge: expiration });
return user;
}
async signUp({
name,
password,
passwordConfirm,
username,
}: {
name: string;
password: string;
passwordConfirm: string;
username: string;
}) {
validateLength('req.name', name, 3, 50);
validateLength('req.username', username, 3, 18);
validatePassword('req.password', password);
if (password !== passwordConfirm) {
throw Error("req.password and req.passwordConfirm don't match");
}
const existingUser = await this.users.findByUsername(username);
if (existingUser) {
throw Error('username already exists');
}
return this.users.newUser({
username,
name,
password,
});
}
async currentUser(): Promise<User | null> {
if (this.req.cookies.authToken) {
const username = jwt.verify(this.req.cookies.authToken, secret) as string;
if (username) {
return this.users.findByUsername(username);
}
}
return null;
}
}