AuthService.php 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. <?php
  2. namespace App\Modules\Admin\Services;
  3. use App\Base\BaseService;
  4. use App\Exceptions\ClientException;
  5. use App\Models\Auth\AdminPermission;
  6. use App\Models\User\User;
  7. use Illuminate\Support\Facades\Auth;
  8. class AuthService extends BaseService
  9. {
  10. public function login($data)
  11. {
  12. $u = User::wherePhone($data['username'])->orWhere("email", $data['username'])->first();
  13. if (is_null($u)) {
  14. throw new ClientException("账号或密码错误,请重新输入");
  15. }
  16. if (!$u->checkPassword($data['password'])) {
  17. throw new ClientException("账号或密码错误,请重新输入!");
  18. }
  19. if ($u->status != User::STATUS_OK) {
  20. throw new ClientException("当前用户被禁用,请联系管理员");
  21. }
  22. if (!$u->group_id) {
  23. throw new ClientException("无权限");
  24. }
  25. return [
  26. "admin_token" => $this->encryptToken($u->id),
  27. ];
  28. }
  29. public function profile()
  30. {
  31. $u = Auth::user();
  32. return [
  33. "id" => $u->id,
  34. "phone" => $u->phone,
  35. "email" => $u->email,
  36. "group" => $u->group->name,
  37. "roles" => $this->role($u),
  38. ];
  39. }
  40. public function role(User $u)
  41. {
  42. $permissions = \Arr::get($u->extra, "permissions");
  43. return array_map(function ($pid) {
  44. $per = AdminPermission::find($pid);
  45. return [
  46. "id" => $per->id,
  47. "name" => $per->name,
  48. "code" => $per->code,
  49. ];
  50. }, $permissions);
  51. }
  52. public function changePassword($data)
  53. {
  54. $u = Auth::user();
  55. if (!$u->checkPassword($data['old_password'])) {
  56. throw new ClientException("原密码错误");
  57. }
  58. $u->password = $u->hashPassword($data['password']);
  59. $u->save();
  60. return true;
  61. }
  62. public function encryptToken($uid)
  63. {
  64. return md5($uid) . $uid;
  65. }
  66. public function decryptToken($token)
  67. {
  68. return substr($token, 32);
  69. }
  70. }