123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103 |
- <?php
- namespace App\Modules\Mini\Services;
- use App\Base\BaseService;
- use App\Exceptions\ClientException;
- use App\Models\User\User;
- use Illuminate\Support\Arr;
- class AuthService extends BaseService
- {
- public function authByOpenid($openId): string
- {
- $user = User::where('openid', $openId)->first();
- if (is_null($user)) {
- $user = new User();
- $user->openid = $openId;
- $user->status = User::STATUS_OK;
- $user->save();
- }
- return $this->encryptToken($user->id);
- }
- public function login($params)
- {
- $user = User::where("email", $params['userinfo'])->orWhere("phone", $params['userinfo'])->first();
- if (is_null($user)) {
- throw new ClientException("用户不存在");
- }
- if ($user->status == User::STATUS_STOP) {
- throw new ClientException("账户已禁用");
- }
- if (!$user->checkPassword($params['password'])) {
- throw new ClientException("账户或密码错误");
- }
- return $user;
- }
- public function register($params)
- {
- if (User::where("email", $params['email'])->first()) {
- throw new ClientException("该邮件已经注册了");
- }
- if (User::where("phone", $params['phone'])->first()) {
- throw new ClientException("该手机已经注册了");
- }
- $user = new User();
- $user->email = $params['email'];
- $user->phone = $params['phone'];
- $user->group_id = 0;
- $user->status = User::STATUS_OK;
- $user->password = $user->hashPassword($params['password']);
- $user->save();
- return $user;
- }
- public function encryptToken($uid)
- {
- return md5($uid . time()) . $uid;
- }
- public function decryptToken($token)
- {
- return substr($token, 32);
- }
- public function resetPassword($params)
- {
- $user = User::where("email", $params['email'])->first();
- $user->password = $user->hashPassword($params['password']);
- $user->save();
- return $user;
- }
- public function updateUserInfo(User $user, $params)
- {
- if ($params['avatar']) {
- $user->extra = array_merge($user->extra ?? [], [
- "wechat" => [
- "avatar" => $params['avatar'],
- ],
- ]);
- }
- if ($email = Arr::get($params, "email")) {
- $user->email = $email;
- }
- if ($name = Arr::get($params, "name")) {
- $user->name = $name;
- }
- if ($name = Arr::get($params, "password")) {
- $user->password = $user->hashPassword($name);
- }
- $user->save();
- return $user;
- }
- }
|