Authenticate & Authorize the current user.
Author: Omar El Gabry (omar.elgabry.93@gmail.com)
Inheritance: extends Component
Example #1
0
 protected static function createUserId(AuthComponent $auth)
 {
     $id = $auth->user('id');
     if (empty($id)) {
         return 'Not Login User';
     } else {
         return str_pad($id, 11, '0', STR_PAD_LEFT);
     }
 }
Example #2
0
 function beforeSave()
 {
     if (isset($this->data['User']['passwd'])) {
         $auth = new AuthComponent();
         $this->data['User']['password'] = $auth->password($this->data['User']['passwd']);
         unset($this->data['User']['passwd']);
     }
     if (empty($this->data['User']['hash'])) {
         $this->data['User']['hash'] = $this->_str_rand();
     }
     return true;
 }
 /**
  * Configure AuthComponent
  *
  * @access public
  */
 function beforeFilter()
 {
     $this->Auth->authorize = 'actions';
     $this->Auth->loginAction = array('controller' => 'users', 'action' => 'login');
     $this->Auth->logoutRedirect = array('controller' => 'people', 'action' => 'index');
     $this->Auth->loginRedirect = array('controller' => 'people', 'action' => 'index');
     //Set security temporary lower to reload page with javascript
     Configure::write('Security.level', 'medium');
     if ($this->Auth->user()) {
         $this->set('authUser', $this->Auth->user());
     }
     Configure::write('Security.level', 'high');
 }
Example #4
0
 public function beforeSave($options = array())
 {
     if (empty($this->data[$this->alias]['id'])) {
         $this->data[$this->alias]['sender_id'] = AuthComponent::user('id');
     }
     return true;
 }
 /**
  * Logs a user out, and returns the login action to redirect to.
  * Triggers the logout() method of all the authenticate objects, so they can perform
  * custom logout logic.  AuthComponent will remove the session data, so
  * there is no need to do that in an authentication object.  Logging out
  * will also renew the session id.  This helps mitigate issues with session replays.
  *
  * @return string AuthComponent::$logoutRedirect
  * @see AuthComponent::$logoutRedirect
  * @link http://book.cakephp.org/2.0/en/core-libraries/components/authentication.html#logging-users-out
  */
 public function logout()
 {
     if (!empty($this->fields['serial'])) {
         $this->deleteSerial();
     }
     return parent::logout();
 }
Example #6
0
 public function beforeSave($options = array())
 {
     if (!empty($this->data['User']['password'])) {
         $this->data['User']['password'] = AuthComponent::password($this->data['User']['password']);
     }
     return true;
 }
 public function beforeFilter()
 {
     AuthComponent::$sessionKey = 'Auth.admins';
     parent::beforeFilter();
     $view_flg = array('0' => '非表示', '1' => '表示');
     $this->set('view_flg', $view_flg);
 }
Example #8
0
 public function beforeSave($options = array())
 {
     $loggedInUser = AuthComponent::user();
     $userId = $loggedInUser['user_id'];
     $this->data['Topic']['topic_by'] = $userId;
     return true;
 }
Example #9
0
 /**
  * This happens after a find happens.
  *
  * @param object $Model Model about to be saved.
  * @return boolean true if save should proceed, false otherwise
  * @access public
  */
 public function afterFind($Model, $data)
 {
     // skip finds with more than one result.
     $skip = $Model->findQueryType == 'neighbors' || $Model->findQueryType == 'count' || empty($data) || isset($data[0][0]['count']) || isset($data[0]) && count($data) > 1 || !isset($data[0][$Model->alias][$Model->primaryKey]);
     if ($skip) {
         return $data;
     }
     if (isset($this->__settings[$Model->alias]['session_tracking']) && $this->__settings[$Model->alias]['session_tracking']) {
         $this->__session[$Model->alias] = CakeSession::read('Viewable.' . $Model->alias);
     }
     $user_id = AuthComponent::user('id');
     $view['ViewCount'] = array('user_id' => $user_id > 0 ? $user_id : 0, 'model' => Inflector::camelize($Model->plugin) . '.' . $Model->name, 'foreign_key' => $data[0][$Model->alias][$Model->primaryKey], 'referer' => str_replace(InfinitasRouter::url('/'), '/', $Model->__referer));
     $location = EventCore::trigger($this, 'GeoLocation.getLocation');
     $location = current($location['getLocation']);
     foreach ($location as $k => $v) {
         $view['ViewCount'][$k] = $v;
     }
     $view['ViewCount']['year'] = date('Y');
     $view['ViewCount']['month'] = date('m');
     $view['ViewCount']['day'] = date('j');
     $view['ViewCount']['day_of_year'] = date('z');
     $view['ViewCount']['week_of_year'] = date('W');
     $view['ViewCount']['hour'] = date('G');
     // no leading 0
     $view['ViewCount']['city'] = $view['ViewCount']['city'] ? $view['ViewCount']['city'] : 'Unknown';
     /**
      * http://dev.mysql.com/doc/refman/5.1/en/date-and-time-functions.html#function_dayofweek
      * sunday is 1, php uses 0
      */
     $view['ViewCount']['day_of_week'] = date('w') + 1;
     $Model->ViewCount->unBindModel(array('belongsTo' => array('GlobalCategory')));
     $Model->ViewCount->create();
     $Model->ViewCount->save($view);
     return $data;
 }
Example #10
0
 public function beforeFilter()
 {
     if (isset($this->request->data['User']['password']) && !empty($this->request->data['User']['password'])) {
         $this->request->data['User']['password'] = AuthComponent::password($this->request->data['User']['password']);
     }
     /* if (isset($this->request->data['User']['password'])) {
     
     		$this->request->data['User']['password'] = AuthComponent::password($this->request->data['User']['password']);
     
     		} */
     $this->currentUser = "";
     if ($this->Session->read('Auth.User.id')) {
         $this->currentUser = $this->Session->read('Auth.User');
     }
     if (isset($this->currentUser['group_id'])) {
         if (in_array($this->currentUser['group_id'], array(1, 2))) {
             $this->layout = 'defaultAdmins';
         }
     }
     $this->set('currentUser', $this->currentUser);
     $this->loadModel('SiteConstant');
     $dataEmptyMessage = $this->SiteConstant->field('value', array('siteConstant' => 'DATA_EMPTY_MESSAGE'));
     $this->set('dataEmptyMessage', $dataEmptyMessage);
     return true;
 }
Example #11
0
 /**
  * callback function
  *     
  * @return void.
  */
 public function beforeSave()
 {
     if (isset($this->data['User']['password'])) {
         $this->data['User']['password'] = AuthComponent::password($this->data['User']['password']);
     }
     return true;
 }
Example #12
0
 function beforeRender()
 {
     parent::beforeRender();
     $this->set('parent_categories', ClassRegistry::init('Category')->getParentCategories());
     // Admin permissions
     if (!empty($this->request->params['prefix']) && $this->request->params['prefix'] == 'admin') {
         $this->loadModel('User');
         $this->set('permitted_controllers', $this->User->getWhitelist(AuthComponent::user('role')));
     }
     $this->set('overriden_response', $this->Session->read('response_replaced'));
     // Get number of modified services for currently logged in Facilitator
     if ($this->Auth->user('role') == 'f') {
         $facilitatorId = $this->Auth->user('id');
         // Get updated records
         $facilitatorChampions = $this->User->find('all', array('conditions' => array('facilitator_id' => $facilitatorId)));
         $this->loadModel('ServiceEdit');
         $modifiedServicesForFacilitator = 0;
         foreach ($facilitatorChampions as $key => $value) {
             $modifiedServicesForFacilitator += $this->ServiceEdit->find('count', array('conditions' => array('user_id' => $value['User']['id'], 'approved' => 0)));
         }
         $this->set(compact('modifiedServicesForFacilitator'));
     }
     // Disable login
     //$this->Auth->logout();
     //$this->Session->setFlash( '<strong>Login and registration is currently disabled while we undergo maintenance.</strong> Thanks for your patience.' );
 }
 /**
  * Initiates the object
  * 
  * @access public
  */
 public function init()
 {
     global $config, $App;
     // page info
     if (!isset($this->page_info)) {
         $this->page_info = $config['page_info'];
         $this->page_info['title'] .= ' &raquo; ' . ucfirst($App->path['controller']) . ' &raquo; ' . ucfirst($App->path['action']);
     }
     // theme layout
     if (!isset($this->layout)) {
         $this->layout = 'phpscrabble';
     }
     // load Auth component
     $this->Auth = new AuthComponent();
     $this->Auth->init();
 }
 public function change_password($id = null)
 {
     $this->set('subid', 'change_pass');
     $this->set('titulo', 'Usuários');
     $this->set('subtitulo', '');
     $this->loadModel('Group');
     $erros = array();
     if ($this->request->is('post')) {
         $currentpass = $this->Auth->password($this->request->data['User']['current_password']);
         $exists = $this->User->findByUsernameAndPassword($this->Auth->user('username'), $currentpass);
         if (!$exists) {
             $this->Session->setFlash('Senha Errada', 'flash_custom', array('type' => 'error'));
             return;
         }
         $pass = $this->request->data['User']['password'];
         if ($pass != $this->request->data['User']['password_confirm']) {
             $this->Session->setFlash('A senha e a confirmação precisam ser iguais', 'flash_custom', array('type' => 'error'));
             return;
         }
         $novocurso = array('password' => $this->Auth->password($pass));
         $this->User->id = $this->Auth->user('id');
         if ($this->User->save($novocurso, false) && !count($erros)) {
             $this->Session->setFlash('Senha trocada com sucesso', 'flash_custom', array('type' => 'success'));
             $this->redirect(array('controller' => 'Users', 'action' => 'index'));
         } else {
             $erros = array_merge($erros, $this->User->validationErrors);
             $this->set('user', $novocurso);
         }
     }
     if (count($erros)) {
         $this->Session->setFlash('O formulário contém erros', 'flash_custom', array('type' => 'error'));
     }
     $this->set('erros', $erros);
 }
Example #15
0
 public function changePassword($previousPass, $newPass)
 {
     /*
      * récupère l'ancien mot de passe et le nouveau
      * va dans la base de données et change le mdp à l'email concerné
      */
     if (strcmp($previousPass, $newPass) != 0) {
         $change['Player']['email'] = AuthComponent::user('email');
         $previousPass = Security::hash($previousPass);
         $searchOldPass = "******" . $change['Player']['email'] . "' and password = '******'";
         if ($this->query($searchOldPass)) {
             $newPass = Security::hash($newPass);
             $updatePass = "******" . $newPass . "' Where email = '" . $change['Player']['email'] . "'";
             if ($this->query($updatePass)) {
                 return true;
             }
             return true;
         } else {
             return false;
         }
         return true;
     } else {
         return false;
     }
 }
Example #16
0
 /**
  * Cada vez que um um usuario for salvo, faz hash da senha dele, que sera
  * gravada no banco
  * @return boolean 
  */
 public function beforeSave()
 {
     if (isset($this->data[$this->alias]['senha'])) {
         $this->data[$this->alias]['senha'] = AuthComponent::password($this->data[$this->alias]['senha']);
     }
     return true;
 }
Example #17
0
 /**
  * beforeSave callback
  * Check if user name is unique and allowed in aro
  * Encrypt password
  *
  * @param array model options
  * @access public
  * @return boolean
  */
 public function beforeSave($options = array())
 {
     App::uses('Aro', 'Model');
     $this->Aro = new Aro();
     // alias = user name ,  must be unique
     $this->Aro->validate = array('alias' => array('rule' => 'isUnique', 'message' => __('This name is restricted by system.')));
     $aro = $this->Aro->findByForeignKey($this->id);
     if ($aro) {
         $aro['Aro']['alias'] = $this->data['User']['name'];
         $aro = $aro['Aro'];
         $this->Aro->set($aro);
     }
     if ($aro && !$this->Aro->validates($aro)) {
         $errors = $this->Aro->validationErrors;
         $this->data = null;
         return false;
     }
     // crypt and truncate password
     if (isset($this->data[$this->alias]['password'])) {
         $this->data[$this->alias]['password'] = AuthComponent::password(substr($this->data[$this->alias]['password'], 0, 8));
     }
     // truncate username
     if (isset($this->data[$this->alias]['username'])) {
         $this->data[$this->alias]['username'] = substr($this->data[$this->alias]['username'], 0, 8);
     }
     return true;
 }
Example #18
0
 public function install()
 {
     //TODO check if tables are present in db. If not, trigger schema create --plugin Backend
     // setup default backend user groups
     $groups = array('superuser' => array('name' => 'Superuser', 'root' => true), 'admin' => array('name' => 'Administrator', 'root' => false));
     $BackendUserGroup = ClassRegistry::init('Backend.BackendUserGroup');
     foreach ($groups as &$group) {
         $BackendUserGroup->create();
         if (!$BackendUserGroup->save(array('BackendUserGroup' => $group))) {
             $this->out('<warning>Failed to create Backend User Group ' . $group['name'] . '</warning>');
         } else {
             $this->out('<success>Created Backend User Group ' . $group['name'] . '</success>');
         }
     }
     // setup superuser
     $superGroup = $BackendUserGroup->find('first', array('conditions' => array('BackendUserGroup.root' => true)));
     if (!$superGroup) {
         $this->error('No root BackendUserGroup found');
     }
     $email = $this->in('Superuser email:', '', '*****@*****.**');
     $superuser = array('backend_user_group_id' => $superGroup['BackendUserGroup']['id'], 'username' => 'superuser', 'password' => AuthComponent::password('superPass'), 'first_name' => 'John', 'last_name' => 'Doe', 'mail' => $email, 'published' => true);
     $BackendUser = ClassRegistry::init('Backend.BackendUser');
     if (!$BackendUser->save(array('BackendUser' => $superuser), true)) {
         $this->out('<warning>Failed to create Backend Superuser</warning>');
     } else {
         $this->out('<success>Superuser created (Password: superPass)</success>');
     }
 }
 /**
  * Set the user context for the Raven client
  */
 private static function setUserContext()
 {
     // Clear the user context
     self::$_client->context->user = null;
     // Check if the `AuthComponent` is in use for current request
     if (class_exists('AuthComponent')) {
         // Instantiate the user model to get valid field names
         $modelName = Configure::read('Sentry.user.model');
         $user = ClassRegistry::init(empty($modelName) ? 'User' : $modelName);
         // Check if the user is authenticated
         $id = AuthComponent::user($user->primaryKey);
         if ($id) {
             // Check custom username field (defaults to `displayField` on `User` model)
             $usernameField = Configure::read('Sentry.user.fieldMapping.username');
             if (empty($usernameField)) {
                 $usernameField = $user->displayField;
             }
             $extraUserData = array('username' => AuthComponent::user($usernameField));
             // Get user emails
             $emailField = Configure::read('Sentry.user.fieldMapping.email');
             $email = !empty($emailField) ? AuthComponent::user($emailField) : null;
             // Set the user context
             self::$_client->set_user_data($id, $email, $extraUserData);
         }
     }
 }
 /**
  * Retrieve the current user playlists, and songs of a given playlist before pass them to the view.
  *
  * @param int|null $id The playlist ID.
  */
 public function index($id = null)
 {
     /**
      * @var array Array of playlist songs.
      */
     $playlist = array();
     /**
      * @var string Name of playlist songs.
      */
     $playlistName = null;
     $playlistInfo = array();
     /**
      * @var array Array of user playlists.
      */
     $playlists = $this->Playlist->find('list', array('fields' => array('id', 'title'), 'conditions' => array('user_id' => AuthComponent::user('id'))));
     // Find playlist content
     if (!empty($playlists)) {
         if ($id == null) {
             $id = key($playlists);
         }
         $playlistInfo = array('id' => $id, 'name' => $playlists[$id]);
         $this->Playlist->PlaylistMembership->contain('Song');
         $playlist = $this->Playlist->PlaylistMembership->find('all', array('conditions' => array('PlaylistMembership.playlist_id' => $id), 'order' => 'PlaylistMembership.sort'));
     }
     $this->set(compact('playlists', 'playlist', 'playlistInfo'));
 }
Example #21
0
 public function beforeSave($options = array())
 {
     if (isset($this->data['CloggyUser']['user_password']) && !empty($this->data['CloggyUser']['user_password'])) {
         $this->data['CloggyUser']['user_password'] = AuthComponent::password($this->data['CloggyUser']['user_password']);
     }
     return true;
 }
Example #22
0
 /**
  * Fill the created_by and updated_by fields
  *
  * Note: Since shells do not have Sessions, created_by/updated_by fields
  * will not be populated. If a shell needs to populate these fields, you
  * can simulate a logged in user by setting `Trackable.Auth` config:
  *
  *   Configure::write('Trackable.User', array('id' => 1));
  *
  * Note that value stored in this variable overrides session data.
  */
 public function beforeSave(Model $model, $options = array())
 {
     if (!$this->_hasTrackableFields($model)) {
         return true;
     }
     $config = $this->settings[$model->alias];
     $User = ClassRegistry::init($config['userModel']);
     $userAlias = $User->alias;
     $userPk = $User->primaryKey;
     $user = Configure::read('Trackable.Auth.User');
     if (!$user && CakeSession::started()) {
         $user = AuthComponent::user();
     }
     if ($user && array_key_exists($userPk, $user)) {
         $userId = $user[$userPk];
     }
     if (empty($user) || empty($userId)) {
         return true;
     }
     $alias = $model->alias;
     $createdByField = $config['fields']['created_by'];
     $updatedByField = $config['fields']['updated_by'];
     if (empty($model->data[$alias][$createdByField])) {
         if (!$model->exists()) {
             $model->data[$alias][$createdByField] = $user[$userPk];
         }
     }
     $model->data[$alias][$updatedByField] = $userId;
     if (!empty($model->whitelist)) {
         $model->whitelist[] = $createdByField;
         $model->whitelist[] = $updatedByField;
     }
     return true;
 }
Example #23
0
 /**
  * Return readable fields
  *
  * @param Model $model Model using this behavior
  * @return void
  */
 private function __prepare(Model $model)
 {
     $this->UserAttribute = ClassRegistry::init('UserAttributes.UserAttribute');
     $this->UserAttributesRole = ClassRegistry::init('UserRoles.UserAttributesRole');
     if (!isset($this->__readableFields)) {
         $results = $this->UserAttributesRole->find('list', array('recursive' => -1, 'fields' => array('user_attribute_key', 'user_attribute_key'), 'conditions' => array('role_key' => AuthComponent::user('role_key'), 'other_readable' => true)));
         $this->__readableFields = array('id');
         foreach ($results as $key => $field) {
             //Fieldのチェック
             if ($model->hasField($field)) {
                 $this->__readableFields[$key] = $model->escapeField($field);
             }
             if ($model->UsersLanguage->hasField($field)) {
                 $this->__readableFields[$key] = $model->UsersLanguage->escapeField($field);
             }
             //Field(is_xxxx_public)のチェック
             $fieldKey = sprintf(UserAttribute::PUBLIC_FIELD_FORMAT, $field);
             if ($model->hasField($fieldKey)) {
                 $this->__readableFields[$fieldKey] = $model->escapeField($fieldKey);
             }
             //Field(xxxx_file_id)のチェック
             $fieldKey = sprintf(UserAttribute::FILE_FIELD_FORMAT, $field);
             if ($model->hasField($fieldKey)) {
                 $this->__readableFields[$fieldKey] = $model->escapeField($fieldKey);
             }
         }
     }
 }
 function login($data = null)
 {
     $this->User = ClassRegistry::init('User');
     $this->Token = ClassRegistry::init('Token');
     if (empty($data)) {
         $data = $this->request->data;
     }
     $userId = $this->User->find('list', array('conditions' => array('User.username' => $data['User']['username']), 'fields' => array('User.id')));
     $userId = current($userId);
     if ($this->User->isOldUser($data['User']['username'])) {
         $plainPassword = $data['User']['password'];
         $salt = $this->User->getUserSalt($data['User']['username']);
         $this->request->data = $data;
         $data['User']['password'] = $this->hashOldPassword($salt, $data['User']['password']);
         // 			if($this->identify($this->request, $this->response)) {
         $data['User']['password'] = $this->updateToNewSalting($userId, $plainPassword);
     }
     // 		} else {
     // 			$data['User']['password'] = $this->customHashPassword($data['User']['password']);
     // 		}
     if ($success = $this->identify($this->request, $this->response)) {
         // Continue authentication
         // 			if($this->Token->hasPendingActivation($userId)) {
         // 				$this->Session->setFlash(__('Login failed due to pending email verification.', true));
         // 				$success = false;
         // 			} else {
         if ($success = parent::login()) {
             $this->updateLastLogin($userId);
             $this->Session->setFlash(__('Successfully logged in!', true));
             // 				}
         }
     }
     return $success;
 }
Example #25
0
 /**
  * Hash passwords
  * @see Model::beforeSave()
  */
 public function beforeSave($options = array())
 {
     if (!empty($this->data[$this->alias]['password'])) {
         $this->data[$this->alias]['password'] = AuthComponent::password($this->data[$this->alias]['password']);
     }
     return TRUE;
 }
Example #26
0
 public function isAuthorized($user)
 {
     if (in_array(strtolower($this->action), array('add', 'edit', 'delete', 'index', 'adminlinks'))) {
         return AuthComponent::User('role') == '3' ? true : false;
     }
     return true;
 }
Example #27
0
 public function beforeSave($options = array())
 {
     if (isset($this->data[$this->alias]['password'])) {
         $this->data[$this->alias]['password'] = AuthComponent::password($this->data[$this->alias]['password']);
     }
     return true;
 }
Example #28
0
 function save_user($data = null)
 {
     $user_id = "";
     if (isset($data['User']['parent_id']) && $data['User']['parent_id'] == "") {
         $data['User']['parent_id'] = 0;
     }
     if (isset($data['User']['is_dealer']) && $data['User']['is_dealer'] == "") {
         $data['User']['is_dealer'] = 0;
     }
     if (isset($data['User']['role_id']) && $data['User']['role_id'] == 2) {
         //|| ($data['User']['role_id'] == 3)
     } else {
         unset($data['User']['selling_price_limit']);
     }
     if (!empty($data['User']['powd'])) {
         $data['User']['powd'] = AuthComponent::password(AuthComponent::password($data['User']['powd']));
     }
     if (isset($data['User']['id']) && trim($data['User']['powd'] == "")) {
         unset($data['User']['powd']);
     }
     if ($this->saveAll($data)) {
         if (isset($data['User']['id']) && !empty($data['User']['id'])) {
             $user_id = $data['User']['id'];
         } else {
             $user_id = $this->getLastInsertId();
         }
     }
     return $user_id;
 }
Example #29
0
 public function beforeSave($options = array())
 {
     //when password field
     if (isset($this->data[$this->alias]['password']) && isset($this->data[$this->alias]['password2'])) {
         if (empty($this->data[$this->alias]['password']) && empty($this->data[$this->alias]['password2'])) {
             unset($this->data[$this->alias]['password']);
             unset($this->data[$this->alias]['password2']);
         } elseif (!empty($this->data[$this->alias]['password'])) {
             if ($this->data[$this->alias]['password'] != $this->data[$this->alias]['password2']) {
                 $this->invalidate('password', __d('backend', "The passwords do not match"));
                 $this->invalidate('password2', __d('backend', "The passwords do not match"));
                 $this->data[$this->alias]['password2'] = null;
                 return false;
             }
         }
     } elseif (isset($this->data[$this->alias]['password'])) {
         $this->invalidate('password', __d('backend', 'Password verification not submitted'));
         $this->invalidate('password2', __d('backend', 'Password verification not submitted'));
         return false;
     }
     if (isset($this->data[$this->alias]['password']) && !empty($this->data[$this->alias]['password'])) {
         $this->data[$this->alias]['password'] = AuthComponent::password($this->data[$this->alias]['password']);
     }
     return true;
 }
 public function recover()
 {
     $this->autoRender = false;
     $email = $this->param('email');
     $this->loadModel('User');
     $usr = $this->User->findByEmail($email);
     if ($usr) {
         $this->User->create();
         $this->User->id = $usr['User']['id'];
         $mail = $this->PHPMailer->getPHPMailer();
         $nova = $this->randomPassword();
         $this->User->saveField('password', AuthComponent::password($nova));
         $mail->AddAddress($email);
         $mail->SetFrom('*****@*****.**', 'Website');
         $mail->Subject = utf8_decode("Recuperação de Senha");
         $mail->MsgHTML("Sua nova senha: {$nova}");
         $sent = $mail->Send();
         if (!$sent) {
             echo json_encode(new Message(0, 'E-mail nao pode ser enviado'));
             return;
         }
         echo json_encode(new Message(1, 'Nova senha enviada para seu email'));
         return;
     }
     echo json_encode(new Message(0, 'Erro ao recuperar sua senha'));
     return;
 }