yii 2でrestful urlアクセス構成、ログインインタフェースaccess-token検証クラス

30237 ワード

アクセスインタフェースaccess-token検証クラスControllerの下に新しいBaseActiveControllerを作成します.php

/**
 * 
 * @author  
 * 1.0
 *
 */
namespace backend\controllers;

use yii\filters\auth\CompositeAuth;
use yii\filters\auth\HttpBasicAuth;
use yii\filters\auth\HttpBearerAuth;
use yii\filters\auth\QueryParamAuth;
use yii\filters\Cors;
use yii\filters\RateLimiter;
use yii\rest\Controller;
use Yii;

class BaseActiveController extends Controller
{
    public $modelClass = 'common\models\user';

    public $post = null;
    public $get = null;
    public $user = null;
    public $userId = null;

    public function init()
    {
        parent::init();

        Yii::$app->user->enableSession = false;
    }

    public function behaviors()
    {
        $behaviors = parent::behaviors();

        $behaviors['authenticator'] = [
            'class' => CompositeAuth::className(),
            'authMethods' => [
           //     HttpBasicAuth::className(),
           //     HttpBearerAuth::className(),
                QueryParamAuth::className(),
            ],
        ];

      
      //   
        //$behaviors['contentNegotiator']['formats']['application/json'] = 'json';
       //$behaviors['contentNegotiator']['formats']['application/xml'] = 'json';
    
        return $behaviors;
    }


    public function beforeAction($action)
    {
        parent::beforeAction($action);

        $this->post = yii::$app->request->post();
        $this->get = yii::$app->request->get();
        $this->user = yii::$app->user->identity;
        $this->userId = Yii::$app->user->id;

        return $action;
    }


} 

下に新しいUserControllerを作成します.php

namespace backend\controllers;
use Yii;
use yii\filters\auth\CompositeAuth;
use yii\filters\auth\QueryParamAuth;
use yii\data\ActiveDataProvider;
use \yii\helpers\Json;
use common\models\LoginForm;

class UserController extends BaseActiveController
{
    /**
     *  , 。
     * @author   
     */
    public function actionIndex()
    {
        if(Yii::$app->user->isGuest){
            $data=array(
                'code'=>100,
                'message'=>' ',
                'data'=>'',
            );
        }else{
            $data=array(
                'code'=>200,
                'message'=>' ',
                'data'=>array(
                    'user_id'=>Yii::$app->user->id,
                    'user_name'=>isset(\Yii::$app->user->identity->username) ? \Yii::$app->user->identity->username : '',
                ),
            );
        }
        echo json_encode($data);exit;
    }

}

ディレクトリcommon/modelsの下に新しいUserを作成します.php

namespace common\models;

use Yii;
use yii\base\NotSupportedException;
use yii\behaviors\TimestampBehavior;
use yii\db\ActiveRecord;
use yii\web\IdentityInterface;

/**
 * User model
 *
 * @property integer $id
 * @property string $username
 * @property string $password_hash
 * @property string $password_reset_token
 * @property string $email
 * @property string $auth_key
 * @property integer $status
 * @property integer $created_at
 * @property integer $updated_at
* @property integer  $curr_login_ip
 * @property integer $curr_login_at
 * @property string $password write-only password
 */



class User extends ActiveRecord implements IdentityInterface
{

    public $curr_login_at;
    const STATUS_DELETED = 0;
    const STATUS_ACTIVE = 10;


    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return '{{%user}}';
    }

    /**
     * @inheritdoc
     */
    public function behaviors()
    {
        return [
            TimestampBehavior::className(),
        ];
    }

    #  access_token  
    public function generateAccessToken()  
    {  
        $this->access_token = Yii::$app->security->generateRandomString();  
    }  

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            ['status', 'default', 'value' => self::STATUS_ACTIVE],
            ['status', 'in', 'range' => [self::STATUS_ACTIVE, self::STATUS_DELETED]],
        ];
    }

    /**
     * @inheritdoc
     */
    public static function findIdentity($id)
    {
        return static::findOne(['id' => $id, 'status' => self::STATUS_ACTIVE]);
    }




    public static function findIdentityByAccessToken($token, $type = null)
    {

        return static::findOne(['access_token' => $token]);
    }

    /**
     * Finds user by username
     *
     * @param string $username
     * @return static|null
     */
    public static function findByUsername($username)
    {
        return static::findOne(['username' => $username, 'status' => self::STATUS_ACTIVE]);
    }

    /**
     * Finds user by password reset token
     *
     * @param string $token password reset token
     * @return static|null
     */
    public static function findByPasswordResetToken($token)
    {
        if (!static::isPasswordResetTokenValid($token)) {
            return null;
        }

        return static::findOne([
            'password_reset_token' => $token,
            'status' => self::STATUS_ACTIVE,
        ]);
    }

    /**
     * Finds out if password reset token is valid
     *
     * @param string $token password reset token
     * @return bool
     */
    public static function isPasswordResetTokenValid($token)
    {
        if (empty($token)) {
            return false;
        }

        $timestamp = (int) substr($token, strrpos($token, '_') + 1);
        $expire = Yii::$app->params['user.passwordResetTokenExpire'];
        return $timestamp + $expire >= time();
    }

    /**
     * @inheritdoc
     */
    public function getId()
    {
        return $this->getPrimaryKey();
    }

    /**
     * @inheritdoc
     */
    public function getAuthKey()
    {
        return $this->auth_key;
    }

    /**
     * @inheritdoc
     */
    public function validateAuthKey($authKey)
    {
        return $this->getAuthKey() === $authKey;
    }

    /**
     * Validates password
     *
     * @param string $password password to validate
     * @return bool if password provided is valid for current user
     */
    public function validatePassword($password)
    {
        

        return Yii::$app->security->validatePassword($password, $this->password_hash);
    }

    /**
     * Generates password hash from password and sets it to the model
     *
     * @param string $password
     */
    public function setPassword($password)
    {
        $this->password_hash = Yii::$app->security->generatePasswordHash($password);
    }

    /**
     * Generates "remember me" authentication key
     */
    public function generateAuthKey()
    {
        $this->auth_key = Yii::$app->security->generateRandomString();
    }

    /**
     * Generates new password reset token
     */
    public function generatePasswordResetToken()
    {
        $this->password_reset_token = Yii::$app->security->generateRandomString() . '_' . time();
    }

    /**
     * Removes password reset token
     */
    public function removePasswordResetToken()
    {
        $this->password_reset_token = null;
    }
}

新しいLoginFormでphp

namespace common\models;

use Yii;
use yii\base\Model;

/**
 * Login form
 */
class LoginForm extends Model
{
    public $username;
    public $password;
    public $rememberMe = true;

    private $_user;


    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            // username and password are both required
            [['username', 'password'], 'required'],
            // rememberMe must be a boolean value
            ['rememberMe', 'boolean'],
            // password is validated by validatePassword()
            ['password', 'validatePassword'],
        ];
    }

    /**
     * Validates the password.
     * This method serves as the inline validation for password.
     *
     * @param string $attribute the attribute currently being validated
     * @param array $params the additional name-value pairs given in the rule
     */
    public function validatePassword($attribute, $params)
    {
        if (!$this->hasErrors()) {
            $user = $this->getUser();
            if (!$user || !$user->validatePassword($this->password)) {
                $this->addError($attribute, 'Incorrect username or password.');
            }
        }
    }

    /**
     * Logs in a user using the provided username and password.
     *
     * @return bool whether the user is logged in successfully
     */
    public function login()
    {
        if ($this->validate()) {
            return Yii::$app->user->login($this->getUser(), $this->rememberMe ? 3600 * 24 * 30 : 0);
        } else {
            return false;
        }
    }

    /**
     * Finds user by username
     *
     * @return User|null
     */
    protected function getUser()
    {
        if ($this->_user === null) {
            $this->_user = User::findByUsername($this->username);
        }

        return $this->_user;
    }
}
http://localhost/yii2/backend/web/index.php?r=user/index&access-token=rMwh_EnqAc0qEPTfzb66BlGtSqoF15sg美化していないで、みんなは自分で処理して、このrMwhに注意しますEnqAc 0 qEPTfzb 66 BlGtSqoF 15 sgコンテンツはデータベース内のaccess-tokenというコンテンツの値を返します.
{"code":200,"message":"\u7528\u6237\u5df2\u7ecf\u767b\u5f55","data":{"user_id":"1","user_name":"terry"}}

この内容を返すと成功した
ログインユーザ名とパスワードの検証を完了してaccess-tokenを生成する内容はcontrollersというディレクトリの下でSiteControllerを新規作成する.php

/**
* 
* access-token 
* @author  
* 1.0
*
*
*/

namespace backend\controllers;

use Yii;
use backend\models\forms\LoginForm;
use common\lib\Helper;
use yii\base\Exception;
use yii\base\InvalidValueException;
use yii\base\UserException;
use yii\web\ErrorAction;
use yii\web\HttpException;
use yii\rest\Controller;

class SiteController extends Controller
{

    public $modelClass = 'common\models\user';
    public function behaviors()
    {
       $behaviors = parent::behaviors();
       // unset($behaviors['authenticator']);
        return $behaviors;
    }

    protected function verbs()
    {
        $verbs = parent::verbs();
      //  $verbs['index'] = ['POST'];
        return $verbs;
    }

    public function actionLogin()
    {

        $loginModel = new LoginForm();
        $loginModel->load([$loginModel->formName() => yii::$app->request->get()]);

         if ($loginModel->validate()) {
            $rs = $loginModel->login();
     
            return Helper::format_data($rs);
        } else {
            return Helper::format_data($loginModel->getErrors(), HTTP_STATUS_401);
        }
    }
}

運転http://localhost/yii2/backend/web/index.php?r=site/login&password=rasmuslerdorf&username=terry
Use of undefined constant HTTP_STATUS_200 - assumed 'HTTP_STATUS_200'

この内容を返すと成功した