AuthService.php 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  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. "role" => $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. ];
  49. }, $permissions);
  50. }
  51. public function changePassword($data)
  52. {
  53. $u = Auth::user();
  54. if (!$u->checkPassword($data['old_password'])) {
  55. throw new ClientException("原密码错误");
  56. }
  57. $u->password = $u->hashPassword($data['password']);
  58. $u->save();
  59. return true;
  60. }
  61. public function encryptToken($uid)
  62. {
  63. return md5($uid) . $uid;
  64. }
  65. public function decryptToken($token)
  66. {
  67. return substr($token, 32);
  68. }
  69. }