-
Notifications
You must be signed in to change notification settings - Fork 12
Expand file tree
/
Copy pathSession.ts
More file actions
81 lines (68 loc) · 2.39 KB
/
Session.ts
File metadata and controls
81 lines (68 loc) · 2.39 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
import {
JsonController,
Authorized,
Get,
Post,
Body,
CurrentUser,
HttpCode,
OnUndefined,
} from 'routing-controllers';
import { ResponseSchema } from 'routing-controllers-openapi';
import { uniqueID } from 'web-utility';
import { Captcha, SMSCodeInput, PhoneSignInData, User } from '../model';
import { leanClient } from '../utility';
import { sessionService } from '../service';
@JsonController('/session')
export class SessionController {
userStore = sessionService.userStore;
@Post('/captcha')
@ResponseSchema(Captcha)
async createCaptcha() {
const { body } =
await leanClient.get<Record<`captcha_${'token' | 'url'}`, string>>('requestCaptcha');
return { token: body.captcha_token, link: body.captcha_url };
}
static async verifyCaptcha(captcha_token: string, captcha_code: string) {
const { body } = await leanClient.post<{ validate_token: string }>('verifyCaptcha', {
captcha_code,
captcha_token,
});
return { token: body.validate_token };
}
@Post('/session/SMS-code')
@OnUndefined(201)
async createSMSCode(@Body() { captchaToken, captchaCode, mobilePhone }: SMSCodeInput) {
if (captchaToken && captchaCode)
var { token } = await SessionController.verifyCaptcha(captchaToken, captchaCode);
await leanClient.post<{}>('requestSmsCode', {
mobilePhoneNumber: mobilePhone,
validate_token: token,
});
}
static verifySMSCode = (mobilePhoneNumber: string, code: string) =>
leanClient.post<{}>(`verifySmsCode/${code}`, { mobilePhoneNumber });
@Post('/')
@HttpCode(201)
@ResponseSchema(User)
async signIn(@Body() { mobilePhone, password }: PhoneSignInData): Promise<User> {
const { userStore } = this;
let user = await userStore.findOneBy({
mobilePhone,
password: sessionService.encrypt(password),
});
if (!user) {
await SessionController.verifySMSCode(mobilePhone, password);
user =
(await userStore.findOneBy({ mobilePhone })) ||
(await sessionService.signUp({ mobilePhone, password: uniqueID() }));
}
return sessionService.sign(user);
}
@Get('/')
@Authorized()
@ResponseSchema(User)
getSession(@CurrentUser() user: User) {
return user;
}
}