Commit d9fea626 by lincyawer

重构个人主页页面api

parent 1fa6a45e
...@@ -8,7 +8,6 @@ ...@@ -8,7 +8,6 @@
use App\Http\Service\LoginService; use App\Http\Service\LoginService;
use App\Http\Service\UserService; use App\Http\Service\UserService;
use App\Http\Service\UserTokenService; use App\Http\Service\UserTokenService;
use App\Models\user\UserInfoModel;
use App\Models\user\LoginModel; use App\Models\user\LoginModel;
use Illuminate\Http\Request; use Illuminate\Http\Request;
use Illuminate\Support\Facades\Config; use Illuminate\Support\Facades\Config;
...@@ -221,7 +220,6 @@ private function checkLoginFailedLimit($info) ...@@ -221,7 +220,6 @@ private function checkLoginFailedLimit($info)
// 只做邮件提醒 // 只做邮件提醒
$maxTimes = Config::get('website.maxPasswdIncorrectTimes', 3); // 3 30 90 $maxTimes = Config::get('website.maxPasswdIncorrectTimes', 3); // 3 30 90
// if ($wrongTimes == $maxTimes || $wrongTimes == 10 * $maxTimes || $wrongTimes == 30 * $maxTimes) {
if ($wrongTimes == $maxTimes) { if ($wrongTimes == $maxTimes) {
$body = "您的账号24小时内已错误登录{$wrongTimes}次, 为了您的账号安全,请尽快更改密码。"; $body = "您的账号24小时内已错误登录{$wrongTimes}次, 为了您的账号安全,请尽快更改密码。";
Mail::raw($body, function ($message) use ($email, $name) { Mail::raw($body, function ($message) use ($email, $name) {
......
...@@ -2,16 +2,82 @@ ...@@ -2,16 +2,82 @@
namespace App\Http\Controllers; namespace App\Http\Controllers;
use App\Http\Error;
use App\Http\Output;
use App\Http\Service\DepartmentService; use App\Http\Service\DepartmentService;
use App\Http\Service\LdapManagerService;
use App\Http\Service\PermService; use App\Http\Service\PermService;
use App\Http\Service\UserService; use App\Http\Service\UserService;
use App\Models\queue\QueuedModel;
use App\Models\user\DepartmentModel; use App\Models\user\DepartmentModel;
use App\Models\user\PositionModel; use App\Models\user\PositionModel;
use App\Models\user\PositionPermModel;
use App\Models\user\UserInfoModel;
use App\Models\user\UserModel;
use Illuminate\Http\Request; use Illuminate\Http\Request;
use Illuminate\Support\Facades\Config; use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Mockery\CountValidator\Exception;
class UserController extends Controller class UserController extends Controller
{ {
//用户详情
public function info(Request $request, $userId = 0)
{
// 用户角色
$user_role = PermService::getUserRole($request);
$userPerms = PermService::getUserAllPerms($request->user->userId, $user_role); // 用户权限
$page_info = [
'role' => $user_role,
'userPerms' => $userPerms,
];
if ($userId == 0) {
$userId = $request->user->userId;
}
// 默认管理员账号或管理、经理、技术、产品权限
$isAdmin = in_array($request->user->email, Config::get('website.admin')) || in_array($page_info['role'],
[1, 2, 3, 4]);
// 非本人账号、非管理员、无编辑权限
$isLimit = ($request->user->userId != $userId && !$isAdmin && !in_array('user_userlist_edit',
$page_info['userPerms']));
$user_info = UserService::getUserInfo($userId, $isLimit);
if (!$user_info) {
abort(404);
}
// 如果头像地址不是正确的url,那么为空字符串,避免修改信息失败
if (!filter_var($user_info->header, FILTER_VALIDATE_URL)) {
$user_info->header = "";
}
$department_id_name_parentId_list = DepartmentModel::getDepList();
$department_tree = UserService::generateTree($department_id_name_parentId_list);
$data = [
'role' => $user_role,
'userPerms' => $userPerms,
'limitInfo' => (bool)$isLimit,
'username' => $request->user->email,
'header' => $request->user->header,
'title' => '用户信息',
'userId' => $userId,
'active' => $userId == $request->user->userId ? 'my' : 'userlist',
'isAdmin' => $isAdmin,
'userInfo' => $user_info,
'department_html' => DepartmentService::getDepartmentHtml($department_tree),
'position' => PositionModel::getPositionNameMap(), // 职位
'paths' => [
['href' => '/userlist', 'title' => '帐号列表'],
['href' => '/info/' . $userId, 'title' => '用户信息']
],
];
setcookie('crsf_token', bin2hex(openssl_random_pseudo_bytes(16)), 0, '/');
return view('user.info', $data);
}
public function my(Request $req, $userId = 0) public function my(Request $req, $userId = 0)
{ {
$user = $req->getUserResolver()(); $user = $req->getUserResolver()();
...@@ -53,6 +119,211 @@ public function my(Request $req, $userId = 0) ...@@ -53,6 +119,211 @@ public function my(Request $req, $userId = 0)
setcookie('crsf_token', bin2hex(openssl_random_pseudo_bytes(16)), 0, '/'); setcookie('crsf_token', bin2hex(openssl_random_pseudo_bytes(16)), 0, '/');
return view('user.info', $data); return view('user.info', $data);
} }
public function update(Request $request)
{
try {
$token = $request->input('token', '');
if ($token != $request->cookie('crsf_token')) {
Log::error("Bad Request: invaild token $token"); // 记录到日志文件
return Output::makeResult($request, Error::E_PARAM, "Bad Request: invaild token $token");
}
$info = UserService::extractUserInfoFromReq($request, false);
if (empty($info['name'])) {
return Output::makeResult($request, Error::E_PARAM, "中文名没有设置");
}
if (!$info['department_id']) {
return Output::makeResult($request, Error::E_PARAM, "部门没有设置");
}
$ret = UserService::checkUserInfo($info);
if ($ret !== true) {
$last_err_msg = array_pop($ret);
Log::error($last_err_msg); // 记录到日志文件
return Output::makeResult($request, Error::E_PARAM, $last_err_msg);
}
if (!isset($info['userId'])) {
Log::error("userId not set"); // 记录到日志文件
return Output::makeResult($request, Error::E_PARAM, "userId not set");
}
$userId = $info['userId'];
// unset($info['userId']);
$info['mtime'] = date('Y-m-d H:i:s');
$email = $request->user->email;;
// var_dump($request->getUserResolver()());
if (!in_array($email, Config::get('website.admin')) && $userId == $request->getUserResolver()()->userId) {
unset($info['status']);
}
$user = UserInfoModel::getInfoById($userId);
$info['email'] = $user[0]->email;
DB::transaction(function () use ($info, $userId) {
DB::table('user_info')->where('userId', $userId)->update($info);
// 获取用户角色绑定权限
$rolePerm = PositionPermModel::getUserRolePermList($info['position_id']);
$del = PermService::delUserPerms($userId);
if ($del === false) {
throw new Exception("清除用户所有权限失败");
}
if (!empty($rolePerm)) {
foreach ($rolePerm as $v) {
$res = PermService::setUserRolePerm($info, $v['bid'], $v['role_id']);
if ($res === false) {
throw new Exception("新增用户权限失败");
}
}
} else {
// 添加账号系统运营权限
$info['title'] = '内部用户管理系统';
$res = PermService::setupUserPerm($info);
if ($res === false) {
throw new Exception("新增账号系统运营权限失败");
}
}
DepartmentService::getSubDepartmentId(Config('config.online_sales_department_id'),
$online_sales); // 获取线上销售部门ID集合
// 若用户属于线上部门,则操作CRM员工卡
if (in_array($info['department_id'], $online_sales)) {
if (isset($info['status']) && $info['status'] == 4) { // 离职
$res = EmployeeCardModel::delById($userId);
} else { // 在职
$employee = [];
$employee['sale_name'] = $info['name'];
$employee['email'] = $info['email'];
$res = EmployeeCardModel::create($userId, $employee);
}
}
});
// 若设置离职状态,且为线上销售部门,则同步到CRM
if (isset($info['status']) && $info['status'] == 4) {
$this->sysToCrm($info);
}
try {
$ldap = new LdapManagerService();
$default_ldap_group_info = Config('config.default_ldap_group_info');
$cms_department_id_with_ldap_map = Config('config.cms_department_id_with_ldap_map');
// 如果部门不一样,那么ldap需要删除用户,在重新创建用户
if ($info['department_id'] != $user->department_id) {
$root_department_id = DepartmentService::getRootDepartmentId($user->department_id);
if (isset($cms_department_id_with_ldap_map[$root_department_id])) {
$businessCategory = $cms_department_id_with_ldap_map[$root_department_id]['ldap_department_name'];
} else {
$businessCategory = $default_ldap_group_info['ldap_department_name'];
}
$ldap->ldapDelete($user->email, $businessCategory);
// 重新创建ldap用户
$userInfo = DB::table('user_info')->where('userId', $userId)->first();
$userInfo = (array)$userInfo;
$root_department_id = DepartmentService::getRootDepartmentId($info['department_id']);
if (isset($cms_department_id_with_ldap_map[$root_department_id])) {
$userInfo['gidNumber'] = $cms_department_id_with_ldap_map[$root_department_id]['ldap_gid'];
$userInfo['businessCategory'] = $cms_department_id_with_ldap_map[$root_department_id]['ldap_department_name'];
} else {
$userInfo['gidNumber'] = $default_ldap_group_info['ldap_gid'];
$userInfo['businessCategory'] = $default_ldap_group_info['ldap_department_name'];
}
if (!$ldap->ldapSearchCn($userInfo['email'], $userInfo['businessCategory'])) {
$ldap->ldapCreateUser($userInfo);
}
} else {
$root_department_id = DepartmentService::getRootDepartmentId($info['department_id']);
if (isset($cms_department_id_with_ldap_map[$root_department_id])) {
$gidNumber = $cms_department_id_with_ldap_map[$root_department_id]['ldap_gid'];
$businessCategory = $cms_department_id_with_ldap_map[$root_department_id]['ldap_department_name'];
} else {
$gidNumber = $default_ldap_group_info['ldap_gid'];
$businessCategory = $default_ldap_group_info['ldap_department_name'];
}
if (isset($info['status']) && $info['status'] == 4) {
$ldap->ldapDelete($user->email, $businessCategory);
} else {
$info['gidNumber'] = $gidNumber;
$info['businessCategory'] = $businessCategory;
$ldap->ldapUpdate($user->email, $info);
}
}
} catch (\Exception $e) {
Log::error("ldap update failed, userId={$userId}, info=" . json_encode($info));
}
if ($userId == $request->user->userId && isset($info['header']) && $info['header'] != $request->cookie('oa_header')) {
$this->setLoginCookie(null, null, $info['header'], time() + self::expireTime());
}
// 推入到队列
if (strpos(Config('website.user_url'), 'liexin') === false) { // 本地暂不推队列
$saveData['type'] = 'user.syn';
$userData['userid'] = $userId;
$userData['email'] = $user->email;
$userData['name'] = $info['name'];
$userData['status'] = (isset($info['status']) && $info['status']) == 0 ? 1 : -1;
$saveData['data'] = $userData;
$queue = new QueuedModel();
$queue->pushAmq(json_encode($saveData));
}
return Output::makeResult($request, 0);
} catch (\Exception $e) {
$err_msg = "msg:{$e->getMessage()},file:{$e->getFile()},line:{$e->getLine()}";
Log::error("unknown server error: " . $err_msg); // 记录到日志文件
return Output::makeResult($request, Error::E_SERVER,
"unknown server error: " . $err_msg . ", try again");
}
}
// 账号列表
public function userlist(Request $request)
{
// 用户角色
$user_role = PermService::getUserRole($request);
$userPerms = PermService::getUserAllPerms($request->getUserResolver()()->userId, $user_role); // 用户权限
$first_page_info = UserService::getList($request);
if ($first_page_info["retcode"] != 0) {
abort(500);
}
$isAdmin = in_array($request->getUserResolver()()->email, Config::get('website.admin'));
$data = [
'username' => $request->getUserResolver()()->email,
'role' => $user_role,
'userPerms' => $userPerms,
'header' => $request->getUserResolver()()->header,
'title' => '帐号列表',
'department_select' => DepartmentModel::getDepartmentNameWithIdArray(),
'position_select' => PositionModel::getPositionNameWithIdArray(),
'active' => 'userlist',
'isAdmin' => $isAdmin,
'list' => $first_page_info,
'paths' => [
['href' => '/userlist', 'title' => '帐号列表']
]
];
return view('user.userlist', $data);
}
public static function expireTime()
{
$expire = Config::get('website.skeyExpire');
return $expire ? $expire : 3600 * 12;
}
} }
......
...@@ -113,7 +113,7 @@ public static function Autograph() ...@@ -113,7 +113,7 @@ public static function Autograph()
function Crumbs($menus, $uri) function Crumbs($menus, $uri)
{ {
$actives = []; $actives = [];
CheckActive($menus, $actives, $uri); Functions::CheckActive($menus, $actives, $uri);
$ret = ''; $ret = '';
foreach ($actives as $k => $v) { foreach ($actives as $k => $v) {
if ($k == count($actives) - 1) { if ($k == count($actives) - 1) {
...@@ -141,7 +141,7 @@ static function CheckActive($menus, &$arr, $url) ...@@ -141,7 +141,7 @@ static function CheckActive($menus, &$arr, $url)
if (isset($menu->href) && ($menu->href == $url || ($menu->href == '/' && $url == '//'))) if (isset($menu->href) && ($menu->href == $url || ($menu->href == '/' && $url == '//')))
return true; return true;
if (isset($menu->childs) && count($menu->childs) > 0) { // 多级菜单递归查找 if (isset($menu->childs) && count($menu->childs) > 0) { // 多级菜单递归查找
$ret = CheckActive($menu->childs, $arr, $url); $ret = Functions::CheckActive($menu->childs, $arr, $url);
if ($ret) if ($ret)
return $ret; return $ret;
} }
......
...@@ -43,6 +43,7 @@ class Kernel extends HttpKernel ...@@ -43,6 +43,7 @@ class Kernel extends HttpKernel
'api' => [ 'api' => [
// \Laravel\Sanctum\Http\Middleware\EnsureFrontendRequestsAreStateful::class, // \Laravel\Sanctum\Http\Middleware\EnsureFrontendRequestsAreStateful::class,
'throttle:api', 'throttle:api',
\App\Http\Middleware\CheckLogin::class,
\Illuminate\Routing\Middleware\SubstituteBindings::class, \Illuminate\Routing\Middleware\SubstituteBindings::class,
], ],
'noauth' => [], 'noauth' => [],
......
...@@ -36,7 +36,7 @@ public function handle($request, Closure $next) ...@@ -36,7 +36,7 @@ public function handle($request, Closure $next)
$user = (object)$ret['data']; $user = (object)$ret['data'];
$user->header = $request->cookie('oa_header'); $user->header = $request->cookie('oa_header');
// $request->user= $user; $request->user= $user;
$request->setUserResolver(function () use ($user) { $request->setUserResolver(function () use ($user) {
return $user; return $user;
}); });
......
...@@ -2,14 +2,21 @@ ...@@ -2,14 +2,21 @@
namespace App\Http\Service; namespace App\Http\Service;
use App\Models\CommonModel;
use App\Models\user\DepartmentModel; use App\Models\user\DepartmentModel;
class DepartmentService class DepartmentService extends CommonModel
{ {
protected $table = 'user_department';
protected $primaryKey = 'department_id';
protected $guarded = ['department_id'];
// protected $fillable = ['department_name', 'author', 'last_author'];
const CREATED_AT = 'ctime';
const UPDATED_AT = 'mtime';
// 获取菜单 // 获取菜单
public static function getDepartmentHtml() public static function getDepartmentHtml()
{ {
$department_id_name_parentId_list = DepartmentModel::getDepartmentIdNameParentIdList(); $department_id_name_parentId_list = DepartmentModel::getDepList();
$department_tree = self::generateTree($department_id_name_parentId_list); $department_tree = self::generateTree($department_id_name_parentId_list);
return self::makeDepartmentHtml($department_tree); return self::makeDepartmentHtml($department_tree);
} }
...@@ -73,18 +80,22 @@ public static function getSubDepartmentId($department_id, &$department_ids) ...@@ -73,18 +80,22 @@ public static function getSubDepartmentId($department_id, &$department_ids)
return $department_ids; return $department_ids;
} }
// 获取最顶层部门id // 获取最顶层部门id
public static function getRootDepartmentId($department_id) public static function getRootDepartmentId($department_id)
{ {
if (empty($department_id)) { if (empty($department_id)) {
return $department_id; return $department_id;
} }
$department_info = DepartmentModel::getDepartmentById($department_id); $department_info = self::getDepartmentById($department_id);
if ($department_info['parent_id']) { if ($department_info['parent_id']) {
return self::getRootDepartmentId($department_info['parent_id']); return self::getRootDepartmentId($department_info['parent_id']);
} }
return ($department_info) ? $department_info['department_id'] : 0; return ($department_info) ? $department_info['department_id'] : 0;
} }
// 根据部门id,获取部门信息
public static function getDepartmentById($department_id)
{
$res = self::where('department_id', $department_id)->first();
return ($res) ? $res->toArray() : [];
}
} }
<?php
namespace App\Http\Service;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\Log;
class LdapManagerService
{
// LDAP variables
private $ldaphost;
private $ldaprdn;
private $ldappass;
private $ldapport;
private static $fields = [
'email' => 'mail',
'name' => 'displayName',
'workNumber' => 'employeeNumber',
'mobile' => 'mobile',
'introduction' => 'description',
'address' => 'street',
'province' => 'st',
'header' => 'jpegPhoto',
];
public function __construct()
{
$config = Config::get('website.ldap');
$this->ldaphost = $config['host'];
$this->ldaprdn = $config['dn'];
$this->ldappass = $config['passwd'];
$this->ldapport = $config['port'];
$dn_arr = explode(",", $this->ldaprdn);
array_shift($dn_arr);
$this->ldapUserOu = "ou=Group," . implode(",", $dn_arr);
}
public function ldapCreateUser($info)
{
if (!function_exists('ldap_connect')) {
Log::error("ldap not installed");
return false;
}
if (empty($info['engName']) || empty($info['userId'])) {
Log::error("ldapCreateUser : empty engName or userId");
throw new \Exception("ldapCreateUser : empty engName or userId");
}
Log::info("execute ldapCreateUser" . $info['userId']);
// Connecting to LDAP
$ldapconn = ldap_connect($this->ldaphost, $this->ldapport);
if (!$ldapconn) {
Log::error("Could not connect to {$this->ldaphost}");
throw new \Exception("Could not connect to {$this->ldaphost}");
}
ldap_set_option($ldapconn, LDAP_OPT_PROTOCOL_VERSION, 3);
// binding to ldap server
$ldapbind = ldap_bind($ldapconn, $this->ldaprdn, $this->ldappass);
if (!$ldapbind) {
Log::error("Could not bind to {$this->ldaprdn}");
throw new \Exception("Could not bind to {$this->ldaprdn}");
}
$dn = "cn=" . $info['email'] . ",cn={$info['businessCategory']}," . $this->ldapUserOu;
$temp['cn'] = $info['email'];
$temp['sn'] = $info['engName'];
$temp['uid'] = $info['userId'];
$temp['gidNumber'] = $info['gidNumber'];
$temp['businessCategory'] = $info['businessCategory'];
$temp['uidNumber'] = $info['userId'];
$temp['givenName'] = $info['engName'];
$temp['objectclass'] = ["top", "posixAccount", "inetOrgPerson"];
$temp['homeDirectory'] = "/home/users/{$info['engName']}";
$temp['userPassword'] = '{MD5}' . base64_encode(pack('H*', md5("123456")));
foreach (self::$fields as $from => $to) {
if (!empty($info[$from])) {
$temp[$to] = $info[$from];
}
}
$ret = ldap_add($ldapconn, $dn, $temp);
if (!$ret) {
Log::error("ldap_add failed");
}
ldap_close($ldapconn);
return $ret ? true : false;
}
public function ldapUpdate($email, $info)
{
if (!function_exists('ldap_connect')) {
Log::error("ldap not installed");
return false;
}
assert(!empty($info));
Log::info("execute ldapUpdate " . $email);
// Connecting to LDAP
$ldapconn = ldap_connect($this->ldaphost, $this->ldapport);
if (!$ldapconn) {
Log::error("Could not connect to {$this->ldaphost}");
throw new \Exception("Could not connect to {$this->ldaphost}");
}
ldap_set_option($ldapconn, LDAP_OPT_PROTOCOL_VERSION, 3);
// binding to ldap server
$ldapbind = ldap_bind($ldapconn, $this->ldaprdn, $this->ldappass);
if (!$ldapbind) {
Log::error("Could not bind to {$this->ldaprdn}");
throw new \Exception("Could not bind to {$this->ldaprdn}");
}
$dn = "cn=" . $email . ",cn={$info['businessCategory']}," . $this->ldapUserOu;
foreach (self::$fields as $from => $to) {
if (!empty($info[$from])) {
$update[$to] = $info[$from];
} else {
$update[$to] = Array();
}
}
$update['gidNumber'] = $info['gidNumber'];
$update['businessCategory'] = $info['businessCategory'];
$ret = ldap_modify($ldapconn, $dn, $update);
if (!$ret) {
Log::error("ldap_modify failed : update failed");
}
ldap_close($ldapconn);
return $ret ? true : false;
}
public function ldapResetPasswd($email, $passwd, $ldap_group_name)
{
if (!function_exists('ldap_connect')) {
Log::error("ldap not installed");
return false;
}
Asset(!empty($passwd));
Log::info("ldapResetPasswd " . $email);
// Connecting to LDAP
$ldapconn = ldap_connect($this->ldaphost, $this->ldapport);
if (!$ldapconn) {
Log::error("Could not connect to {$this->ldaphost}");
throw new \Exception("Could not connect to {$this->ldaphost}");
}
ldap_set_option($ldapconn, LDAP_OPT_PROTOCOL_VERSION, 3);
// binding to ldap server
$ldapbind = ldap_bind($ldapconn, $this->ldaprdn, $this->ldappass);
if (!$ldapbind) {
Log::error("Could not bind to {$this->ldaprdn}");
throw new \Exception("Could not bind to {$this->ldaprdn}");
}
$passwd = '{MD5}' . base64_encode(pack('H*', md5($passwd)));
$dn = "cn=" . $email . ",cn={$ldap_group_name}," . $this->ldapUserOu;
$reset['userPassword'] = $passwd;
$ret = ldap_modify($ldapconn, $dn, $reset);
if (!$ret) {
Log::error("ldap_modify failed: reset password failed");
}
ldap_close($ldapconn);
return $ret ? true : false;
}
public function ldapSearchCn($email, $ldap_group_name)
{
if (!function_exists('ldap_connect')) {
Log::error("ldap not installed");
return false;
}
Assert(!empty($email));
Log::info("execute ldapSearchCn " . $email);
// Connecting to LDAP
$ldapconn = ldap_connect($this->ldaphost, $this->ldapport);
if (!$ldapconn) {
Log::error("Could not connect to {$this->ldaphost}");
throw new \Exception("Could not connect to {$this->ldaphost}");
}
ldap_set_option($ldapconn, LDAP_OPT_PROTOCOL_VERSION, 3);
// binding to ldap server
$ldapbind = ldap_bind($ldapconn, $this->ldaprdn, $this->ldappass);
if (!$ldapbind) {
Log::error("Could not bind to {$this->ldaprdn}");
throw new \Exception("Could not bind to {$this->ldaprdn}");
}
$ret = ldap_search($ldapconn, "cn={$ldap_group_name}," . $this->ldapUserOu, "(cn={$email})");
if (!$ret) {
Log::error("ldap_search error");
return false;
}
$entry = ldap_first_entry($ldapconn, $ret);
ldap_close($ldapconn);
return $entry ? true : false;
}
public function ldapDelete($email, $ldap_department_name)
{
if (!function_exists('ldap_connect')) {
Log::error("ldap not installed");
return false;
}
Log::info("execute ldapDelete " . $email);
// Connecting to LDAP
$ldapconn = ldap_connect($this->ldaphost, $this->ldapport);
if (!$ldapconn) {
Log::error("Could not connect to {$this->ldaphost}");
throw new \Exception("Could not connect to {$this->ldaphost}");
}
ldap_set_option($ldapconn, LDAP_OPT_PROTOCOL_VERSION, 3);
// binding to ldap server
$ldapbind = ldap_bind($ldapconn, $this->ldaprdn, $this->ldappass);
if (!$ldapbind) {
Log::error("Could not bind to {$this->ldaprdn}");
throw new \Exception("Could not bind to {$this->ldaprdn}");
}
$dn = "cn=" . $email . ",cn={$ldap_department_name}," . $this->ldapUserOu;
if (!$this->ldapSearchCn($email, $ldap_department_name)) {
return true;
}
$ret = ldap_delete($ldapconn, $dn);
if (!$ret) {
Log::error("ldap_delete failed : delete failed");
}
ldap_close($ldapconn);
return $ret ? true : false;
}
}
<?php <?php
namespace App\Http\Service; namespace App\Http\Service;
use App\Http\Error;
use App\Http\Output;
use App\Models\user\DepartmentModel;
use App\Models\user\TBusinessConfigModel; use App\Models\user\TBusinessConfigModel;
use App\Models\user\TRolePermModel; use App\Models\user\TRolePermModel;
use App\Models\user\TUserPermModel; use App\Models\user\TUserPermModel;
use App\Models\user\UserInfoModel;
use Illuminate\Http\Request; use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
class PermService class PermService
{ {
...@@ -18,10 +25,11 @@ class PermService ...@@ -18,10 +25,11 @@ class PermService
'采购' => 8, '采购' => 8,
'行政' => 9, '行政' => 9,
]; ];
// 检查用户是否具有系统访问权限 // 检查用户是否具有系统访问权限
public static function checkAccess($request): bool public static function checkAccess(Request $request): bool
{ {
$user_id = $request->user->userId; $user_id = $request->getUserResolver()()->userId;
$role = self::getUserRole($request); $role = self::getUserRole($request);
if ($role == 1) { if ($role == 1) {
...@@ -40,6 +48,7 @@ public static function checkAccess($request): bool ...@@ -40,6 +48,7 @@ public static function checkAccess($request): bool
return false; return false;
} }
// 获取用户角色:1-管理员,0-用户 // 获取用户角色:1-管理员,0-用户
public static function getUserRole(Request $request): int public static function getUserRole(Request $request): int
{ {
...@@ -173,6 +182,7 @@ public static function handleMenus($menus, $perms) ...@@ -173,6 +182,7 @@ public static function handleMenus($menus, $perms)
return array_values($menus); return array_values($menus);
} }
// 获取权限菜单 // 获取权限菜单
public static function getMenuPerm($menus, $user_id) public static function getMenuPerm($menus, $user_id)
{ {
...@@ -183,4 +193,94 @@ public static function getMenuPerm($menus, $user_id) ...@@ -183,4 +193,94 @@ public static function getMenuPerm($menus, $user_id)
return false; return false;
} }
public static function getParentDepartment($id)
{
$parentId = DepartmentModel::getParentId($id);
$parentDep = DepartmentModel::getInfoById($parentId);
if(isset($parentDep[0])){
return $parentDep[0]['department_name'];
}
return '';
}
// 设置用户角色权限
public static function setUserRolePerm($info, $bid, $roleId)
{
$data = [];
$data['bid'] = $bid;
$data['userId'] = $info['userId'];
$data['roles'] = json_encode(array("{$roleId}"));
$data['perms'] = json_encode(array());
$data['username'] = $info['email'];
$data['begDate'] = date('Y-m-d');
$data['endDate'] = date('Y-m-d', time() + 15552000); // 半年
$data['ctime'] = date('Y-m-d H:i:s');
$data['mtime'] = date('Y-m-d H:i:s');
$id = TUserPermModel::setUserRoot($data);
if ($id === false) {
return false;
}
return true;
}
// 清除用户所有权限
public static function delUserPerms($userId)
{
$map = [];
if (is_array($userId)) {
$str_userid = implode(',', $userId);
$map[] = [DB::raw("userId in ({$str_userid})"), '1'];
} else {
$map['userId'] = $userId;
}
return TUserPermModel::deleteUserRoot($map);
}
// 设置用户权限
public static function setupUserPerm($info, $rolename = '运营')
{
$business_info = TBusinessConfigModel::getBusinessInfoByTitle($info['title']);
$data['bid'] = $business_info->bid;
$data['userId'] = $info['userId'];
// 检查是否存在
$ret = TUserPermModel::getBidUserId($data);
if ($ret) {
$data['roles'] = json_encode(["{self::roles[$rolename]}"]);
$data['mtime'] = date('Y-m-d H:i:s');
$update = TUserPermModel::updateRoleNameMtime($data);
if ($update === false) {
return false;
}
return true;
}
// 不存在则创建
$role = TRolePermModel::getBidUsername($business_info->bid, $rolename);
$data['roles'] = json_encode(array("{$role->roleId}"));
$data['perms'] = json_encode(array());
$data['username'] = $info['email'];
$data['begDate'] = date('Y-m-d');
$data['endDate'] = date('Y-m-d', time() + 15552000); // 半年
$data['ctime'] = date('Y-m-d H:i:s');
$data['mtime'] = date('Y-m-d H:i:s');
$id = TUserPermModel::setUserRoot($data);
if ($id === false) {
return false;
}
return true;
}
} }
...@@ -2,19 +2,19 @@ ...@@ -2,19 +2,19 @@
namespace App\Http\Service; namespace App\Http\Service;
use App\Http\Error;
use App\Http\Output;
use App\Models\user\UserInfoModel; use App\Models\user\UserInfoModel;
use App\Models\user\UserModel; use App\Models\user\UserModel;
use http\Client\Curl\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
class UserService class UserService
{ {
const SLAT_LENGTH = 32; // 用户密码加盐的随机数 const SLAT_LENGTH = 32; // 用户密码加盐的随机数
const TABLE_NAME = 'user'; // 表名 const TABLE_NAME = 'user'; // 表名
public static function createSlat()
{
return base64_encode(openssl_random_pseudo_bytes(self::SLAT_LENGTH));
}
public static function createPasswd($passwd, $slat) public static function createPasswd($passwd, $slat)
{ {
return hash('sha256', md5($passwd) . $slat); return hash('sha256', md5($passwd) . $slat);
...@@ -23,8 +23,13 @@ public static function createPasswd($passwd, $slat) ...@@ -23,8 +23,13 @@ public static function createPasswd($passwd, $slat)
public static function getUserInfo($userId, $isLimit) public static function getUserInfo($userId, $isLimit)
{ {
$user_info = UserInfoModel::getNameWithEngNameMap($userId); $user_info = UserInfoModel::getNameWithEngNameMap($userId);
// UserInfoModel::getUsersByIds($userId); $info = UserInfoModel::getInfoById($userId);
// var_dump($user_info);exit(); $boss = UserInfoModel::getInfoById($info[0]->superior);
$user_info = $info[0];
if(isset($boss[0])){
$user_info->sup_engName = $boss->engName;
$user_info->sup_name = $boss->name;
}
if ($isLimit) { if ($isLimit) {
unset($user_info->idCard); unset($user_info->idCard);
unset($user_info->birthday); unset($user_info->birthday);
...@@ -47,16 +52,6 @@ public static function getUserInfo($userId, $isLimit) ...@@ -47,16 +52,6 @@ public static function getUserInfo($userId, $isLimit)
return $user_info; return $user_info;
} }
public static function getUserListMapByIds($user_ids)
{
$user_list = UserInfoModel::getUsersByIds($user_ids);
$user_list_map = [];
if ($user_list) {
$user_list_map = array_column($user_list, null, 'userId');
}
return $user_list_map;
}
public static function getUserInfoByName($type, $name) public static function getUserInfoByName($type, $name)
{ {
$userInfo = UserInfoModel::QueryWhere([ $userInfo = UserInfoModel::QueryWhere([
...@@ -89,4 +84,218 @@ public static function getUserInfoByName($type, $name) ...@@ -89,4 +84,218 @@ public static function getUserInfoByName($type, $name)
$userInfo[0]->status = $metaUser[0]->status; $userInfo[0]->status = $metaUser[0]->status;
return $userInfo; return $userInfo;
} }
public static function getList(Request $request): array
{
$count = $request->input('count', 20);
$page = $request->input('page', 1);
$key = $request->input('key', '');
$value = trim($request->input('value', ''));
if ($count <= 0 || $count > 100) {
Log::error("invalid count = {$count}"); // 记录到日志文件
return Output::makeResult($request, Error::E_PARAM, "invalid count = {$count}");
}
if ($page <= 0) {
Log::error("invalid page = {$page}"); // 记录到日志文件
return Output::makeResult($request, Error::E_PARAM, "invalid page = {$page}");
}
try {
$whereList = [];
if (!empty($_REQUEST['key']['userId'])) {
$whereList[] = ['userId', $_REQUEST['key']['userId']];
}
if (!empty($_REQUEST['key']['name'])) {
$whereList[] = ['name', 'LIKE', $_REQUEST['key']['name'] . "%"];
}
if (!empty($_REQUEST['key']['email'])) {
$whereList[] = ['email', 'LIKE', $_REQUEST['key']['email'] . "%"];
}
if (!empty($_REQUEST['key']['department_id'])) {
$whereList[] = ['department_id', $_REQUEST['key']['department_id']];
}
if (!empty($_REQUEST['key']['position_id'])) {
$whereList[] = ['position_id', $_REQUEST['key']['position_id']];
}
// $q->where($key, 'LIKE', $value . "%");
$result = UserInfoModel::queryLimitOffset($whereList,$count,($page - 1) * $count);
$total = $result['total'];
$users = $result['data'];
$list = [];
foreach ($users as $u) {
$list[] = [
'userId' => $u->userId,
'name' => $u->name,
'email' => $u->email,
'code_sn' => $u->code_sn,
'header' => $u->header,
'engName' => $u->engName,
'mobile' => $u->mobile,
'ctime' => $u->ctime,
'department_id' => $u->department_id,
'department_name' => $u->department_name,
'position_id' => $u->position_id,
'position_name' => $u->position_name,
'jobLevel' => $u->jobLevel,
'status' => $u->status,
'qq' => $u->qq,
];
}
$i = 0;
foreach ($list as $key => $value) {
//获取上级部门名称
$list[$key]['parent_department_name'] = PermService::getParentDepartment($value['department_id']);
$list[$key]['index'] = ++$i;
}
$data = ['page' => $page, 'count' => $count, 'total' => $total, 'list' => $list];
return Output::makeResult($request, 0, null, $data);
} catch (\Exception $e) {
Log::error("unknown server: " . $e->getMessage()); // 记录到日志文件
return Output::makeResult($request, Error::E_SERVER, "get failed: " . $e->getMessage(), $e->getTrace());
}
}
public static function extractUserInfoFromReq(Request $request, $isRegistered)
{
$fields = [
'name',
'mobile',
'code_sn',
'gender',
'idCard',
'tel',
'workAddr',
'fax',
'degree',
'schoole',
'qq',
'wechat',
'header',
'country',
'province',
'city',
'address',
'abo',
'birthday',
'unemployDate',
'entryDate',
'personSite',
'introduction',
'emergencyPeople',
'emergencyPhone',
'status',
'department_id',
'department_name',
'position_id',
'position_name',
'workNumber',
'jobLevel',
'dingtalk',
'superior',
];
$data = [];
self::getValue($request, $fields, $data);
if ($isRegistered) {
self::getValue($request, ['email', 'engName'], $data);
} else {
self::getValue($request, ['userId'], $data);
}
return $data;
}
public static function checkUserInfo($info)
{
if (!empty($info['userId']) && $info['userId'] <= 0) {
return ['userId' => '错误的用户id: ' . $info['userId']];
}
if (!empty($info['email'])) {
if (!filter_var($info['email'], FILTER_VALIDATE_EMAIL) || !LoginService::checkEmailDomain($info['email'])) {
return ['email' => '错误的邮件地址: ' . $info['email']];
}
}
if (!empty($info['engName']) && (strlen($info['engName']) >= 32 || !preg_match('/^[0-9A-Za-z_.]+$/',
$info['engName']))) {
return ['engName' => '错误的用户名: ' . $info['engName']];
}
if (!empty($info['workNumber']) && !preg_match('/^[A-Za-z0-9]+$/', $info['workNumber'])) {
return ['workAddr' => '错误的工号: ' . $info['workNumber']];
}
if (!empty($info['mobile']) && !preg_match('/^[1-9][0-9]{10}$/', $info['mobile'])) {
return ['mobile' => '错误的手机号: ' . $info['mobile']];
}
if (!empty($info['gender']) && ($info['gender'] != 1 && $info['gender'] != 2)) {
return ['gender' => '错误的性别: ' . $info['gender']];
}
if (!empty($info['idCard']) && !preg_match('/^[0-9]{17}([0-9]|[xX])$/', $info['idCard'])) {
return ['idCard' => '错误的身份证号: ' . $info['idCard']];
}
if (!empty($info['tel']) && !preg_match('/^([0-9]{3,4}-)?[0-9]{6,8}(-[0-9]+)?$/', $info['tel'])) {
return ['idCard' => '错误的座机号: ' . $info['tel']];
}
if (!empty($info['fax']) && !preg_match('/^([0-9]{3,4}-)?[0-9]{6,8}(-[0-9]+)$/', $info['fax'])) {
return ['fax' => '错误的传真号: ' . $info['fax']];
}
if (!empty($info['qq']) && (string)(int)$info['qq'] != $info['qq']) {
return ['qq' => '错误的QQ号: ' . $info['qq']];
}
if (!empty($info['header']) && !filter_var($info['header'], FILTER_VALIDATE_URL)) {
return ['header' => '错误的头像url: ' . $info['qq']];
}
if (!empty($info['birthday']) && strtotime($info['birthday']) === false) {
return ['birthday' => '错误的生日: ' . $info['birthday']];
}
if (!empty($info['unemployDate']) && strtotime($info['unemployDate']) === false) {
return ['unemployDate' => '错误的离职日期: ' . $info['unemployDate']];
}
if (!empty($info['entryDate']) && strtotime($info['entryDate']) === false) {
return ['entryDate' => '错误的入职日期: ' . $info['entryDate']];
}
if (!empty($info['status']) && $info['status'] != 4) {
return ['entryDate' => '错误的状态: ' . $info['status']];
}
return true;
}
private static function getValue(Request $request, $names, &$data)
{
foreach ($names as $name) {
$val = $request->input($name, null);
if ($val === null) {
continue;
}
$data[$name] = $val;
}
}
// 转换部门tree
public static function generateTree($list, $pk = 'department_id', $pid = 'parent_id', $child = '_child', $root = 0)
{
$department_tree = array();
$packData = array();
foreach ($list as $data) {
$packData[$data[$pk]] = $data;
}
foreach ($packData as $key => $val) {
if ($val[$pid] == $root) { //代表跟节点
$department_tree[] = &$packData[$key];
} else { //找到其父类
$packData[$val[$pid]][$child][] = &$packData[$key];
}
}
return $department_tree;
}
} }
...@@ -45,18 +45,4 @@ public static function createToken($userId, $expire = null) ...@@ -45,18 +45,4 @@ public static function createToken($userId, $expire = null)
} }
return $data; return $data;
} }
public static function setTokenStatus($userId, $token, $status)
{
return DB::table(self::TABLE_NAME)->where('userId', $userId)
->where('token', $token)->update(['status' => $status, 'mtime' => date('Y-m-d H:i:s')]);
}
public static function checkToken($userId, $token)
{
$count = DB::table(self::TABLE_NAME)->where('userId', $userId)
->where('status', 0)->where('token', $token)
->where('expireTime', '>=', date('Y-m-d H:i:s'))->count();
return $count == 1;
}
} }
<?php
namespace App\Models\crm;
use Illuminate\Database\Eloquent\Model;
class EmployeeCardModel extends Model
{
protected $connection = 'crm';
protected $table = 'employee_card';
protected $primaryKey = 'id';
protected $guarded = ['id'];
public $timestamps = true;
const CREATED_AT = 'create_time';
const UPDATED_AT = 'update_time';
/** * @param \DateTime|int $value * @return false|int * @author dividez */
public function fromDateTime($value)
{
return strtotime(parent::fromDateTime($value));
}
public static function delById($userId)
{
return self::where('sale_id', $userId)->delete();
}
public static function create($userId,$employee)
{
return self::updateOrCreate(['sale_id' => $userId], $employee);
}
}
<?php
namespace App\Models\queue;
use Illuminate\Database\Eloquent\Model;
use PhpAmqpLib\Connection\AMQPStreamConnection;
use PhpAmqpLib\Message\AMQPMessage;
class QueuedModel extends Model
{
public function pushAmq($content = '')
{
$config = Config('database.connections.rabbitmq');
$connection = new AMQPStreamConnection($config['host'], $config['port'], $config['login'], $config['password'],
$config['vhost']); // 创建连接
$channel = $connection->channel();
$channel->queue_declare($config['queue'], false, true, false, false);
$message = new AMQPMessage($content);
$channel->basic_publish($message, '', $config['queue']); // 推送消息
$channel->close();
$connection->close();
}
public function pullAmq($queue_name = '')
{
// $queue_name = 'test';
$config = Config('database.connections.rabbitmq');
$connection = new AMQPStreamConnection($config['host'], $config['port'], $config['login'], $config['password'],
$config['vhost']); // 创建连接
$channel = $connection->channel();
$message = $channel->basic_get($queue_name); // 取出消息
echo '<pre>';
print_r($message);
$channel->basic_ack($message->delivery_info['delivery_tag']); // 确认取出消息后会发送一个ack来确认取出来了,然后会从rabbitmq中将这个消息移除,如果删掉这段代码,会发现rabbitmq中的消息还是没有减少
$channel->close();
$connection->close();
}
// 自定义队列推送
public function pushQueue($queue_name, $content)
{
$config = Config('database.connections.rabbitmq');
$connection = new AMQPStreamConnection($config['host'], $config['port'], $config['login'], $config['password'],
$config['vhost']); // 创建连接
$channel = $connection->channel();
$channel->queue_declare($queue_name, false, true, false, false);
$message = new AMQPMessage($content);
$channel->basic_publish($message, '', $queue_name); // 推送消息
$channel->close();
$connection->close();
}
}
<?php <?php
namespace App\Models\user; namespace App\Models\user;
use App\Models\CommonModel; use App\Models\CommonModel;
...@@ -12,103 +14,28 @@ class DepartmentModel extends CommonModel ...@@ -12,103 +14,28 @@ class DepartmentModel extends CommonModel
const CREATED_AT = 'ctime'; const CREATED_AT = 'ctime';
const UPDATED_AT = 'mtime'; const UPDATED_AT = 'mtime';
public static function getDepList()
public static function getDepartmentListByIds($ids)
{
$res = self::whereIn('department_id', $ids)->get();
return ($res) ? $res->toArray() : [];
}
public static function countDepartmentId($departmentId)
{
return self::where('parent', $departmentId)->count();
}
public static function deleteDepartmentId($departmentId)
{
self::where('department_id', $departmentId)->delete();
}
public static function getDepartmentIdWithNameList($department_id)
{
return self::where('parent_id', $department_id)->select('department_id', 'department_name')->get();
}
public static function getDepartmentIdWithNameMap()
{
return self::pluck('department_name', 'department_id');
}
public static function getDepartmentIdList($department_id)
{
return self::where('department_id', $department_id)->first();
}
// 根据部门id,获取部门信息
public static function getDepartmentById($department_id)
{
$res = self::where('department_id', $department_id)->first();
return ($res) ? $res->toArray() : [];
}
public static function getDepartmentNameWithIdList($map = '')
{ {
if ($map) { return self::select('department_id', 'department_name', 'parent_id')->get()->toArray();
return self::where($map)->pluck('department_name', 'department_id')->toArray();
}
return self::pluck('department_name', 'department_id')->toArray();
}
public static function getExistDepartmentIdsByIds($depart_ids)
{
return self::whereIn('department_id', $depart_ids)
->select(['department_name', 'department_id'])
->get()
->pluck(['department_id'])->toArray();
}
public static function getDepartmentNameList($department_name)
{
return self::where('department_name', $department_name)->first();
}
public static function updateDataByDepartmentId($departmentId, $data)
{
return self::where('department_id', $departmentId)->update($data);
}
public static function createData($data)
{
return self::create($data);
}
public function fromDateTime($value)
{
return strtotime(parent::fromDateTime($value));
} }
//根据插入时间获取id public static function getParentId($id)
public static function getIdFormCtime($data)
{ {
return self::insertGetId($data); return self::select('department_id', 'department_name', 'parent_id')->where('department_id', $id)->get()->toArray();
} }
public static function getDepartmentInfoList($field) public static function getInfoById($id)
{ {
return self::select($field) return self::where('department_id', $id)->get()->toArray();
->get()
->toArray();
} }
public static function getDepartmentIdNameParentIdList() public static function getDepartmentNameWithIdArray()
{ {
return self::select('department_id', 'department_name', 'parent_id')->get()->toArray(); return self::select('department_name', 'department_id')->get();
} }
public static function getDepartmentNameWithIdArray() public static function getDepartmentIdWithNameList($department_id)
{ {
return self::lists('department_name', 'department_id'); return self::where('parent_id', $department_id)->select('department_id', 'department_name')->get();
} }
} }
...@@ -14,22 +14,4 @@ public static function insertData($data) ...@@ -14,22 +14,4 @@ public static function insertData($data)
{ {
return self::insert($data); return self::insert($data);
} }
public static function getLoginListByUserIdAndTime($userId, $expire)
{
$res = self::where('userId', $userId)
->where('expireTime', '>', $expire)->get();
return ($res) ? $res->toArray() : [];
}
// 根据条件获取列表
public static function getListByWhere($where, $page, $limit, $field = "*")
{
$query = self::select($field);
if ($where) {
$query->where($where);
}
return $query->orderBy('loginTime', 'desc')->paginate($limit, ['*'], 'page', $page)->toArray();
}
} }
...@@ -13,16 +13,6 @@ class PositionModel extends CommonModel ...@@ -13,16 +13,6 @@ class PositionModel extends CommonModel
const CREATED_AT = 'ctime'; const CREATED_AT = 'ctime';
const UPDATED_AT = 'mtime'; const UPDATED_AT = 'mtime';
public static function getPositionFieldList($where, $field, $limit, $page)
{
$query = self::select($field);
if ($where) {
$query->where($where);
}
return $query->orderBy('ctime', 'desc')
->orderBy('position_id', 'desc')
->paginate($limit, ['*'], 'page', $page)->toArray();
}
public function fromDateTime($value) public function fromDateTime($value)
{ {
...@@ -42,25 +32,7 @@ public static function getPositionNameMap() ...@@ -42,25 +32,7 @@ public static function getPositionNameMap()
return $data; return $data;
} }
public static function getPositionNameWithIdArray(){
public static function getPositionNameList($position_name) return self::select('position_name', 'position_id')->get();
{
return self::where('position_name', $position_name)->first();
}
public static function createData($data)
{
return self::create($data);
} }
public static function updatedData($position_id, $data)
{
return self::where('position_id', $position_id)->update($data);
}
public static function deleteData($position_id)
{
return self::where('position_id', $position_id)->delete();
}
} }
<?php
namespace App\Models\user;
use Illuminate\Database\Eloquent\Model;
class PositionPermModel extends Model
{
protected $table = 'user_position_perm';
protected $primaryKey = 'position_perm_id';
protected $guarded = ['position_perm_id'];
// protected $fillable = ['user_role_id', 'user_role_name', 'bid', 'business_name', 'role_id', 'role_name', 'author', 'last_author'];
const CREATED_AT = 'ctime';
const UPDATED_AT = 'mtime';
// 获取用户角色权限
public static function getUserRolePermList($position_id)
{
if (!$position_id) return false;
return self::where('position_id', $position_id)->select('position_perm_id', 'position_id', 'bid', 'role_id')->get()->toArray();
}
}
...@@ -10,23 +10,6 @@ class TBusinessConfigModel extends CommonModel ...@@ -10,23 +10,6 @@ class TBusinessConfigModel extends CommonModel
protected $primaryKey = 'bid'; protected $primaryKey = 'bid';
public $timestamps = false; public $timestamps = false;
// 获取所有业务系统名称
public static function getBusinessNameList()
{
return self::pluck('title', 'bid')->toArray();
}
//获取系统信息
public static function getBusinessInfo()
{
$domain = $_SERVER['SERVER_ADDR'] == '127.0.0.1' ? 'http://' . substr($_SERVER['HTTP_HOST'], 1) : 'http://' . $_SERVER['HTTP_HOST'];
// 根据域名查询系统业务ID
$business = self::where('url', $domain)->first();
return !empty($business) ? $business : false;
}
//根据title获取系统信息 //根据title获取系统信息
public static function getBusinessInfoByTitle($title) public static function getBusinessInfoByTitle($title)
{ {
......
...@@ -4,16 +4,16 @@ ...@@ -4,16 +4,16 @@
use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Model;
Class TRolePermModel extends Model class TRolePermModel extends Model
{ {
protected $table = 't_role_perm'; protected $table = 't_role_perm';
protected $primaryKey = 'roleId'; protected $primaryKey = 'roleId';
public $timestamps = false; public $timestamps = false;
// 获取所有业务系统角色 //获取业务id和角色名
public static function getRoles($bid) public static function getRoleInfoByRoleIdAndBid($role_id, $bid)
{ {
return self::where('bid', $bid)->pluck('name', 'roleId')->toArray(); return self::where(['roleId' => $role_id, 'bid' => $bid])->first();
} }
//获取业务id和角色名 //获取业务id和角色名
...@@ -22,9 +22,8 @@ public static function getBidUsername($bid, $roleName) ...@@ -22,9 +22,8 @@ public static function getBidUsername($bid, $roleName)
return self::where(['bid' => $bid, 'name' => $roleName])->first(); return self::where(['bid' => $bid, 'name' => $roleName])->first();
} }
//获取业务id和角色名 public static function QueryWhere(array $whereCond)
public static function getRoleInfoByRoleIdAndBid($role_id, $bid)
{ {
return self::where(['roleId' => $role_id, 'bid' => $bid])->first(); return self::where($whereCond)->get();
} }
} }
...@@ -16,39 +16,26 @@ public static function getUserIdBid($uid, $bid) ...@@ -16,39 +16,26 @@ public static function getUserIdBid($uid, $bid)
{ {
return self::where(['userId' => $uid, 'bid' => $bid])->first(); return self::where(['userId' => $uid, 'bid' => $bid])->first();
} }
//清除用户权限
public static function deleteUserRoot($map)
{
return self::where($map)->delete();
}
//设置角色权限 //设置角色权限
public static function setUserRoot($data) public static function setUserRoot($data)
{ {
return self::insertGetId($data); return self::insertGetId($data);
} }
//清除用户权限
//修改角色名称和时间 public static function deleteUserRoot($map)
public static function updateRoleNameMtime($data)
{ {
return self::update($data); return self::where($map)->delete();
} }
//获取业务id和用户id //获取业务id和用户id
public static function getBidUserId($data) public static function getBidUserId($whereList)
{ {
return self::where($data)->first(); return self::where($whereList)->first();
} }
// //修改角色名称和时间
public static function selectBidRoles($bid,$roleId) public static function updateRoleNameMtime($data)
{ {
return self::where(['bid','=', $bid],['roles', 'REGEXP',$roleId])->select(); return self::update($data);
}
public static function insertData($user_perm){
return self::insert($user_perm);
} }
} }
...@@ -12,92 +12,8 @@ class UserInfoModel extends commonModel ...@@ -12,92 +12,8 @@ class UserInfoModel extends commonModel
public $timestamps = false; public $timestamps = false;
const STATUS_WORKING = 0; const STATUS_WORKING = 0;
const STATUS_NOT_WORKING = 4; const STATUS_NOT_WORKING = 4;
public static function getUserDepartmentList()
{
return self::where([
'status' => self::STATUS_WORKING,
])->select([
'userId',
'name',
'department_id',
'department_name'
])->get();
}
// 根据用户ids,获取用户列表
public static function getUsersByIds($user_ids)
{
$res = self::whereIn('userId', $user_ids)->get();
return ($res) ? $res->toArray() : [];
}
// 根据用户email, 获取用户信息
public static function getUserByEmail($email)
{
$res = self::where('email', $email)->first();
return ($res) ? $res->toArray() : [];
}
public static function getDepartmentIdWithNameMap()
{
return self::where('department_id', '>', 0)->pluck('department_name', 'department_id');
}
public static function getUserIdWithEmail($data)
{
return self::where('position_id', $data)->select('userId', 'email')->get()->toArray();
}
public static function getUserIdNameEmailStatusMap()
{
return self::select('userId', 'name', 'email', 'status')->get();
}
public static function updateByDepartmentId($department_id, $data)
{
self::where('department_id', $department_id)->update($data);
}
public static function updateByPositionId($position_id, $data)
{
self::where('position_id', $position_id)->update($data);
}
public static function getUserIdNameStatus($id)
{
return self::where('userId', $id)->select('userId', 'name', 'status')->first();
}
public static function getUserNameEmailStatus($id)
{
$res = self::where('userId', $id)->select('name', 'email', 'status')->first();
return ($res) ? $res->toArray() : [];
}
public static function countIdByStatus($users, $status)
{
return self::whereIn('userId', $users)->where('status', '<>', $status)->count();
}
public static function getUserIdStatus($ids, $status)
{
return self::whereIn('userId', $ids)->select('userId', '<>', $status)->first();
}
public static function getIdByStatus($userId, $status)
{
return self::where('userId', $userId)->where('status', '<>', $status)->first();
}
public static function getIdByName($val)
{
return self::where('name', $val)->select('userId')->first();
}
public static function getNameWithEngNameMap($userId) public static function getNameWithEngNameMap($userId)
{ {
return self::leftJoin('user_info as t', 'user_info.superior', '=', 't.userId') return self::leftJoin('user_info as t', 'user_info.superior', '=', 't.userId')
...@@ -106,9 +22,25 @@ public static function getNameWithEngNameMap($userId) ...@@ -106,9 +22,25 @@ public static function getNameWithEngNameMap($userId)
->first(); ->first();
} }
public static function QueryWhere( array $whereCond) public static function getInfoById($id)
{
return self::where('userId', $id)->get();
}
public static function QueryWhere(array $whereCond)
{ {
return self::where($whereCond)->get(); return self::where($whereCond)->get();
} }
public static function queryLimitOffset($whereList, $limit, $offset)
{
$query = self::where($whereList);
$count = $query->count();
$list = $query->skip($offset)->take($limit)->orderBy("userId", "desc")->get();
return [
'data'=>$list,
'total'=>$count,
];
}
} }
...@@ -9,13 +9,14 @@ ...@@ -9,13 +9,14 @@
"license": "MIT", "license": "MIT",
"require": { "require": {
"php": "^7.4|^8.0", "php": "^7.4|^8.0",
"ext-json": "*",
"ext-openssl": "*",
"fruitcake/laravel-cors": "^2.0", "fruitcake/laravel-cors": "^2.0",
"guzzlehttp/guzzle": "^7.0.1", "guzzlehttp/guzzle": "^7.0.1",
"laravel/framework": "^8.75", "laravel/framework": "^8.75",
"laravel/sanctum": "^2.11", "laravel/sanctum": "^2.11",
"laravel/tinker": "^2.5", "laravel/tinker": "^2.5",
"ext-json": "*", "php-amqplib/php-amqplib": "^3.4"
"ext-openssl": "*"
}, },
"require-dev": { "require-dev": {
"facade/ignition": "^2.5", "facade/ignition": "^2.5",
......
...@@ -4,7 +4,7 @@ ...@@ -4,7 +4,7 @@
"Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies", "Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies",
"This file is @generated automatically" "This file is @generated automatically"
], ],
"content-hash": "c61ff82cbf0142a401a48a8161e1595a", "content-hash": "cb10e013654edb14a35ae00f1c34937b",
"packages": [ "packages": [
{ {
"name": "asm89/stack-cors", "name": "asm89/stack-cors",
...@@ -2142,6 +2142,204 @@ ...@@ -2142,6 +2142,204 @@
"time": "2022-01-27T09:35:39+00:00" "time": "2022-01-27T09:35:39+00:00"
}, },
{ {
"name": "paragonie/constant_time_encoding",
"version": "v2.6.3",
"source": {
"type": "git",
"url": "https://github.com/paragonie/constant_time_encoding.git",
"reference": "58c3f47f650c94ec05a151692652a868995d2938"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/paragonie/constant_time_encoding/zipball/58c3f47f650c94ec05a151692652a868995d2938",
"reference": "58c3f47f650c94ec05a151692652a868995d2938",
"shasum": ""
},
"require": {
"php": "^7|^8"
},
"require-dev": {
"phpunit/phpunit": "^6|^7|^8|^9",
"vimeo/psalm": "^1|^2|^3|^4"
},
"type": "library",
"autoload": {
"psr-4": {
"ParagonIE\\ConstantTime\\": "src/"
}
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"authors": [
{
"name": "Paragon Initiative Enterprises",
"email": "security@paragonie.com",
"homepage": "https://paragonie.com",
"role": "Maintainer"
},
{
"name": "Steve 'Sc00bz' Thomas",
"email": "steve@tobtu.com",
"homepage": "https://www.tobtu.com",
"role": "Original Developer"
}
],
"description": "Constant-time Implementations of RFC 4648 Encoding (Base-64, Base-32, Base-16)",
"keywords": [
"base16",
"base32",
"base32_decode",
"base32_encode",
"base64",
"base64_decode",
"base64_encode",
"bin2hex",
"encoding",
"hex",
"hex2bin",
"rfc4648"
],
"support": {
"email": "info@paragonie.com",
"issues": "https://github.com/paragonie/constant_time_encoding/issues",
"source": "https://github.com/paragonie/constant_time_encoding"
},
"time": "2022-06-14T06:56:20+00:00"
},
{
"name": "paragonie/random_compat",
"version": "v9.99.100",
"source": {
"type": "git",
"url": "https://github.com/paragonie/random_compat.git",
"reference": "996434e5492cb4c3edcb9168db6fbb1359ef965a"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/paragonie/random_compat/zipball/996434e5492cb4c3edcb9168db6fbb1359ef965a",
"reference": "996434e5492cb4c3edcb9168db6fbb1359ef965a",
"shasum": ""
},
"require": {
"php": ">= 7"
},
"require-dev": {
"phpunit/phpunit": "4.*|5.*",
"vimeo/psalm": "^1"
},
"suggest": {
"ext-libsodium": "Provides a modern crypto API that can be used to generate random bytes."
},
"type": "library",
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"authors": [
{
"name": "Paragon Initiative Enterprises",
"email": "security@paragonie.com",
"homepage": "https://paragonie.com"
}
],
"description": "PHP 5.x polyfill for random_bytes() and random_int() from PHP 7",
"keywords": [
"csprng",
"polyfill",
"pseudorandom",
"random"
],
"support": {
"email": "info@paragonie.com",
"issues": "https://github.com/paragonie/random_compat/issues",
"source": "https://github.com/paragonie/random_compat"
},
"time": "2020-10-15T08:29:30+00:00"
},
{
"name": "php-amqplib/php-amqplib",
"version": "v3.4.0",
"source": {
"type": "git",
"url": "https://github.com/php-amqplib/php-amqplib.git",
"reference": "5c537cb724f2e181183c202e63f4303935344c5f"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/php-amqplib/php-amqplib/zipball/5c537cb724f2e181183c202e63f4303935344c5f",
"reference": "5c537cb724f2e181183c202e63f4303935344c5f",
"shasum": ""
},
"require": {
"ext-mbstring": "*",
"ext-sockets": "*",
"php": "^7.1||^8.0",
"phpseclib/phpseclib": "^2.0|^3.0"
},
"conflict": {
"php": "7.4.0 - 7.4.1"
},
"replace": {
"videlalvaro/php-amqplib": "self.version"
},
"require-dev": {
"ext-curl": "*",
"nategood/httpful": "^0.2.20",
"phpunit/phpunit": "^7.5|^9.5",
"squizlabs/php_codesniffer": "^3.6"
},
"type": "library",
"extra": {
"branch-alias": {
"dev-master": "3.0-dev"
}
},
"autoload": {
"psr-4": {
"PhpAmqpLib\\": "PhpAmqpLib/"
}
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"LGPL-2.1-or-later"
],
"authors": [
{
"name": "Alvaro Videla",
"role": "Original Maintainer"
},
{
"name": "Raúl Araya",
"email": "nubeiro@gmail.com",
"role": "Maintainer"
},
{
"name": "Luke Bakken",
"email": "luke@bakken.io",
"role": "Maintainer"
},
{
"name": "Ramūnas Dronga",
"email": "github@ramuno.lt",
"role": "Maintainer"
}
],
"description": "Formerly videlalvaro/php-amqplib. This library is a pure PHP implementation of the AMQP protocol. It's been tested against RabbitMQ.",
"homepage": "https://github.com/php-amqplib/php-amqplib/",
"keywords": [
"message",
"queue",
"rabbitmq"
],
"support": {
"issues": "https://github.com/php-amqplib/php-amqplib/issues",
"source": "https://github.com/php-amqplib/php-amqplib/tree/v3.4.0"
},
"time": "2022-10-18T20:52:02+00:00"
},
{
"name": "phpoption/phpoption", "name": "phpoption/phpoption",
"version": "1.9.0", "version": "1.9.0",
"source": { "source": {
...@@ -2217,6 +2415,116 @@ ...@@ -2217,6 +2415,116 @@
"time": "2022-07-30T15:51:26+00:00" "time": "2022-07-30T15:51:26+00:00"
}, },
{ {
"name": "phpseclib/phpseclib",
"version": "3.0.17",
"source": {
"type": "git",
"url": "https://github.com/phpseclib/phpseclib.git",
"reference": "dbc2307d5c69aeb22db136c52e91130d7f2ca761"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/phpseclib/phpseclib/zipball/dbc2307d5c69aeb22db136c52e91130d7f2ca761",
"reference": "dbc2307d5c69aeb22db136c52e91130d7f2ca761",
"shasum": ""
},
"require": {
"paragonie/constant_time_encoding": "^1|^2",
"paragonie/random_compat": "^1.4|^2.0|^9.99.99",
"php": ">=5.6.1"
},
"require-dev": {
"phpunit/phpunit": "*"
},
"suggest": {
"ext-dom": "Install the DOM extension to load XML formatted public keys.",
"ext-gmp": "Install the GMP (GNU Multiple Precision) extension in order to speed up arbitrary precision integer arithmetic operations.",
"ext-libsodium": "SSH2/SFTP can make use of some algorithms provided by the libsodium-php extension.",
"ext-mcrypt": "Install the Mcrypt extension in order to speed up a few other cryptographic operations.",
"ext-openssl": "Install the OpenSSL extension in order to speed up a wide variety of cryptographic operations."
},
"type": "library",
"autoload": {
"files": [
"phpseclib/bootstrap.php"
],
"psr-4": {
"phpseclib3\\": "phpseclib/"
}
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"authors": [
{
"name": "Jim Wigginton",
"email": "terrafrost@php.net",
"role": "Lead Developer"
},
{
"name": "Patrick Monnerat",
"email": "pm@datasphere.ch",
"role": "Developer"
},
{
"name": "Andreas Fischer",
"email": "bantu@phpbb.com",
"role": "Developer"
},
{
"name": "Hans-Jürgen Petrich",
"email": "petrich@tronic-media.com",
"role": "Developer"
},
{
"name": "Graham Campbell",
"email": "graham@alt-three.com",
"role": "Developer"
}
],
"description": "PHP Secure Communications Library - Pure-PHP implementations of RSA, AES, SSH2, SFTP, X.509 etc.",
"homepage": "http://phpseclib.sourceforge.net",
"keywords": [
"BigInteger",
"aes",
"asn.1",
"asn1",
"blowfish",
"crypto",
"cryptography",
"encryption",
"rsa",
"security",
"sftp",
"signature",
"signing",
"ssh",
"twofish",
"x.509",
"x509"
],
"support": {
"issues": "https://github.com/phpseclib/phpseclib/issues",
"source": "https://github.com/phpseclib/phpseclib/tree/3.0.17"
},
"funding": [
{
"url": "https://github.com/terrafrost",
"type": "github"
},
{
"url": "https://www.patreon.com/phpseclib",
"type": "patreon"
},
{
"url": "https://tidelift.com/funding/github/packagist/phpseclib/phpseclib",
"type": "tidelift"
}
],
"time": "2022-10-24T10:51:50+00:00"
},
{
"name": "psr/container", "name": "psr/container",
"version": "1.1.2", "version": "1.1.2",
"source": { "source": {
...@@ -7708,7 +8016,9 @@ ...@@ -7708,7 +8016,9 @@
"prefer-stable": true, "prefer-stable": true,
"prefer-lowest": false, "prefer-lowest": false,
"platform": { "platform": {
"php": "^7.3|^8.0" "php": "^7.4|^8.0",
"ext-json": "*",
"ext-openssl": "*"
}, },
"platform-dev": [], "platform-dev": [],
"plugin-api-version": "2.3.0" "plugin-api-version": "2.3.0"
......
<?php <?php
use App\Http\Controllers\UserController;
use Illuminate\Http\Request; use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route; use Illuminate\Support\Facades\Route;
...@@ -19,3 +20,5 @@ ...@@ -19,3 +20,5 @@
}); });
Route::post('/login',[\App\Http\Controllers\LoginController::class, 'checkLogin']); Route::post('/login',[\App\Http\Controllers\LoginController::class, 'checkLogin']);
Route::post('/update',[\App\Http\Controllers\UserController::class, 'update']);
Route::get('/user/userlist', [\App\Http\Service\UserService::class, 'getList']);
...@@ -2,6 +2,7 @@ ...@@ -2,6 +2,7 @@
use Illuminate\Support\Facades\Route; use Illuminate\Support\Facades\Route;
use App\Http\Controllers\UserController; use App\Http\Controllers\UserController;
/* /*
|-------------------------------------------------------------------------- |--------------------------------------------------------------------------
| Web Routes | Web Routes
...@@ -16,7 +17,9 @@ ...@@ -16,7 +17,9 @@
//Route::get('/', function () { //Route::get('/', function () {
// return view('welcome'); // return view('welcome');
//}); //});
Route::get('/', function (){ Route::get('/', function () {
return "func"; return "func";
}); });
Route::get('/my', [UserController::class, 'my']);//目前路由为 /my Route::get('/my', [UserController::class, 'my']);//目前路由为 /my
Route::get('/userlist', [UserController::class, 'userlist']);
Route::get('/user/{id?}', [UserController::class, 'info']);
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or sign in to comment