php laravel的智威汤逊自定义联表处理

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了php laravel的智威汤逊自定义联表处理相关的知识,希望对你有一定的参考价值。

# laravel的jwt自定义联表处理

# 配置config的atuh.php
```
    'guards' => [
        'web' => [
            'driver' => 'session',
            'provider' => 'users',
        ],

        'api' => [
            'driver' => 'jwt',
            'provider' => 'api-user',
        ],
    ],
        'providers' => [
        'users' => [
            'driver' => 'eloquent',
            'model' => App\User::class,
        ],
        'api-user' => [
            'driver' => 'apiUser',
            'model' => App\User::class,
            'relationships' => 'authToUWById',
            'validate' => [
                'uw_id' => 'id',
            ],
        ],
    ],
```
<?php
/**
 * Created by PhpStorm.
 * User: code
 * Date: 2019/4/1
 * Time: 19:35
 */

namespace App\Helper\Vendor\JWTAuth;


class JWTAuth extends \Tymon\JWTAuth\JWTAuth
{

    public function authenticate()
    {
        return $this->user();
    }
}
<?php
/**
 * Created by PhpStorm.
 * User: code
 * Date: 2019/4/1
 * Time: 17:57
 */

namespace App\Helper\Vendor\JWTAuth;


class JWTGuard extends \Tymon\JWTAuth\JWTGuard
{
    /**
     * 覆盖方法
     *
     * @return \Illuminate\Contracts\Auth\Authenticatable|null
     */
    public function user()
    {
        if ($this->user !== null) {
            return $this->user;
        }

        if ($this->jwt->setRequest($this->request)->getToken() &&
            ($payload = $this->jwt->check(true)) &&
            $this->validateSubject()
        ) {
            return $this->user = $this->provider->retrieveById($payload);
        }
    }

}
<?php
/**
 * Created by PhpStorm.
 * User: code
 * Date: 2019/4/1
 * Time: 17:55
 */

namespace App\Helper\Vendor\JWTAuth;


class LaravelServiceProvider extends \Tymon\JWTAuth\Providers\LaravelServiceProvider
{

    /**
     * 覆盖方法
     * \Tymon\JWTAuth\Providers\AbstractServiceProvider::extendAuthGuard
     *
     * @return void
     */
    protected function extendAuthGuard()
    {
        $this->app['auth']->extend('jwt', function ($app, $name, array $config) {
            $guard = new JWTGuard(
                $app['tymon.jwt'],
                $app['auth']->createUserProvider($config['provider']),
                $app['request']
            );

            $app->refresh('request', $guard, 'setRequest');

            return $guard;
        });
    }

    /**
     * Register the bindings for the main JWTAuth class.
     *
     * @return void
     */
    protected function registerJWTAuth()
    {
        $this->app->singleton('tymon.jwt.auth', function ($app) {
            return (new JWTAuth(
                $app['tymon.jwt.manager'],
                $app['tymon.jwt.provider.auth'],
                $app['tymon.jwt.parser']
            ))->lockSubject($this->config('lock_subject'));
        });
    }
}
<?php
/**
 * Created by PhpStorm.
 * User: code
 * Date: 2019/4/1
 * Time: 9:55
 */

namespace App\Http\Middleware;


class ApiMiddleware
{
    public function handle($request, \Closure $next)
    {
        \Illuminate\Support\Facades\Auth::setDefaultDriver('api'); // 解决默认auth是web的问题,当是api中间件就是用guards为api的

        return $next($request);
    }

}
<?php

namespace App\Providers;

use Illuminate\Support\Facades\Gate;
use Illuminate\Support\Facades\Auth;
use Illuminate\Foundation\Support\Providers\AuthServiceProvider as ServiceProvider;

class AuthServiceProvider extends ServiceProvider
{
    /**
     * The policy mappings for the application.
     *
     * @var array
     */
    protected $policies = [
        // 'App\Model' => 'App\Policies\ModelPolicy',
    ];

    /**
     * Register any authentication / authorization services.
     *
     * @return void
     */
    public function boot()
    {
        $this->registerPolicies();

        //

        Auth::provider('apiUser', function($app, array $config) {
            // 返回一个Illuminate\Contracts\Auth\Guard实例...
            return (new RelationshipsUserProvider($app['hash'], $config['model']))->setConfig($config);
        });
    }
}
<?php
/**
 * Created by PhpStorm.
 * User: code
 * Date: 2019/3/30
 * Time: 18:17
 */

namespace App\Providers;

use App\Helper\Vendor\Laravel\Cache;
use Illuminate\Contracts\Auth\Authenticatable as UserContract;

/**
 * 自定义表的auth
 *
 *
 * 在auth的providers增加
 *  'api-user' => [
 *      'driver' => 'apiUser',
 *      'model' => App\User::class,
 *      'relationships' => 'authToUWById',
 *      'validate' => [
 *      'uw_id' => 'id',
 *      ],
 * ],
 */
class RelationshipsUserProvider extends \Illuminate\Auth\EloquentUserProvider implements \Illuminate\Contracts\Auth\UserProvider
{
    /**
     * model关联关系的方法
     *
     * @var string
     */
    protected $relationships = '';

    /**
     * 需要验证的key
     *
     * @var array
     */
    protected $validateKey = [];

    /**
     * 获取数据
     *
     * @param $id
     * @param $payload
     * @return \App\Models\Model|\Illuminate\Database\Eloquent\Builder|\Illuminate\Database\Eloquent\Model|\Illuminate\Database\Query\Builder|object|null
     */
    protected function getModelData($id, $payload)
    {
        return Cache::remember(
            $this->getCacheKey($id, $payload),
            config('sys.cache.user-model-data-minute'),
            function () use ($id, $payload) {
                /** @var \Illuminate\Contracts\Auth\Authenticatable|\App\Models\Model $model */
                $model = $this->createModel();
                $modelData = $model->where($model->getAuthIdentifierName(), $id)->first();
                if (!empty($this->relationships) && $modelData) { // 定义了关联关系
                    $modelData[$this->relationships] = $modelData->{$this->relationships}($payload)->first();
                }

                return $modelData;
            });
    }

    /**
     * 处理缓存key
     *
     * @param $id
     * @param $payload
     * @return string
     */
    protected function getCacheKey($id, $payload)
    {
        $args = [];
        foreach ((array)$this->validateKey as $item => $relationshipsField) {
            if (isset($payload[$item])){
                $args[] = $payload[$item];
            }
        }

        return Cache::getCacheKey($id, ...$args); // 不加时间,登录时还没有过期时间
    }

    /**
     *
     * 登录时调用
     *
     * @param array $credentials
     * @return mixed
     */
    public function retrieveByCredentials(array $credentials)
    {
        /**
            // 用于auth的关联关系
            public function authToUWById($credentials)
            {
                return $this->hasMany(Models\UserWechatModel::class, 'user_id')->where('id', $credentials['uw_id'] ?? 0);
            }
         */
        return $this->getModelData($credentials['id'], $credentials);
    }

    /**
     * 验证
     *
     * @param UserContract $user
     * @param array $credentials
     * @return bool
     */
    public function validateCredentials(UserContract $user, array $credentials)
    {
        foreach ((array)$this->validateKey as $item => $relationshipsField) {
            if ($user[$this->relationships][$relationshipsField] !== $credentials[$item]) {
                return false;
            }
        }

        return true;
    }

    /**
     * 每次请求接口时获取到的数据
     *
     * @param mixed $payload
     * @return \App\Models\Model|\Illuminate\Database\Eloquent\Builder|\Illuminate\Database\Eloquent\Model|\Illuminate\Database\Query\Builder|object
     */
    public function retrieveById($payload)
    {
        return $this->getModelData($payload['sub'], $payload);
    }

    /**
     * @param string $relationships
     * @return RelationshipsUserProvider
     */
    public function setRelationships(string $relationships): RelationshipsUserProvider
    {
        $this->relationships = $relationships;

        return $this;
    }

    /**
     * @param array|string $validateKey
     * @return RelationshipsUserProvider
     */
    public function setValidateKey($validateKey): RelationshipsUserProvider
    {
        $this->validateKey = $validateKey;
        return $this;
    }

    /**
     * @param array $config
     * @return RelationshipsUserProvider
     */
    public function setConfig(array $config): RelationshipsUserProvider
    {
        if (isset($config['validate'])) {
            $this->setValidateKey($config['validate']);
        }
        if (isset($config['relationships'])) {
            $this->setRelationships($config['relationships']);
        }

        return $this;
    }

}

以上是关于php laravel的智威汤逊自定义联表处理的主要内容,如果未能解决你的问题,请参考以下文章

laravel5自定义分页

处理来自 PHPUnit (Laravel 5.2) 的自定义异常

Laravel之加密解密/日志/异常处理及自定义错误

laravel5.6 laravel 接口 接管 自定义异常类

php [Laravel - 自定义错误消息] Laravel 5.4其他登录条件 - 添加自定义错误消息。 #All #Script #Laravel #Php

Laravel 自定义字符串帮助文件