调整登录判断及增加 fixtures

This commit is contained in:
yulixing 2019-05-22 16:12:42 +08:00
parent 4e001fece6
commit 565adf32b9
10 changed files with 123 additions and 206 deletions

26
fixtures/roles.js Normal file
View File

@ -0,0 +1,26 @@
const ObjectId = require('pow-mongodb-fixtures').createObjectId;
const ISODate = function(dateStr) {
return new Date(dateStr);
};
exports.roles = [
{
_id: ObjectId('5cdcdd0c25609b18348ef7b5'),
permissions: [
'users-writeable',
'permission-writeable',
'logs-writeable',
'dics-writeable',
'data-writeable'
],
name: '系统管理员',
rolename: 'admin',
describe: '拥有所有系统权限。',
comment: '',
createdAt: ISODate('2019-05-16T03:46:20.316Z'),
updatedAt: ISODate('2019-05-16T03:46:20.316Z'),
__v: 0,
basePermissionTable:
'{"users":{"name":"users","label":"用户列表","permission":"writeable"},"permission":{"name":"permission","label":"权限管理","permission":"writeable"},"logs":{"name":"logs","label":"操作日志","permission":"writeable"},"dics":{"name":"dics","label":"字典","permission":"writeable"},"data":{"name":"data","label":"数据查询","permission":"writeable"}}'
}
];

View File

@ -5,7 +5,8 @@
"main": "index.js", "main": "index.js",
"scripts": { "scripts": {
"test": "echo \"Error: no test specified\" && exit 1", "test": "echo \"Error: no test specified\" && exit 1",
"dev": "cross-env nodemon src/app.js --exec babel-node " "dev": "cross-env nodemon src/app.js --exec babel-node ",
"init": "cross-env node src/init-data.js --exec babel-node"
}, },
"keywords": [], "keywords": [],
"author": "", "author": "",
@ -39,9 +40,11 @@
"multer": "^1.4.1", "multer": "^1.4.1",
"node-schedule": "^1.3.2", "node-schedule": "^1.3.2",
"nodemon": "^1.19.0", "nodemon": "^1.19.0",
"pow-mongodb-fixtures": "^0.14.0",
"redis": "^2.8.0", "redis": "^2.8.0",
"request": "^2.88.0", "request": "^2.88.0",
"serve-favicon": "^2.5.0" "serve-favicon": "^2.5.0",
"yargs": "^13.2.4"
}, },
"devDependencies": { "devDependencies": {
"babel-cli": "^6.26.0", "babel-cli": "^6.26.0",

View File

@ -1,4 +1,3 @@
'use strict';
import mongoose from 'mongoose'; import mongoose from 'mongoose';
import config from '../config/config'; import config from '../config/config';
import app from './bin/express'; import app from './bin/express';

View File

@ -1,5 +1,3 @@
'use strict';
import express from 'express'; import express from 'express';
import expressValidator from 'express-validator'; import expressValidator from 'express-validator';
import flash from 'express-flash'; import flash from 'express-flash';

View File

@ -68,13 +68,11 @@ router.get('/one_game_cfg', async (req, res, next) => {
} }
if (records) { if (records) {
records = JSON.parse(records); records = JSON.parse(records);
console.log(records)
for (const record of records) { for (const record of records) {
const cfg = platformMap.get(record.key); const cfg = platformMap.get(record.key);
record.title = !cfg || !cfg.title ? record.key : cfg.title; record.title = !cfg || !cfg.title ? record.key : cfg.title;
record.type = !cfg || !cfg.type ? 'string' : cfg.type; record.type = !cfg || !cfg.type ? 'string' : cfg.type;
} }
console.log(records)
} else { } else {
records = []; records = [];
} }

View File

@ -3,10 +3,10 @@ import jwt from 'jsonwebtoken';
import config from '../../../config/config'; import config from '../../../config/config';
import { User } from '../../models/admin/User'; import { User } from '../../models/admin/User';
import { Router } from 'express'; import { Router } from 'express';
import { isatty } from 'tty';
const router = new Router(); const router = new Router();
router.post('/login', function(req, res, next) { router.post('/login', function(req, res, next) {
console.log('login ❤')
const body = req.body; const body = req.body;
const client = ldap.createClient({ const client = ldap.createClient({
url: config.ldap.url url: config.ldap.url
@ -17,14 +17,13 @@ router.post('/login', function(req, res, next) {
timeLimit: 500 timeLimit: 500
}; };
const data = []; const data = [];
const admins = [];
client.bind(config.ldap.user, config.ldap.password, function(err, bindRes) { 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( client.search('ou=people,dc=kingsome,dc=cn', opts, function(
err, err,
searchRes searchRes
) { ) {
if (err) next(err);
searchRes.on('searchEntry', function(entry) { searchRes.on('searchEntry', function(entry) {
data.push(entry.object); data.push(entry.object);
}); });
@ -37,54 +36,89 @@ router.post('/login', function(req, res, next) {
// 用户存在,验证密码 // 用户存在,验证密码
const user = data[0]; const user = data[0];
const dn = user.dn; const dn = user.dn;
client.bind(dn, body.password, async function(err, verifyRes) { let isAdmin = false;
// 登录成功
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) { client.search(
const newUser = new User({ 'cn=gmplatform-admin,ou=group,dc=kingsome,dc=cn',
_id: user.uidNumber, {
username: user.uid, filter: `(&(objectClass=posixGroup)(cn=gmplatform-admin))`,
fullname: user.sn scope: 'sub',
}); timeLimit: 500
const saveResult = await newUser.save(); },
userSearch = saveResult; function(err, adminRes) {
} else { adminRes.on('searchEntry', function(entry) {
await User.update( admins.push(entry.object);
{ username: user.uid }, });
{ adminRes.on('error', function(err) {
lastLogin: new Date()
}
);
}
client.unbind(); client.unbind();
res.send({
errcode: 0,
token,
userInfo: userSearch
});
} catch (err) {
next(err); next(err);
} });
} else { adminRes.on('end', async function(result) {
client.unbind(); for (let i = 0; i < admins.length; i++) {
res.send({ if (admins[i].memberUid === body.username) {
errcode: 1, isAdmin = true;
errmsg: '密码不正确。' }
break;
}
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 userObj = {
_id: user.uidNumber,
username: user.uid,
fullname: user.sn
};
if (isAdmin) {
userObj.roles = ['超级管理员'];
userObj.permissions = ['5cdcdd0c25609b18348ef7b5'];
}
const newUser = new User(userObj);
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 { } else {
// 用户不存在 // 用户不存在
client.unbind(); client.unbind();

12
src/init-data.js Normal file
View File

@ -0,0 +1,12 @@
import pmf from 'pow-mongodb-fixtures';
import config from '../config/config';
import path from 'path';
const fixture = pmf.connect(config.db_admin);
const fixturesDir = path.join(config.root, '/fixtures');
fixture.clearAndLoad(fixturesDir, function(err) {
if (err) console.log(err);
console.log('初始数据加载完毕!');
process.exit(0);
});

View File

@ -1,62 +0,0 @@
var express = require('express');
var ldap = require('ldapjs');
var app = express();
//创建LDAP client把服务器url传入
var client = ldap.createClient({
url: 'ldap://ldap.kingsome.cn:389'
});
//创建LDAP查询选项
//filter的作用就是相当于SQL的条件
var opts = {
filter: '(uid=yulixing)', //查询条件过滤器查找uid=kxh的用户节点
scope: 'sub', //查询范围
timeLimit: 500 //查询超时
};
var user = [];
app.get('/', function(req, res, next) {
//将client绑定LDAP Server
//第一个参数:是用户,必须是从根节点到用户节点的全路径
//第二个参数:用户密码
client.bind('cn=admin,dc=kingsome,dc=cn', 'milesQWE321', function(err, res1) {
//开始查询
//第一个参数:查询基础路径,代表在查询用户信心将在这个路径下进行,这个路径是由根节开始
//第二个参数:查询选项
client.search('ou=people,dc=kingsome,dc=cn', opts, function(err, res2) {
console.log(res2)
//查询结果事件响应
res2.on('searchEntry', function(entry) {
//获取查询的对象
var user = entry.object;
var userText = JSON.stringify(user, null, 2);
users = entry
// console.log(entry)
// console.log(userText);
});
res2.on('searchReference', function(referral) {
console.log('referral: ' + referral.uris.join());
});
//查询错误事件
res2.on('error', function(err) {
console.error('error: ' + err.message);
//unbind操作必须要做
client.unbind();
});
//查询结束
res2.on('end', function(result) {
console.log('search status: ' + result);
//unbind操作必须要做
client.unbind();
});
res.send({})
});
});
});
app.listen('6789');

View File

@ -1,84 +0,0 @@
var express = require('express');
var ldap = require('ldapjs');
var app = express();
//创建LDAP client把服务器url传入
var client = ldap.createClient({
url: 'ldap://ldap.kingsome.cn:389'
});
//创建LDAP查询选项
//filter的作用就是相当于SQL的条件
var opts = {
// filter: '(objectClass=posixAccount)', //查询条件过滤器查找uid=kxh的用户节点
filter: '(uid=yulixing1)', //查询条件过滤器查找uid=kxh的用户节点
scope: 'sub', //查询范围
timeLimit: 500 //查询超时
};
var user = [];
app.get('/', function(req, res, next) {
//将client绑定LDAP Server
//第一个参数:是用户,必须是从根节点到用户节点的全路径
//第二个参数:用户密码
client.bind('cn=admin,dc=kingsome,dc=cn', 'milesQWE321', function(err, res1) {
//开始查询
//第一个参数:查询基础路径,代表在查询用户信心将在这个路径下进行,这个路径是由根节开始
//第二个参数:查询选项
client.search('ou=people,dc=kingsome,dc=cn', opts, function(err, res2) {
var entries = [];
//查询结果事件响应
res2.on('searchEntry', function(entry) {
//获取查询的对象
var user = entry.object;
entries.push(user);
users = entry;
});
res2.on('searchReference', function(referral) {
console.log('referral: ' + referral.uris.join());
});
//查询错误事件
res2.on('error', function(err) {
//unbind操作必须要做
client.unbind();
});
//查询结束
res2.on('end', function(result) {
if (entries.length !== 0) {
client.bind(entries[0].dn, 'yulixing123456', function(
err,
res3
) {
if (err) {
res.send({
err: err,
errmsg: err.message
})
} else {
res.send({
result: entries,
state: 0
});
}
});
} else {
res.send({
msg: '登录失败'
})
}
// res.send({
// entries
// })
//unbind操作必须要做
client.unbind();
});
});
});
});
app.listen('6789');

View File

@ -1,7 +0,0 @@
import {Role} from './../src/models/admin/User'
const newRole = new Role({
rolename: 'normal',
permissions: ['game-readable', 'sys-writable']
})