-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathSession.ts
More file actions
100 lines (87 loc) · 2.58 KB
/
Session.ts
File metadata and controls
100 lines (87 loc) · 2.58 KB
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
import {
JsonController,
Authorized,
Get,
Post,
Patch,
Delete,
Body,
CurrentUser,
ForbiddenError,
OnUndefined
} from 'routing-controllers';
import { ResponseSchema } from 'routing-controllers-openapi';
import { sign } from 'jsonwebtoken';
import { User } from 'leanengine';
import { Cloud } from 'leancloud-storage';
import {
SMSCodeRequest,
SignInPhoneRequest,
SignInOAuthRequest,
SignInResponse,
UserRole,
UserModel
} from '../model';
import { getWechatSession } from '../utility';
const { ROOT_ACCOUNT, LEANCLOUD_APP_KEY } = process.env;
@JsonController('/session')
export class SessionController {
static signToken(user: User) {
return sign(
{ token: user.getSessionToken(), roles: user.get('roles') },
LEANCLOUD_APP_KEY,
{ expiresIn: '7d' }
);
}
@Post('/smsCode')
sendSMSCode(@Body() { mobilePhoneNumber: phone }: SMSCodeRequest) {
return Cloud.requestSmsCode(phone);
}
@Post()
@ResponseSchema(SignInResponse)
async signInWithPhone(
@Body()
{ mobilePhoneNumber: phone, verificationCode: code }: SignInPhoneRequest
) {
const user = await User.signUpOrlogInWithMobilePhone(phone, code);
if (!user.get('roles') && phone === ROOT_ACCOUNT)
await user.save({ roles: [UserRole.Admin] }, { user });
return { token: SessionController.signToken(user) } as SignInResponse;
}
@Post()
@ResponseSchema(SignInResponse)
async signInWithWechat(@Body() { code }: SignInOAuthRequest) {
const { unionid, session_key, ...data } = await getWechatSession(code);
const user = await (unionid
? User.loginWithWeappWithUnionId(unionid)
: User.loginWithAuthData(
{ access_token: session_key, ...data },
'weixin'
));
return { token: SessionController.signToken(user) } as SignInResponse;
}
@Get()
@Authorized()
@ResponseSchema(UserModel)
async getProfile(@CurrentUser() user: User) {
return (await user.fetch()).toJSON() as UserModel;
}
@Patch()
@Authorized()
@ResponseSchema(UserModel)
async editProfile(
@CurrentUser() user: User,
@Body() { roles, ...data }: UserModel
) {
if (roles) throw new ForbiddenError();
return (
await user.save(data, { user, fetchWhenSave: true })
).toJSON() as UserModel;
}
@Delete()
@Authorized()
@OnUndefined(204)
async destroy() {
await User.logOut();
}
}