login.js 1.36 KB
'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;