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
| const router = require('koa-router')() const User = require('../models/User.js') const jwt = require('jsonwebtoken') const { success, fail } = require('../utils/index.js')
router.prefix('/user')
router.post('/login', async ctx => { const user = await User.findOne({ where: ctx.request.body, raw: true }) if (!user) { ctx.body = fail('用户名或密码错误') } else { const token = jwt.sign(user, 'secret', { expiresIn: '7d' }) ctx.body = success({ token }, '登陆成功') } })
router.get('/profile', async ctx => { const token = ctx.get('Authorization').split(' ').pop() jwt.verify(token, 'secret', (err, decode) => { if (err) { ctx.body = fail(err.message, 401) } else { ctx.body = success({ userInfo: decode }, '获取成功') } }) })
module.exports = router
|