-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathweb.user.js
More file actions
113 lines (103 loc) · 3.39 KB
/
Copy pathweb.user.js
File metadata and controls
113 lines (103 loc) · 3.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
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
/**
* todo fix me
* 注册登录页面应该具有独立的页面,不至于未登录状态和登录状态的逻辑处理重叠,比如首页会增加ctx.state.User
*/
const createError = require('http-errors');
const Router = require('koa-router');
const { CookieSession } = require('../constant');
const router = new Router({
prefix: '/user',
});
router.post('/signup', async (ctx, next) => {
const body = ctx.request.body;
let email = body.email.trim();
let password = body.password.trim();
let timestamp = new Date().getTime();
if (!email || !password) {
throw createError(400, 'params less');
}
await UserModel.findOne({ where: { email: email } })
.then((user) => {
if (user) {
console.log(
'findOne user',
user.get({
plain: true,
})
);
throw createError(400, '邮箱已存在');
}
})
.then(() => {
return UserModel.create({
namenick: 'User' + timestamp,
email: email,
password: password,
})
.then((user) => {
let user_plain = user.get({
plain: true,
});
session.user_id = user_plain.id;
DB_Redis.hset(session.id, session);
DB_Redis.expire(session.id, CookieSession.SessionExpire);
ctx.redirect('/');
})
.catch((err) => {
throw createError(500, '注册失败');
});
});
await next();
});
router.post('/signin', async (ctx, next) => {
const body = ctx.request.body;
let email = body.email.trim();
let password = body.password.trim();
await UserModel.findOne({
where: { email: email, password: password },
}).then((user) => {
if (user) {
let user_plain = user.get({
plain: true,
});
session.user_id = user_plain.id;
DB_Redis.hset(session.id, session);
DB_Redis.expire(session.id, CookieSession.SessionExpire);
ctx.redirect('/');
} else {
throw createError(400, '用户不存在或密码错误');
}
});
await next();
});
router.get('/signout', async (ctx, next) => {
if (!session || !session.user_id) {
throw createError(400, '错误请求');
}
await UserModel.findByPk(parseInt(session.user_id)).then((user) => {
if (user) {
let user_plain = user.get({ plain: true });
DB_Redis.expire(session.id, 0);
ctx.cookies.set(CookieSession.session_name, '', {
signed: true,
expires: 0,
});
session = null;
delete ctx.state.User;
ctx.redirect('/');
} else {
throw createError(400, '用户不存在或密码错误');
}
});
await next();
});
router.post('/consultSubmit', async (ctx, next) => {
const request = ctx.request;
console.log('body', request.body);
console.log('files', request.files);
const body = request.body || {};
// if (!body.age) ctx.throw(400, '.age required');
ctx.body = { age: body.age || '---' };
await next();
});
module.exports = router;