const express = require('request-promise');
const crypto = require('crypto');
const agent = require('../db/mongo/tao-agent');
const session = require('../db/mongo/session');

const _ = require('lodash');

exports.login = async (req,res,next) => {
	let {username,password} = req.body;
	console.dir(crypto.createHash('md5').update(password).digest('hex'));
	let user = await agent.findOne({user:username,password:crypto.createHash('md5').update(password).digest('hex')});
	if(user){
		let sess = { user: user._id};
		const _sess = await new session(sess).save();
		res.cookie('sess',_sess._id+'');
		res.cookie('username',username);
		res.send({result: 'ok'});
	}
	else
		res.status(500).send({result:'密码不正确'});
		
};

exports.logout = async (req,res,next) => {
	let sess = req.cookies['sess'];
    if(sess){
     	session.remove({_id:sess},function(err,result) {
     		if(!err){
     			res.clearCookie('sess');
     			res.clearCookie('username');
     			res.send({result:'ok'})
     		}
     		else{
     			res.status(500).send('错误');
     		}
     	});
     	
    }
    else
		res.status(500).send('错误');
		
};