123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171 |
- <?php
- namespace App\Services\Auth;
- use App\MicroApi\Exceptions\RpcException;
- use App\MicroApi\Items\UserItem;
- use App\MicroApi\Services\UserService;
- use Firebase\JWT\JWT;
- use Illuminate\Auth\AuthenticationException;
- use Illuminate\Contracts\Auth\Authenticatable;
- use Illuminate\Contracts\Auth\UserProvider;
- class MicroUserProvider implements UserProvider
- {
-
- protected $userService;
-
- protected $model;
-
- public function __construct($model)
- {
- $this->model = $model;
- $this->userService = resolve('microUserService');
- }
-
- public function retrieveById($identifier)
- {
- $user = $this->userService->getById($identifier);
- if ($user) {
- $model = $this->createModel();
- $model->fillAttributes($user);
- } else {
- $model = null;
- }
- return $model;
- }
-
- public function retrieveByToken($identifier, $token)
- {
- $model = $this->createModel();
- $data = JWT::decode($token, config('services.micro.jwt_key'), [config('services.micro.jwt_algorithms')]);
- if ($data->exp <= time()) {
- return null;
- }
- $model->fillAttributes($data->User);
- return $model;
- }
-
- public function updateRememberToken(Authenticatable $user, $token)
- {
-
- }
-
- public function retrieveByCredentials(array $credentials)
- {
- if (empty($credentials) ||empty($credentials['email']) ||
- (count($credentials) === 1 &&
- array_key_exists('password', $credentials))) {
- return null;
- }
- try {
- $user = $this->userService->getByEmail($credentials['email']);
- } catch (RpcException $exception) {
- throw new AuthenticationException("认证失败:对应邮箱尚未注册");
- }
- $model = $this->createModel();
- $model->fillAttributes($user);
- return $model;
- }
-
- public function validateCredentials(Authenticatable $user, array $credentials)
- {
- try {
- if (empty($credentials['jwt_token'])) {
- $token = $this->userService->auth($credentials);
- } else {
- $token = $this->userService->isAuth($credentials['jwt_token']);
- }
- } catch (RpcException $exception) {
- $message = empty($credentials['jwt_token']) ? '注册邮箱与密码不匹配' : '令牌失效';
- throw new AuthenticationException("认证失败:" . $message);
- }
- return $token;
- }
-
- public function createModel()
- {
- $class = '\\'.ltrim($this->model, '\\');
- return new $class;
- }
-
- public function getModel()
- {
- return $this->model;
- }
-
- public function setModel($model)
- {
- $this->model = $model;
- return $this;
- }
- }
|