-
Notifications
You must be signed in to change notification settings - Fork 49
/
cookie-session.js
53 lines (43 loc) · 1.13 KB
/
cookie-session.js
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
const {Router} = require('express')
const AV = require('leanengine')
const router = module.exports = new Router
/*
* 使用 Cookie Session 示例
*
* 注意检查 app.js 中需要有 `app.use(AV.Cloud.CookieSession({ secret: 'randomString', maxAge: 3600000, fetchUser: true }))`
*
*/
/* 对于已登录的用户会返回用户信息,未登录的用户会返回空 */
router.get('/', (req, res) => {
res.json(req.currentUser)
})
/* 注册用户并自动登录 */
router.post('/register', async (req, res, next) => {
const {username, password} = req.body
const user = new AV.User()
user.set('username', username)
user.set('password', password)
try {
await user.signUp()
res.saveCurrentUser(user)
res.json(user)
} catch (err) {
next(err)
}
})
/* 登录用户 */
router.post('/login', async (req, res, next) => {
const {username, password} = req.body
try {
const user = await AV.User.logIn(username, password)
res.saveCurrentUser(user)
res.json(user)
} catch (err) {
next(err)
}
})
/* 登出用户 */
router.post('/logout', (req, res) => {
res.clearCurrentUser()
res.sendStatus(204)
})