AuthService.php 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  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. // 提交事务
  43. DB::commit();
  44. // 写操作日志
  45. _syslog("登录", "管理员【" . $params['username'] . "】登录系统; ID:" . $user->user_id, false, false, $user->user_id);
  46. return json_success('', $token);
  47. } catch (\Exception $e) {
  48. // 回滚事务
  49. DB::rollBack();
  50. return json_fail($e->getMessage());
  51. }
  52. }
  53. /**
  54. * @Desc 刷新token
  55. * @Author Gorden
  56. * @Date 2024/2/21 17:10
  57. *
  58. * @return \support\Response
  59. */
  60. public static function refreshToken()
  61. {
  62. $token = JwtToken::refreshToken();
  63. return json_success('Token已刷新', $token);
  64. }
  65. public static function userInfo(Request $request)
  66. {
  67. $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')
  68. ->where('user_id', $request->adminId)
  69. ->first()
  70. ->toArray();
  71. $user['roleName'] = '';
  72. if (!empty($user['join_user_role_id'])) {
  73. $role = SysRole::where('role_id', $user['join_user_role_id'])->first();
  74. if (!empty($role->role_name)) {
  75. $user['roleName'] = $role->role_name;
  76. }
  77. }
  78. return json_success('', $user);
  79. }
  80. }