-
Notifications
You must be signed in to change notification settings - Fork 2
/
User.ts
154 lines (134 loc) · 3.83 KB
/
User.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
import { createHash } from 'crypto';
import { JsonWebTokenError, sign } from 'jsonwebtoken';
import {
Authorized,
Body,
CurrentUser,
Delete,
ForbiddenError,
Get,
HttpCode,
JsonController,
OnNull,
OnUndefined,
Param,
Post,
Put,
QueryParams
} from 'routing-controllers';
import { ResponseSchema } from 'routing-controllers-openapi';
import {
dataSource,
JWTAction,
Role,
SignInData,
User,
UserFilter,
UserListChunk
} from '../model';
import { APP_SECRET, searchConditionOf } from '../utility';
import { ActivityLogController } from './ActivityLog';
const store = dataSource.getRepository(User);
@JsonController('/user')
export class UserController {
static encrypt = (raw: string) =>
createHash('sha1')
.update(APP_SECRET + raw)
.digest('hex');
static sign = (user: User): User => ({
...user,
token: sign({ ...user }, APP_SECRET)
});
static async signUp({ email, password }: SignInData) {
const sum = await store.count();
const { password: _, ...user } = await store.save({
name: email,
email,
password: UserController.encrypt(password),
roles: [sum ? Role.Client : Role.Administrator]
});
await ActivityLogController.logCreate(user, 'User', user.id);
return user;
}
static getSession({ context: { state } }: JWTAction) {
return state instanceof JsonWebTokenError
? console.error(state)
: state.user;
}
@Get('/session')
@Authorized()
@ResponseSchema(User)
getSession(@CurrentUser() user: User) {
return user;
}
@Post('/session')
@HttpCode(201)
@ResponseSchema(User)
async signIn(@Body() { email, password }: SignInData): Promise<User> {
const user = await store.findOneBy({
email,
password: UserController.encrypt(password)
});
if (!user) throw new ForbiddenError();
return UserController.sign(user);
}
@Post()
@HttpCode(201)
@ResponseSchema(User)
signUp(@Body() data: SignInData) {
return UserController.signUp(data);
}
@Put('/:id')
@Authorized()
@ResponseSchema(User)
async updateOne(
@Param('id') id: number,
@CurrentUser() updatedBy: User,
@Body() { password, ...data }: User
) {
if (
!updatedBy.roles.includes(Role.Administrator) &&
id !== updatedBy.id
)
throw new ForbiddenError();
const saved = await store.save({
...data,
password: password && UserController.encrypt(password),
id
});
await ActivityLogController.logUpdate(updatedBy, 'User', id);
return UserController.sign(saved);
}
@Get('/:id')
@OnNull(404)
@ResponseSchema(User)
getOne(@Param('id') id: number) {
return store.findOne({ where: { id } });
}
@Delete('/:id')
@Authorized()
@OnUndefined(204)
async deleteOne(@Param('id') id: number, @CurrentUser() deletedBy: User) {
if (deletedBy.roles.includes(Role.Administrator) && id == deletedBy.id)
throw new ForbiddenError();
await store.softDelete(id);
await ActivityLogController.logDelete(deletedBy, 'User', id);
}
@Get()
@ResponseSchema(UserListChunk)
async getList(
@QueryParams() { gender, keywords, pageSize, pageIndex }: UserFilter
) {
const where = searchConditionOf<User>(
['email', 'mobilePhone', 'name'],
keywords,
gender && { gender }
);
const [list, count] = await store.findAndCount({
where,
skip: pageSize * (pageIndex - 1),
take: pageSize
});
return { list, count };
}
}