我将标准REST actionUpdate替换为只允许更新密码的操作:
class UserController extends ActiveController
{
// ...
public function actions()
{
$actions = parent::actions();
unset($actions['update']);
return $actions;
}
// ...
public function actionUpdate($id)
{
if (! Yii::$app->request->isPut) {
throw new MethodNotAllowedHttpException('Please use PUT');
}
/** @var User $user */
$user = User::findIdentity($id);
if (Yii::$app->request->post('password') !== null) {
$user->setPassword(Yii::$app->request->post('password'));
}
return $user->save();
}
// ...
}
[编辑]以下是用户模型:
<?php
namespace app\models\user;
use Yii;
use yii\base\NotSupportedException;
use yii\web\IdentityInterface;
class User extends \yii\db\ActiveRecord
implements IdentityInterface
{
public static function tableName()
{
return 'Users';
}
public function rules()
{
return [
[['username', 'password_hash', 'email'], 'required'],
[['role', 'status'], 'integer'],
[['username', 'email', 'last_login'], 'string', 'max' => 255],
[['username'], 'unique'],
[['email'], 'email'],
[['auth_key'], 'string', 'max' => 32],
[['password'], 'safe'],
];
}
public function beforeSave($insert)
{
$return = parent::beforeSave($insert);
if ($this->isNewRecord)
$this->auth_key = Yii::$app->security->generateRandomKey($length = 255);
return $return;
}
public function getId()
{
return $this->id;
}
public static function findIdentity($id)
{
return static::findOne($id);
}
public function getAuthKey()
{
return $this->auth_key;
}
public function validateAuthKey($authKey)
{
return $this->getAuthKey() === $authKey;
}
public function getPassword()
{
return $this->password_hash;
}
public function setPassword($password)
{
$this->password_hash = Yii::$app->security->generatePasswordHash($password);
}
public static function findIdentityByAccessToken($token, $type = null)
{
throw new NotSupportedException('You can only login by username/password pair for now.');
}
public function validatePassword($password)
{
return Yii::$app->security->validatePassword($password, $this->password_hash);
}
}
[/编辑]
使用Postman和Codeception进行测试,[Response] = true,[Status] = 200.两者都是预期的。但是,更新不会。
[请求] =
PUT http://localhost:8888/api/v1/users/1 {"password":"anotherpassword"}
......这是正确的。当我print_r
Yii::$app->request->post()
在actionUpdate中,它返回一个空数组。型号规则列出了密码&#39;安全。
有什么想法吗?
马洛, 乔
答案 0 :(得分:0)
如果其他人感兴趣,这里最终适合我。对于Postman,我将Json参数放在请求体中(而不是作为参数)。
在Codeception中,我得到了线索here。我不得不
$I->haveHttpHeader('Content-Type','application/json');
在$ I-&gt; sendPUT(...)之前。
希望这有助于下一个人...