AuthService.php 2.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. <?php
  2. namespace app\admin\service\auth;
  3. use app\model\SysRole;
  4. use app\model\SysUser;
  5. use support\Db;
  6. use support\Request;
  7. use Tinywan\Jwt\JwtToken;
  8. class AuthService
  9. {
  10. public static function login($params)
  11. {
  12. DB::beginTransaction();
  13. try {
  14. $user = SysUser::findByLoginName($params['username']);
  15. if (!$user || $user->user_login_pass != md5(sha1($params['password']))) {
  16. throw new \Exception('账号 / 密码错误');
  17. }
  18. // 禁用用户
  19. if ($user->user_status == 'DISABLED') {
  20. throw new \Exception('当前账户已禁用,请联系管理员');
  21. }
  22. switch ($user->user_status) {
  23. case 'DISABLED':
  24. throw new \Exception('当前账户已禁用,请联系管理员');
  25. break;
  26. case 'PENDING':
  27. // 待激活用户登录后自动激活
  28. $user->user_status = 'ACTIVED';
  29. if (!$user->save()) {
  30. throw new \Exception('用户状态修改失败');
  31. }
  32. break;
  33. default:
  34. break;
  35. }
  36. $extend = [
  37. 'id' => $user->user_id,
  38. 'client' => 'admin',
  39. 'name'=> $user->user_name
  40. ];
  41. $token = JwtToken::generateToken($extend);
  42. $user->user_login_status = "ONLINE";
  43. $user->save();
  44. // 提交事务
  45. DB::commit();
  46. // 写操作日志
  47. _syslog("登录", "管理员【" . $params['username'] . "】登录系统; ID:" . $user->user_id, false, ['username'=>$params['username']], $user->user_id);
  48. return json_success('', $token);
  49. } catch (\Exception $e) {
  50. // 回滚事务
  51. DB::rollBack();
  52. return json_fail($e->getMessage());
  53. }
  54. }
  55. /**
  56. * @Desc 刷新token
  57. * @Author Gorden
  58. * @Date 2024/2/21 17:10
  59. *
  60. * @return \support\Response
  61. */
  62. public static function refreshToken()
  63. {
  64. $token = JwtToken::refreshToken();
  65. return json_success('Token已刷新', $token);
  66. }
  67. public static function userInfo(Request $request)
  68. {
  69. $user = SysUser::select('user_id', 'join_user_role_id', 'join_user_dept_id', 'user_status', 'user_category', 'user_name', 'user_login_name', 'user_mobile', 'user_remark', 'user_extend_json', 'user_addtimes')
  70. ->where('user_id', $request->adminId)
  71. ->first()
  72. ->toArray();
  73. $user['roleName'] = '';
  74. if (!empty($user['join_user_role_id'])) {
  75. $role = SysRole::where('role_id', $user['join_user_role_id'])->first();
  76. if (!empty($role->role_name)) {
  77. $user['roleName'] = $role->role_name;
  78. }
  79. }
  80. return json_success('', $user);
  81. }
  82. }