AuthService.php 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  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. ];
  37. }
  38. public function changePassword($data)
  39. {
  40. $u = Auth::user();
  41. if (!$u->checkPassword($data['old_password'])) {
  42. throw new ClientException("原密码错误");
  43. }
  44. $u->password = $u->hashPassword($data['password']);
  45. $u->save();
  46. return true;
  47. }
  48. public function encryptToken($uid)
  49. {
  50. return md5($uid) . $uid;
  51. }
  52. public function decryptToken($token)
  53. {
  54. return substr($token, 32);
  55. }
  56. }