政务数据资源中心(Government data Resource center) 03专项3期主要建设内容
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 

85 lines
2.3 KiB

'use strict';
const Hex = require('crypto-js/enc-hex');
const SHA1 = require('crypto-js/sha1');
const MD5 = require('crypto-js/md5');
const moment = require('moment');
const uuid = require('uuid');
async function login (ctx, next) {
// const transaction = await ctx.fs.dc.orm.transaction();
try {
const models = ctx.fs.dc.models;
const params = ctx.request.body;
let userRes = null
if (params.username && params.password) {
const password = Hex.stringify(MD5(params.password));
userRes = await models.User.findOne({
attributes: { exclude: ['password'] },
where: {
username: params.username,
password: password
},
});
}
if (userRes) {
if (userRes.forbidden) {
throw '用户已禁用'
} else {
const token = uuid.v4();
const userInfo = {
authorized: true,
...userRes.dataValues,
token,
};
// 记录token
const expiredDay = 7;
const expired = moment().add(expiredDay, 'day').format('YYYY-MM-DD HH:mm:ss')
await models.UserToken.create({
token: token,
userInfo: userInfo,
expired: expired
});
ctx.status = 200;
ctx.body = userInfo;
}
} else {
throw '账号或密码错误'
}
// await transaction.commit();
} catch (error) {
// await transaction.rollback();
ctx.status = 400;
ctx.body = {
message: typeof error == 'string' ? error : '登录失败'
}
}
}
async function logout (ctx) {
try {
const models = ctx.fs.dc.models;
const params = ctx.request.body;
await models.UserToken.destroy({
where: {
token: params.token,
}
});
ctx.status = 204;
} catch (error) {
ctx.fs.logger.error(`path: ${ctx.path}, error: ${error}`);
ctx.status = 400;
ctx.body = {
message: typeof error == 'string' ? error : undefined
}
}
}
module.exports = {
login,
logout,
};