Question: let’s suppose we have clients. First i create the user only with required data. Then I’ll provide them with a random password (and ask them to change it asap).
How can i do to give them permission to change (update, cuz i’ve already create the users) ONLY their own data?
Speaking about password change, your action may look like this:
public function actionChangePassword()
{
$user = User::model()->findByPk(Yii::app()->user->id);
if ($user === null) {
throw new CHttpException(403, 'Access denied.');
}
...
}
This makes sure the user can edit his own record only.
Speaking about all the other data, I use extra field ‘ownerId’ in every table where user’s data are stored.
Btw, I have moved all the boring stuff to model, so my code looks like this:
# models/ActiveRecord.php:
public function scopes() {
return array(
'own' => array(
'condition' => 't.ownerId = :uid',
'params' => array(':uid' => Yii::app()->user->id)
),
);
}
public function beforeSave() {
if ($this->isNewRecord) {
### record owner
if ($this->hasAttribute('ownerId') && !isset($this->ownerId)) {
$this->ownerId = Yii::app()->user->id;
}
}
return parent::beforeSave();
}
# Controller:
public function actionUpdate($id)
{
$record = ExampleModel::model()->own()->findByPk($id);
if ($record === null) {
throw new CHttpException(404, 'Oops.');
}
...
}
That’s not very good in terms of MVC (because model should not know anything about current session), but I can afford it on my projects.
And if you need more complicated permissions control, take a look at RBAC