login.js
1.36 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
'use strict';
const Router = require('koa-router');
const md5 = require('md5');
const {User} = require('../../models');
const Operation = require('../../logger/operation');
let r = new Router();
const login = {
loginPage: async (ctx, next) => {
await ctx.render('login', { layout: '' });
},
auth: async (ctx, next) => {
let username = ctx.request.body.username;
let password = ctx.request.body.password;
let user = await User.findByUsername(username);
if (user && password && user.password === md5(password)) {
ctx.session = {
user: user
};
Operation.action(user, 'LOGIN', '用户登陆');
ctx.redirect('/');
ctx.status = 301;
} else {
ctx.flash = { error: '账户密码错误' };
await ctx.render('login', { layout: '', message: ctx.flash.error });
}
},
logout: (ctx, next) => {
ctx.session = null;
console.log('logout!');
ctx.set('Cache-Control', 'no-cache');
ctx.redirect('/');
},
info(ctx) {
const user = ctx.session.user
delete user._id
delete user.password
ctx.body = user;
}
};
r.get('/login', login.loginPage);
r.get('/logout', login.logout);
r.post('/auth', login.auth);
r.get('/login/info', login.info);
module.exports = r;