您好,登錄后才能下訂單哦!
1. 幾個Controller之間關系的說明
⑴ 不需要進行認證
ApiController
UserController extends ApiController
⑵ 需要進行認證
AuthApiController extends ApiController
AuthuserController extends AuthApiController
2. 只有安全認證過的api才可執行賬戶驗證和速率控制。
⑴ AuthApiController.php
<?php
namespace app\controllers;
use yii;
use yii\filters\auth\QueryParamAuth;
use yii\filters\RateLimiter;
use app\models\User;
class AuthApiController extends ApiController{
/**
* 并添加token驗證
* {@inheritDoc}
* @see \yii\rest\Controller::behaviors()
*/
public function behaviors()
{
$behaviors=parent::behaviors();
$behaviors['authenticator']['class']=QueryParamAuth::className();
$behaviors['rateLimiter']['class']=RateLimiter::className();
$behaviors['rateLimiter']['enableRateLimitHeaders'] =true;
return $behaviors;
}
/**
* checkUsernameAndToken:
* 1. check token 是否 empty
* 2. username是否empty,是否符合正則規則
* checkTokenByUser:
* user表中是否存在符合條件的記錄: username, accesstoken
*/
public function checkTokenUsername(){
$token=yii::$app->request->get('accesstoken');
$username=yii::$app->request->post('username');
//檢查username,token在user表中是否存在
$userInfo=User::checkTokenByUser($token, $username);
if(false==$userInfo){
return ['error', 'operationIllegal'];
}
return $userInfo;
}
}
⑵ AuthuserController.php
<?php
namespace app\controllers;
use yii;
use app\models\User;
class AuthuserController extends AuthApiController {
// 用戶中心
public $modelClass = 'app\models\User';
/**
* 過濾數據接收方式
* {@inheritDoc}
* @see \yii\rest\ActiveController::verbs()
*/
protected function verbs(){
return [
'getuserinfo'=>['get','post'],
];
}
/**
* 獲取個人信息
*/
public function actionGetuserinfo(){
$userInfo = $this->checkTokenUsername();
if(isset ($userInfo['error']))
return [‘error’=>’nouser’];
return $userInfo;
}
}
⑶ 最重要的User.php
<?php
namespace app\models;
use Yii;
use app\components\Utility;
use yii\web\IdentityInterface;
use yii\filters\RateLimitInterface;
class User extends \yii\db\ActiveRecord implements IdentityInterface, RateLimitInterface
{
/**
* @inheritdoc
*/
public static function tableName()
{
return '`user`';
}
/**
* @inheritdoc
*/
public function rules()
{
return [
[['username', 'password'], 'required'],
[['status', 'addtime', 'logins', 'allowance', 'allowance_updated_at'], 'integer'],
[['username', 'password', 'email'], 'string', 'max' => 64],
[['mobile'], 'string', 'max' => 11],
[['last_login_ip'], 'string', 'max' => 15],
[['access_token'], 'string', 'max' => 32],
[['access_token'], 'unique']
];
}
/**
* @inheritdoc
*/
public function attributeLabels()
{
return [
'uid' => 'Uid',
'username' => 'Username',
'password' => 'Password',
'email' => 'Email',
'status' => 'Status',
'addtime' => 'Addtime',
'mobile' => 'Mobile',
'last_login_ip' => 'Last Login Ip',
'logins' => 'Logins',
'access_token' => 'Access Token',
'allowance' => 'Allowance',
'allowance_updated_at' => 'Allowance Updated At',
];
}
/**
* @inheritdoc
* @return UserQuery the active query used by this AR class.
*/
public static function find()
{
return new UserQuery(get_called_class());
}
/**
* 授權認證. IdentityInterface
*/
public static function findIdentityByAccessToken($token, $type = null) {
return static::findOne(['access_token' => $token]);
}
public static function findIdentity($id) {
return static::findOne(['uid' => $id]);
}
public function getId() {
return $this->uid;
}
public function getAuthKey() { }
public function validateAuthKey($authKey) { }
/**
* 限速部分. RateLimitInterface
*/
public function getRateLimit($request, $action) {
return [3,6]; // 6秒3次
}
public function loadAllowance($request, $action){
return [$this->allowance,$this->allowance_updated_at];
}
public function saveAllowance($request, $action, $allowance, $timestamp){
$this->allowance=$allowance;
$this->allowance_updated_at=$timestamp;
$this->save();
}
/**
* 檢查token跟用戶名(手機或者郵箱)是否對應
*/
public static function checkTokenByUser($token, $user) {
$userInfo = self::findByUsername($user);
return ((!!$userInfo) && ($userInfo->access_token == $token)) ? $userInfo : false;
}
/**
* 通過username查找一個用戶
*/
public static function findByUsername($username){
if(empty($username)) return false;
$sqlstr = "select * from ".self::tableName()." where username=$username";
$userInfo = self::findBySql($sqlstr)->one();
return empty($userInfo) ? false : $userInfo;
}
}
3. 測試
⑴ 賬戶驗證
① 當access-token在yii2_user表中不存在時,報錯:You are requesting with an invalid credential.
⑵ 速率控制
① Headers下的信息:
② Body返回的信息:
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。