This repository has been archived by the owner on Feb 11, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathauth.ts
162 lines (156 loc) · 4.49 KB
/
auth.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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
import { Request, Response, NextFunction } from 'express';
import { UserModel, AuthModel } from '@/models';
import { scryptPassword, getTokenFromUserId, formatDate } from '@/utils';
import { APP_JWT_EXPIRES_IN } from '@/constants';
import {
authMiddleware,
validate,
bodyUsernameValidationChain,
bodyPasswordValidationChain,
} from '@/middlewares';
export const USER_ROLE = {
1: 'admin',
2: 'user',
admin: 1,
user: 2,
};
export const authRouterBasePath = '/';
export const authController: IController = {
signIn: {
path: '/sign-in',
methods: ['post'],
middlewares: [validate([bodyUsernameValidationChain, bodyPasswordValidationChain])],
function: async (request: Request, response: Response, next: NextFunction) => {
try {
const { username, password } = request.body as { username: string; password: string };
// check username and password
const user = await UserModel.findOne({ username });
const userId = user?._id;
const auth = await AuthModel.findOne({ userId });
if (!user || !userId || !auth || scryptPassword(password, user._id) !== auth.password) {
next({
status: 401,
message: `Wrong username ${username} or password.`,
});
return;
}
// update auth
const token = auth.token || getTokenFromUserId(userId);
const expiredAt = new Date(Date.now() + APP_JWT_EXPIRES_IN);
await auth.updateOne({
token,
expiredAt,
updatedAt: new Date(),
});
// response
response.json({
user: user.toJSON(),
auth: {
token,
expiredAt: formatDate(expiredAt),
},
});
return;
} catch (error: any) {
next({
message: `/auth/sign-in ${error?.message ?? error}`,
});
}
},
},
signUp: {
path: '/sign-up',
methods: ['post'],
middlewares: [validate([bodyUsernameValidationChain, bodyPasswordValidationChain])],
function: async (request: Request, response: Response, next: NextFunction) => {
try {
const { username, password } = request.body as {
username: string;
password: string;
};
// username has been used
const existedUser = await UserModel.findOne({ username });
if (existedUser) {
next({
status: 409,
message: `Username ${username} has been used.`,
});
return;
}
// create user
const user = await UserModel.create({
username,
role: USER_ROLE.user,
});
// create auth
await AuthModel.create<IAuth>({
userId: user._id,
password: scryptPassword(password, user._id),
token: '',
expiredAt: new Date(),
});
// response
response.status(201).json();
return;
} catch (error: any) {
next({
message: `/auth/sign-up ${error?.message ?? error}`,
});
}
},
},
signOut: {
path: '/sign-out',
methods: ['post'],
middlewares: [authMiddleware],
function: async (request: Request, response: Response, next: NextFunction) => {
try {
const { user } = request.body as Body;
const auth = (await AuthModel.findOne({ userId: user._id }))!;
await auth.updateOne({
expiredAt: new Date(),
updatedAt: new Date(),
});
response.json({
message: 'OK.',
});
return;
} catch (error: any) {
next({
message: `/auth/sign-out ${error?.message ?? error}`,
});
}
},
},
renew: {
path: '/renew',
methods: ['post'],
middlewares: [authMiddleware],
function: async (request: Request, response: Response, next: NextFunction) => {
try {
const { user } = request.body as Body;
// update auth
const auth = (await AuthModel.findOne({ userId: user._id }))!;
const { token } = auth;
const expiredAt = new Date(Date.now() + APP_JWT_EXPIRES_IN);
await auth.updateOne({
expiredAt,
updatedAt: new Date(),
});
// response
response.json({
user: user.toJSON(),
auth: {
token,
expiredAt: formatDate(expiredAt),
},
});
return;
} catch (error: any) {
next({
message: `/auth/renew ${error?.message ?? error}`,
});
}
},
},
};