<?php
/**
 * Created by PhpStorm.
 * User: nodelog
 * Date: 2020/6/20
 * Time: 16:38
 */

namespace api\common\behaviors;


use common\enums\CodeEnum;
use common\enums\StatusEnum;
use common\modules\user\models\User;
use yii\filters\auth\AuthMethod;
use yii\web\HttpException;

class StoreQueryParamAuth extends AuthMethod
{

    public $tokenParam = 'token';

    /**
     * @param \yii\web\User $user
     * @param \yii\web\Request $request
     * @param \yii\web\Response $response
     * @return User|\yii\web\IdentityInterface|null
     * @throws HttpException
     * @author nodelog
     */
    public function authenticate($user, $request, $response)
    {
        $accessToken = $request->get($this->tokenParam);
        if (is_string($accessToken)) {
            /* @var User $identity */
            $identity = $user->loginByAccessToken($accessToken, get_class($this));

            //商家验证
            $store = $identity->store;
            if (empty($store) || $store->status == StatusEnum::STATUS_OFF) {
                $this->handleFailure($response);
            }

            if ($identity !== null) {
                return $identity;
            }
        }

        if ($accessToken !== null) {
            $this->handleFailure($response);
        }

        return null;
    }

    /**
     * @param $response
     * @throws HttpException
     * @author nodelog
     */
    public function handleFailure($response)
    {
        throw new HttpException(CodeEnum::CODE_FORBIDDEN, '您没有权限，请联系管理员');
    }

}
