Skip to content

Instantly share code, notes, and snippets.

@brianally
Created July 2, 2015 20:16
Show Gist options
  • Save brianally/f4f70f5bb8c0f2304307 to your computer and use it in GitHub Desktop.
Save brianally/f4f70f5bb8c0f2304307 to your computer and use it in GitHub Desktop.
CakePHP 2.x User model for use with Role ACL
<?php
App::uses('AppModel', 'Model');
App::uses('SimplePasswordHasher', 'Controller/Component/Auth');
class User extends AppModel {
public $actsAs = [
'Acl' => ['type' => 'requester']
];
public $belongsTo = [
'Role' => [
'className' => 'Role',
'foreignKey' => 'role_id'
]
];
public $validate = [
'username' => [
'notempty' => [
'rule' => ['notempty'],
'message' => 'You must include a username',
'allowEmpty' => false,
'on' => 'create'
]
],
'role_id' => [
'numeric' => [
'rule' => ['numeric'],
'message' => 'No role specified',
'allowEmpty' => false
]
],
'email' => [
'email' => [
'rule' => ['email'],
'message' => 'You must include an email address',
'allowEmpty' => false,
'on' => 'create'
]
],
'first_name' => [
'notempty' => [
'rule' => ['notempty'],
'message' => 'You must provide a first name',
'allowEmpty' => false,
'on' => 'create'
]
],
'last_name' => [
'notempty' => [
'rule' => ['notempty'],
'message' => 'You must provide a last name',
'allowEmpty' => false,
'on' => 'create'
]
]
];
public function parentNode() {
if (!$this->id && empty($this->data)) {
return null;
}
if (isset($this->data[$this->alias]['role_id'])) {
$role_id = $this->data[$this->alias]['role_id'];
} else {
$role_id = $this->field('role_id');
}
if (!$role_id) {
return null;
} else {
return ['Role' => ['id' => $role_id]];
}
}
/**
* implement Role-only ACL: skip checks on User AROs
*
* @param array User data
* @return array
* @access public
*/
public function bindNode($user) {
return [
'model' => 'Role',
'foreign_key' => $user[$this->alias]['role_id']
];
}
/**
* Hash password before save if present in data
*
* @param array $options save options
* @return boolean true to continue, false to cancel save
*/
public function beforeSave($options = []) {
parent::beforeSave($options);
// do not use isset() here!!
if (!empty($this->data[$this->alias]['password'])) {
$PasswordHasher = new SimplePasswordHasher( ['hashType' => 'sha256'] );
$this->data[$this->alias]['password'] = $PasswordHasher->hash($this->data[$this->alias]['password']);
}
return true;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment