2019-05-15 20:15:49 +08:00

95 lines
2.6 KiB
JavaScript

import ldap from 'ldapjs';
import jwt from 'jsonwebtoken';
import config from '../../../config/config';
import {User} from '../../models/admin/User';
export default function(req, res, next) {
console.log('登录')
const body = req.body;
const client = ldap.createClient({
url: config.ldap.url
});
const opts = {
filter: `(uid=${body.username})`,
scope: 'sub',
timeLimit: 500
};
const data = [];
client.bind(config.ldap.user, config.ldap.password, function(err, bindRes) {
if (err) next(err);
client.search('ou=people,dc=kingsome,dc=cn', opts, function(
err,
searchRes
) {
if (err) next(err);
searchRes.on('searchEntry', function(entry) {
data.push(entry.object);
});
searchRes.on('error', function(err) {
client.unbind();
next(err);
});
searchRes.on('end', function(result) {
if (data.length > 0) {
// 用户存在,验证密码
const user = data[0];
const dn = user.dn;
client.bind(dn, body.password, async function(err, verifyRes) {
// 登录成功
if (err === null) {
const token = jwt.sign(
{
username: user.uid
},
config.jwtSecret,
{
expiresIn: 60 * 60 * 2
}
);
try {
let userSearch = await User.findOne({ username: user.uid });
if (!userSearch) {
const newUser = new User({
_id:user.uidNumber,
username: user.uid,
fullname: user.sn
});
const saveResult = await newUser.save();
userSearch = saveResult;
} else {
await User.update({username: user.uid}, {
lastLogin: new Date()
})
}
client.unbind();
res.send({
errcode: 0,
token,
userInfo: userSearch
});
} catch (err) {
next(err);
}
} else {
client.unbind();
res.send({
errcode: 1,
errmsg: '密码不正确。'
});
}
});
} else {
// 用户不存在
client.unbind();
res.send({
errcode: 2,
errmsg: '用户不存在。'
});
}
});
});
});
}