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

namespace api\common\behaviors;


use Yii;
use yii\filters\auth\AuthMethod;
use yii\web\UnauthorizedHttpException;

class QueryParamAuth extends AuthMethod
{

    public $forceAuth = true;//是否强制验证，false则只登录，不关心是否成功
    public $tokenParam = 'token';

    /**
     * @inheritdoc
     */
    public function authenticate($user, $request, $response)
    {
        $accessToken = $request->headers->get($this->tokenParam);
        if (is_string($accessToken)) {
            $identity = $user->loginByAccessToken($accessToken, get_class($this));
            if ($identity !== null) {
                return $identity;
            }
        }

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

        return null;
    }


    /**
     * @param $action
     * @return bool
     * @throws UnauthorizedHttpException
     * @author nodelog
     */
    public function beforeAction($action)
    {
        $response = $this->response ? : Yii::$app->getResponse();

        try {
            $identity = $this->authenticate(
                $this->user ? : Yii::$app->getUser(),
                $this->request ? : Yii::$app->getRequest(),
                $response
            );
        } catch (UnauthorizedHttpException $e) {
            if ($this->isOptional($action) || !$this->forceAuth) {
                return true;
            }

            throw $e;
        }

        if ($identity !== null || $this->isOptional($action) || !$this->forceAuth) {
            return true;
        } else {
            $this->challenge($response);
            $this->handleFailure($response);
            return false;
        }
    }
}
