login.js 1.02 KB
'use strict';

import Router from 'koa-router';
import md5 from 'md5';
import {User} from '../../models';

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
            };
            ctx.redirect('/projects');
            ctx.status = 301;
        } else {
            ctx.flash = { error: '账户密码错误' };
            await ctx.render('login', { layout: '', message: ctx.flash.error });
        }
    },
    logout: (ctx, next) => {
        ctx.session = null;
        ctx.redirect('/');
        ctx.status = 301;
    }
};

r.get('/login', login.loginPage);
r.get('/logout', login.logout);
r.post('/auth', login.auth);


export default r;