AuthService.php 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  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 EasyWeChat\Kernel\HttpClient\Response;
  7. use EasyWeChat\MiniApp\Application;
  8. class AuthService extends BaseService
  9. {
  10. public function authByOpenid($openId): string
  11. {
  12. $user = User::where('openid', $openId)->first();
  13. if (is_null($user)) {
  14. $user = new User();
  15. $user->openid = $openId;
  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. }