AuthService.php 1.7 KB

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