AuthService.php 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103
  1. <?php
  2. namespace App\Modules\Mini\Services;
  3. use App\Base\BaseService;
  4. use App\Exceptions\ClientException;
  5. use App\Models\User\User;
  6. use Illuminate\Support\Arr;
  7. class AuthService extends BaseService
  8. {
  9. public function authByOpenid($openId): string
  10. {
  11. $user = User::where('openid', $openId)->first();
  12. if (is_null($user)) {
  13. $user = new User();
  14. $user->openid = $openId;
  15. $user->status = User::STATUS_OK;
  16. $user->save();
  17. }
  18. return $this->encryptToken($user->id);
  19. }
  20. public function login($params)
  21. {
  22. $user = User::where("email", $params['userinfo'])->orWhere("phone", $params['userinfo'])->first();
  23. if (is_null($user)) {
  24. throw new ClientException("用户不存在");
  25. }
  26. if ($user->status == User::STATUS_STOP) {
  27. throw new ClientException("账户已禁用");
  28. }
  29. if (!$user->checkPassword($params['password'])) {
  30. throw new ClientException("账户或密码错误");
  31. }
  32. return $user;
  33. }
  34. public function register($params)
  35. {
  36. if (User::where("email", $params['email'])->first()) {
  37. throw new ClientException("该邮件已经注册了");
  38. }
  39. if (User::where("phone", $params['phone'])->first()) {
  40. throw new ClientException("该手机已经注册了");
  41. }
  42. $user = new User();
  43. $user->email = $params['email'];
  44. $user->phone = $params['phone'];
  45. $user->group_id = 0;
  46. $user->status = User::STATUS_OK;
  47. $user->password = $user->hashPassword($params['password']);
  48. $user->save();
  49. return $user;
  50. }
  51. public function encryptToken($uid)
  52. {
  53. return md5($uid . time()) . $uid;
  54. }
  55. public function decryptToken($token)
  56. {
  57. return substr($token, 32);
  58. }
  59. public function resetPassword($params)
  60. {
  61. $user = User::where("email", $params['email'])->first();
  62. $user->password = $user->hashPassword($params['password']);
  63. $user->save();
  64. return $user;
  65. }
  66. public function updateUserInfo(User $user, $params)
  67. {
  68. if ($params['avatar']) {
  69. $user->extra = array_merge($user->extra ?? [], [
  70. "wechat" => [
  71. "avatar" => $params['avatar'],
  72. ],
  73. ]);
  74. }
  75. if ($email = Arr::get($params, "email")) {
  76. $user->email = $email;
  77. }
  78. if ($name = Arr::get($params, "name")) {
  79. $user->name = $name;
  80. }
  81. if ($name = Arr::get($params, "password")) {
  82. $user->password = $user->hashPassword($name);
  83. }
  84. $user->save();
  85. return $user;
  86. }
  87. }