【发布时间】:2015-07-31 09:30:15
【问题描述】:
我将标准 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 中,它返回一个空数组。模型规则将“密码”列为安全。
有什么想法吗?
马哈洛, 乔
【问题讨论】:
-
你能发布你的用户模型吗?
-
尝试使用 PATCH HTTP 方法而不是 PUT。在使用 Codeception 进行测试时,我也遇到了 PUT 请求空有效负载的问题。
-
@balaji 发布用户模型。
-
你换行了吗: if (! Yii::$app->request->isPut) { throw new MethodNotAllowedHttpException('Please use PUT'); } to if (! Yii::$app->request->isPatch) { throw new MethodNotAllowedHttpException('请使用 PATCH'); } 在 actionUpdate() 函数中?
-
@matej PATCH 还在 post() 中传递了一个空数组。