AuthService.php 3.0 KB

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