AdminUser.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338
  1. <?php
  2. /**
  3. * Created by PhpStorm.
  4. * User: dingran
  5. * Date: 2019/2/19
  6. * Time: 下午4:51
  7. */
  8. namespace app\platform\modules\user\models;
  9. use app\common\events\UserActionEvent;
  10. use app\common\services\Utils;
  11. use Illuminate\Foundation\Auth\User as Authenticatable;
  12. use Illuminate\Notifications\Notifiable;
  13. use Illuminate\Support\Facades\Hash;
  14. class AdminUser extends Authenticatable
  15. {
  16. use Notifiable;
  17. public $primaryKey = 'uid';
  18. protected $table = 'yz_admin_users';
  19. public $timestamps = true;
  20. protected $guarded = [''];
  21. protected $dateFormat = 'U';
  22. public static $base = '';
  23. const ORIGINAL = '原密码错误';
  24. const NEW_AND_ORIGINAL = '新密码与原密码一致';
  25. const STORAGE = '存储相关信息表失败';
  26. const PARAM = '参数错误';
  27. const NO_DATA = '未获取到数据';
  28. const FAIL = '失败';
  29. /**
  30. * The attributes excluded from the model's JSON form.
  31. *
  32. * @var array
  33. */
  34. protected $hidden = ['password', 'remember_token'];
  35. //用户角色
  36. public function roles()
  37. {
  38. return $this->belongsToMany(Role::class, 'yz_admin_role_user', 'user_id', 'role_id');
  39. }
  40. // 判断用户是否具有某个角色
  41. public function hasRole($role)
  42. {
  43. if (is_string($role)) {
  44. return $this->roles->contains('name', $role); // ?
  45. }
  46. return !!$role->intersect($this->roles)->count();
  47. }
  48. // 判断用户是否具有某权限
  49. public function hasPermission($permission)
  50. {
  51. if (is_string($permission)) {
  52. $permission = Permission::where('name', $permission)->first();
  53. if (!$permission) {
  54. return false;
  55. }
  56. }
  57. return $this->hasRole($permission->roles);
  58. }
  59. // 给用户分配角色
  60. public function assignRole($role)
  61. {
  62. return $this->roles()->save($role);
  63. }
  64. //角色整体添加与修改
  65. public function giveRoleTo(array $RoleId)
  66. {
  67. $this->roles()->detach();
  68. $roles = Role::whereIn('id', $RoleId)->get();
  69. foreach ($roles as $v) {
  70. $this->assignRole($v);
  71. }
  72. return true;
  73. }
  74. /**
  75. * 保存数据
  76. *
  77. * @param $data
  78. * @param string $user_model
  79. * @return mixed
  80. */
  81. public static function saveData($data, $user_model = [])
  82. {
  83. $verify_res = self::verifyData($data, $user_model);
  84. if ($verify_res['sign'] == '0') {
  85. return $verify_res;
  86. }
  87. if (isset($data['re_password']) && !empty($data['re_password'])) {
  88. $verify_res['password'] = bcrypt($verify_res['password']);
  89. }
  90. unset($verify_res['re_password']);
  91. \Log::info("----------管理员用户----------", "管理员:(uid:{$verify_res['uid']})-----用户信息-----" . $verify_res . '-----参数-----' . json_encode($data));
  92. if ($verify_res->save()) {
  93. if (request()->path() != "admin/user/modify_user" && request()->path() != "admin/user/change") {
  94. if (self::saveProfile($data, $verify_res)) {
  95. return self::returnData(0, self::STORAGE);
  96. }
  97. }
  98. //如果修改了密码,清除其他登录态
  99. if (isset($data['password']) && \Auth::guard()->id() == $verify_res->getAuthIdentifier()) {
  100. \Auth::guard('admin')->logoutOtherDevices($data['password']);
  101. }
  102. return self::returnData(1);
  103. } else {
  104. return self::returnData(0, self::FAIL);
  105. }
  106. }
  107. /**
  108. * 整合数据
  109. *
  110. * @param $data
  111. * @param array $user_model
  112. * @return AdminUser|array
  113. */
  114. public static function verifyData($data, $user_model)
  115. {
  116. $data['username'] ? $data['username'] = trim($data['username']) : null;
  117. $data['password'] ? $data['password'] = trim($data['password']) : null;
  118. $data['application_number'] == 0 && !$user_model['application_number'] ? $data['application_number'] = '' : $user_model['application_number'];
  119. $data['endtime'] == 0 && !$user_model['application_number'] ? $data['endtime'] = '' : $user_model['endtime'];
  120. if (request()->path() == "admin/user/change" || (request()->path() == "admin/user/modify_user" && $data['password'])) {
  121. $data['change_password_at'] = time();
  122. $data['old_password'] = trim($data['old_password']);
  123. if (request()->path() != "admin/user/change" && (!Hash::check($data['old_password'], $user_model['password']))) {
  124. return self::returnData(0, self::ORIGINAL);
  125. } elseif (Hash::check($data['password'], $user_model['password'])) {
  126. return self::returnData(0, self::NEW_AND_ORIGINAL);
  127. }
  128. unset($data['old_password']);
  129. }
  130. $data['lastvisit'] = time();
  131. $data['lastip'] = Utils::getClientIp();
  132. unset($data['avatar']);
  133. !$user_model ? $user_model = new self() : null;
  134. !$user_model['joinip'] ? $user_model['joinip'] = Utils::getClientIp() : null;
  135. !$user_model['salt'] ? $user_model['salt'] = Utils::getClientIp() : null;
  136. $user_model->fill($data);
  137. unset($user_model['mobile']);
  138. return $user_model;
  139. }
  140. /**
  141. * 读取所有数据
  142. * @param $parames
  143. * @return mixed
  144. */
  145. public static function getList($parames)
  146. {
  147. $users = self::searchUsers($parames)->where('type', 1)->orderBy('uid', 'desc')->paginate();
  148. foreach ($users as $item) {
  149. $item['create_at'] = $item['created_at']->format('Y年m月d日');
  150. $item['status'] == 2 ? $item['state'] = '有效' : null;
  151. $item['status'] == 3 ? $item['state'] = '已禁用' : null;
  152. if ($item['endtime'] == 0) {
  153. $item['endtime'] = '永久有效';
  154. } else {
  155. if (time() > $item['endtime']) {
  156. $item['state'] = '已过期';
  157. }
  158. $item['endtime'] = date('Y年m月d日', $item['endtime']);
  159. }
  160. }
  161. return $users;
  162. }
  163. /**
  164. * 读取单条数据
  165. *
  166. * @param $uid
  167. * @return mixed
  168. */
  169. public static function getData($uid)
  170. {
  171. return self::find($uid);
  172. }
  173. /**
  174. * 检索用户信息
  175. *
  176. * @param $parame
  177. * @return mixed
  178. */
  179. public static function scopeSearchUsers($result, $parame)
  180. {
  181. $result = $result->select(['uid', 'username', 'status', 'type', 'remark', 'application_number', 'endtime', 'created_at', 'updated_at']);
  182. if ($parame['search']['status']) {
  183. if ($parame['search']['status'] == 4) {
  184. $time = [['endtime', '<', time()], ['endtime', '>', '0']];
  185. $result = $result->where($time);
  186. } else {
  187. $result = $result->where('status', $parame['search']['status'])->where(function ($query) {
  188. $query->where('endtime', '==', '0')
  189. ->orWhere('endtime', '>', time());
  190. });
  191. }
  192. }
  193. if ($parame['search']['searchtime']) {
  194. $range = [$parame['search']['times']['start'], $parame['search']['times']['end']];
  195. if ($parame['search']['searchtime'] == 1 && $parame['search']['times']['start']) {
  196. $result = $result->whereBetween('created_at', $range);
  197. } elseif ($parame['search']['searchtime'] == 2 && $parame['search']['times']['start']) {
  198. $result = $result->whereBetween('endtime', $range);
  199. }
  200. }
  201. if ($parame['search']['keyword']) {
  202. $result = $result->where(function ($query) use ($parame) {
  203. $query->where('username', 'like', '%' . $parame['search']['keyword'] . '%')
  204. ->orWhereHas('hasOneProfile', function ($query) use ($parame) {
  205. $query->where('mobile', 'like', '%' . $parame['search']['keyword'] . '%');
  206. });
  207. });
  208. }
  209. return $result;
  210. }
  211. /**
  212. * 获取随机字符串
  213. *
  214. * @param number $length 字符串长度
  215. * @param boolean $numeric 是否为纯数字
  216. * @return string
  217. */
  218. protected static function randNum($length, $numeric = FALSE)
  219. {
  220. $seed = base_convert(md5(microtime() . $_SERVER['DOCUMENT_ROOT']), 16, $numeric ? 10 : 35);
  221. $seed = $numeric ? (str_replace('0', '', $seed) . '012340567890') : ($seed . 'zZ' . strtoupper($seed));
  222. if ($numeric) {
  223. $hash = '';
  224. } else {
  225. $hash = chr(rand(1, 26) + rand(0, 1) * 32 + 64);
  226. $length--;
  227. }
  228. $max = strlen($seed) - 1;
  229. for ($i = 0; $i < $length; $i++) {
  230. $hash .= $seed{mt_rand(0, $max)};
  231. }
  232. return $hash;
  233. }
  234. /**
  235. * 保存用户信息表
  236. *
  237. * @param $data
  238. * @param $user
  239. * @return int
  240. */
  241. public static function saveProfile($data, $user)
  242. {
  243. $data = [
  244. 'mobile' => $data['mobile'],
  245. 'avatar' => $data['avatar']
  246. ];
  247. $type = 1;
  248. $content = '添加用户';
  249. $profile_model = new YzUserProfile;
  250. if (request()->path() == "admin/user/create" || request()->path() == "admin/register_admin") {
  251. $data['uid'] = $user->uid;
  252. } elseif (request()->path() == "admin/user/edit" || request()->path() == "admin/user/modify_mobile") {
  253. $type = 3;
  254. $content = '编辑用户';
  255. $profile_model = YzUserProfile::where('uid', $user->uid)->first();
  256. }
  257. $profile_model->fill($data);
  258. if (!$profile_model->save()) {
  259. return 1;
  260. }
  261. event(new UserActionEvent(self::class, $user['uid'], $type, $content . $user['username']));
  262. }
  263. /**
  264. * 获得多个平台的使用者.
  265. *
  266. * @return \Illuminate\Database\Eloquent\Relations\HasMany
  267. */
  268. public function hasManyAppUser()
  269. {
  270. return $this->hasMany(\app\platform\modules\application\models\AppUser::class, 'uid', 'uid');
  271. }
  272. /**
  273. * 获取与用户表相关的用户信息
  274. *
  275. * @return \Illuminate\Database\Eloquent\Relations\HasOne
  276. */
  277. public function hasOneProfile()
  278. {
  279. return $this->hasOne(\app\platform\modules\user\models\YzUserProfile::class, 'uid', 'uid');
  280. }
  281. /**
  282. * 获得单个平台的使用者.
  283. *
  284. * @return \Illuminate\Database\Eloquent\Relations\HasOne
  285. */
  286. public function hasOneAppUser()
  287. {
  288. return $this->hasOne(\app\platform\modules\application\models\AppUser::class, 'uid', 'uid');
  289. }
  290. public static function returnData($sign = '', $message = '')
  291. {
  292. return [
  293. 'sign' => $sign,
  294. 'message' => $message
  295. ];
  296. }
  297. }