예제 #1
0
 /**
  * Update remember me and determine redirect url after user identified
  * @param array $user user data after identified
  * @param bool $socialLogin is social login
  * @return array
  */
 protected function _afterIdentifyUser($user, $socialLogin = false)
 {
     $socialKey = Configure::read('Users.Key.Session.social');
     if (!empty($user)) {
         $this->request->session()->delete($socialKey);
         $this->Auth->setUser($user);
         $event = $this->dispatchEvent(UsersAuthComponent::EVENT_AFTER_LOGIN);
         if (is_array($event->result)) {
             return $this->redirect($event->result);
         }
         $url = $this->Auth->redirectUrl();
         return $this->redirect($url);
     } else {
         $message = __d('Users', 'Username or password is incorrect');
         if ($socialLogin) {
             $socialData = $this->request->session()->read($socialKey);
             $socialDataEmail = null;
             if (!empty($socialData->info)) {
                 $socialDataEmail = Hash::get((array) $socialData->info, Configure::read('data_email_key'));
             }
             $postedEmail = $this->request->data(Configure::read('Users.Key.Data.email'));
             if (Configure::read('Users.Email.required') && empty($socialDataEmail) && empty($postedEmail)) {
                 return $this->redirect(['controller' => 'Users', 'action' => 'socialEmail']);
             }
             $message = __d('Users', 'There was an error associating your social network account');
         }
         $this->Flash->error($message, 'default', [], 'auth');
     }
 }
예제 #2
0
 /**
  * Parses a list of arguments into an array of indexes
  *
  * @param array $arguments A list of arguments being parsed
  * @return array
  **/
 public function parseIndexes($arguments)
 {
     $indexes = [];
     $arguments = $this->validArguments($arguments);
     foreach ($arguments as $field) {
         preg_match('/^(\\w*)(?::(\\w*))?(?::(\\w*))?(?::(\\w*))?/', $field, $matches);
         $field = $matches[1];
         $type = Hash::get($matches, 2);
         $indexType = Hash::get($matches, 3);
         $indexName = Hash::get($matches, 4);
         if (in_array($type, ['primary', 'primary_key'])) {
             $indexType = 'primary';
         }
         if ($indexType === null) {
             continue;
         }
         $indexUnique = false;
         if ($indexType == 'primary') {
             $indexUnique = true;
         } elseif ($indexType == 'unique') {
             $indexUnique = true;
         }
         $indexName = $this->getIndexName($field, $indexType, $indexName, $indexUnique);
         if (empty($indexes[$indexName])) {
             $indexes[$indexName] = ['columns' => [], 'options' => ['unique' => $indexUnique, 'name' => $indexName]];
         }
         $indexes[$indexName]['columns'][] = $field;
     }
     return $indexes;
 }
예제 #3
0
 /**
  * Resets user token
  *
  * @param string $reference User username or email
  * @param array $options checkActive, sendEmail, expiration
  *
  * @return string
  * @throws InvalidArgumentException
  * @throws UserNotFoundException
  * @throws UserAlreadyActiveException
  */
 public function resetToken($reference, array $options = [])
 {
     if (empty($reference)) {
         throw new InvalidArgumentException(__d('CakeDC/Users', "Reference cannot be null"));
     }
     $expiration = Hash::get($options, 'expiration');
     if (empty($expiration)) {
         throw new InvalidArgumentException(__d('CakeDC/Users', "Token expiration cannot be empty"));
     }
     $user = $this->_getUser($reference);
     if (empty($user)) {
         throw new UserNotFoundException(__d('CakeDC/Users', "User not found"));
     }
     if (Hash::get($options, 'checkActive')) {
         if ($user->active) {
             throw new UserAlreadyActiveException(__d('CakeDC/Users', "User account already validated"));
         }
         $user->active = false;
         $user->activation_date = null;
     }
     if (Hash::get($options, 'ensureActive')) {
         if (!$user['active']) {
             throw new UserNotActiveException(__d('CakeDC/Users', "User not active"));
         }
     }
     $user->updateToken($expiration);
     $saveResult = $this->_table->save($user);
     $template = !empty($options['emailTemplate']) ? $options['emailTemplate'] : 'CakeDC/Users.reset_password';
     if (Hash::get($options, 'sendEmail')) {
         $this->Email->sendResetPasswordEmail($saveResult, null, $template);
     }
     return $saveResult;
 }
예제 #4
0
 /**
  * Test get()
  *
  * @return void
  */
 public function testGet()
 {
     $data = array('abc', 'def');
     $result = Hash::get($data, '0');
     $this->assertEquals('abc', $result);
     $result = Hash::get($data, 0);
     $this->assertEquals('abc', $result);
     $result = Hash::get($data, '1');
     $this->assertEquals('def', $result);
     $data = self::articleData();
     $result = Hash::get(array(), '1.Article.title');
     $this->assertNull($result);
     $result = Hash::get($data, '');
     $this->assertNull($result);
     $result = Hash::get($data, '0.Article.title');
     $this->assertEquals('First Article', $result);
     $result = Hash::get($data, '1.Article.title');
     $this->assertEquals('Second Article', $result);
     $result = Hash::get($data, '5.Article.title');
     $this->assertNull($result);
     $default = array('empty');
     $this->assertEquals($default, Hash::get($data, '5.Article.title', $default));
     $this->assertEquals($default, Hash::get(array(), '5.Article.title', $default));
     $result = Hash::get($data, '1.Article.title.not_there');
     $this->assertNull($result);
     $result = Hash::get($data, '1.Article');
     $this->assertEquals($data[1]['Article'], $result);
     $result = Hash::get($data, array('1', 'Article'));
     $this->assertEquals($data[1]['Article'], $result);
 }
예제 #5
0
 /**
  * Returns the basepath for the current field/data combination.
  * If a `path` is specified in settings, then that will be used as
  * the replacement pattern
  *
  * @return string
  * @throws LogicException if a replacement is not valid for the current dataset
  */
 public function basepath()
 {
     $defaultPath = 'webroot{DS}files{DS}{model}{DS}{field}{DS}';
     $path = Hash::get($this->settings, 'path', $defaultPath);
     if (strpos($path, '{primaryKey}') !== false) {
         if ($this->entity->isNew()) {
             throw new LogicException('{primaryKey} substitution not allowed for new entities');
         }
         if (is_array($this->table->primaryKey())) {
             throw new LogicException('{primaryKey} substitution not valid for composite primary keys');
         }
     }
     $replacements = ['{primaryKey}' => $this->entity->get($this->table->primaryKey()), '{model}' => $this->table->alias(), '{table}' => $this->table->table(), '{field}' => $this->field, '{year}' => date("Y"), '{month}' => date("m"), '{day}' => date("d"), '{time}' => time(), '{microtime}' => microtime(), '{DS}' => DIRECTORY_SEPARATOR];
     if (preg_match_all("/{field-value:(\\w+)}/", $path, $matches)) {
         foreach ($matches[1] as $field) {
             $value = $this->entity->get($field);
             if ($value === null) {
                 throw new LogicException(sprintf('Field value for substitution is missing: %s', $field));
             } elseif (!is_scalar($value)) {
                 throw new LogicException(sprintf('Field value for substitution must be a integer, float, string or boolean: %s', $field));
             } elseif (strlen($value) < 1) {
                 throw new LogicException(sprintf('Field value for substitution must be non-zero in length: %s', $field));
             }
             $replacements[sprintf('{field-value:%s}', $field)] = $value;
         }
     }
     return str_replace(array_keys($replacements), array_values($replacements), $path);
 }
 public function getUser(Request $request)
 {
     if (!isset($_SESSION)) {
         return false;
     }
     $provider = Hash::get($_SESSION, 'opauth.auth.provider');
     if (!$provider) {
         return false;
     }
     $uid = Hash::get($_SESSION, 'opauth.auth.uid');
     if (!$uid) {
         return false;
     }
     $userModel = $this->_config['userModel'];
     list(, $model) = pluginSplit($userModel);
     $fields = $this->_config['fields'];
     $conditions = [$model . '.' . $fields['auth_provider'] => $provider, $model . '.' . $fields['auth_uid'] => $uid];
     $scope = $this->_config['scope'];
     if ($scope) {
         $conditions = array_merge($conditions, $scope);
     }
     $table = TableRegistry::get($userModel)->find('all');
     $contain = $this->_config['contain'];
     if ($contain) {
         $table = $table->contain($contain);
     }
     $result = $table->where($conditions)->hydrate(false)->first();
     if (empty($result)) {
         return false;
     }
     return $result;
 }
예제 #7
0
 /**
  * Returns the filename for the current field/data combination.
  * If a `nameCallback` is specified in settings, then that callable
  * will be invoked with the current upload data.
  *
  * @return string
  */
 public function filename()
 {
     $processor = Hash::get($this->settings, 'nameCallback', null);
     if (is_callable($processor)) {
         return $processor($this->data, $this->settings);
     }
     return $this->data['name'];
 }
예제 #8
0
파일: Module.php 프로젝트: wasabi-cms/cms
 public function __construct($moduleDefintion)
 {
     parent::__construct($moduleDefintion);
     $moduleClass = Hash::get($moduleDefintion, 'meta.moduleId');
     if ($moduleClass) {
         $this->instance = new $moduleClass(Hash::get($moduleDefintion, 'data'));
     }
 }
예제 #9
0
파일: Game.php 프로젝트: abf6ug/statbro
 protected function _getVictor()
 {
     $gameMembershipsCollection = new Collection($this->game_memberships);
     $victor_member = $gameMembershipsCollection->indexBy('id')->max('points');
     $victor['full_name'] = Hash::get($victor_member, 'member.full_name');
     $victor['id'] = Hash::get($victor_member, 'member.id');
     return $victor;
 }
예제 #10
0
 /**
  * Get the user data of the current session.
  *
  * @param string|null $key Key in dot syntax.
  * @return mixed Data
  */
 public function user($key = null)
 {
     $user = $this->_getUser();
     if ($key === null) {
         return $user;
     }
     return Hash::get($user, $key);
 }
예제 #11
0
파일: Cell.php 프로젝트: wasabi-cms/cms
 public function __construct($cellDefinition)
 {
     parent::__construct($cellDefinition);
     $this->grid = new Grid(Hash::get($cellDefinition, 'meta.grid.colWidth', 0), Hash::get($cellDefinition, 'meta.grid.baseWidth', 0));
     foreach ($cellDefinition['data'] as $moduleDefintion) {
         $this->data[] = new Module($moduleDefintion);
     }
 }
예제 #12
0
 /**
  * Check if the user is superuser
  *
  * @param type $user User information object.
  * @param Request $request Cake request object.
  * @return bool
  */
 public function authorize($user, Request $request)
 {
     $user = (array) $user;
     $superuserField = $this->config('superuser_field');
     if (Hash::check($user, $superuserField)) {
         return (bool) Hash::get($user, $superuserField);
     }
     return false;
 }
예제 #13
0
 /**
  * Generate a link if the target url is authorized for the logged in user
  *
  * @param type $title link's title.
  * @param type $url url that the user is making request.
  * @param array $options Array with option data.
  * @return string
  */
 public function link($title, $url = null, array $options = [])
 {
     if ($this->isAuthorized($url)) {
         $linkOptions = $options;
         unset($linkOptions['before'], $linkOptions['after']);
         return Hash::get($options, 'before') . $this->Html->link($title, $url, $linkOptions) . Hash::get($options, 'after');
     }
     return false;
 }
예제 #14
0
 /**
  * Callback fired from the controller.
  *
  * @param Query $query Query.
  * @param array $options The options for the find.
  *   - `search`: Array of search arguments.
  *   - `collection`: Filter collection name.
  * @return \Cake\ORM\Query The Query object used in pagination.
  * @throws \Exception When missing search arguments.
  */
 public function findSearch(Query $query, array $options)
 {
     if (!isset($options['search'])) {
         throw new Exception('Custom finder "search" expects search arguments ' . 'to be nested under key "search" in find() options.');
     }
     $filters = $this->_getAllFilters(Hash::get($options, 'collection', 'default'));
     $params = $this->_flattenParams((array) $options['search']);
     $params = $this->_extractParams($params, $filters);
     return $this->_processFilters($filters, $params, $query);
 }
 /**
  * Retrieves a queue engine
  *
  * @param \Psr\Log\LoggerInterface $logger logger
  * @return \josegonzalez\Queuesadilla\Engine\Base
  */
 public function getEngine($logger)
 {
     $config = Hash::get($this->params, 'config');
     $engine = Queue::engine($config);
     $engine->setLogger($logger);
     if (!empty($this->params['queue'])) {
         $engine->config('queue', $this->params['queue']);
     }
     return $engine;
 }
 /**
  * Reusable query options.
  *
  * It can be used for retreving the options of the select field(list).
  * Options:
  * - name: List name (required)
  *
  * @param  Query $query   Query object
  * @param  array $options Options see function's long description.
  * @return array          Options for the select option field.
  */
 public function findOptions(Query $query, array $options)
 {
     $result = [];
     $name = Hash::get($options, 'name');
     $list = $this->findByName($name)->first();
     if ($list) {
         $result = $this->DblistItems->find('treeList', ['keyPath' => 'value', 'valuePath' => 'name'])->where(['dblist_id' => $list->get('id')]);
     }
     return $result;
 }
 /**
  * @dataProvider provideTestRespondWithJsonData
  */
 public function testRespondWithJson($arguments, $expectedBody)
 {
     $expectedStatusCode = Hash::get($arguments, [1, 'code'], 200);
     $response = $this->getMock('Cake\\Network\\Response', ['type', 'statusCode', 'body']);
     $response->expects($this->once())->method('type')->with('json');
     $response->expects($this->once())->method('statusCode')->with($expectedStatusCode);
     $response->expects($this->once())->method('body')->with($expectedBody);
     $controller = new ControllerWithJsonResponderTrait(null, $response);
     $this->assertSame($response, call_user_func_array([$controller, 'respondWithJson'], $arguments));
 }
예제 #18
0
파일: UserHelper.php 프로젝트: cakedc/users
 /**
  * Social login link
  *
  * @param string $name name
  * @param array $options options
  * @return string
  */
 public function socialLogin($name, $options = [])
 {
     if (empty($options['label'])) {
         $options['label'] = __d('CakeDC/Users', 'Sign in with');
     }
     $icon = $this->Html->tag('i', '', ['class' => __d('CakeDC/Users', 'fa fa-{0}', strtolower($name))]);
     $providerTitle = __d('CakeDC/Users', '{0} {1}', Hash::get($options, 'label'), Inflector::camelize($name));
     $providerClass = __d('CakeDC/Users', 'btn btn-social btn-{0} ' . Hash::get($options, 'class') ?: '', strtolower($name));
     return $this->Html->link($icon . $providerTitle, "/auth/{$name}", ['escape' => false, 'class' => $providerClass]);
 }
예제 #19
0
 /**
  * Inspect the request and try to retrieve a table based on the current controller
  *
  * @param Request $request request
  * @return Table
  * @throws \OutOfBoundsException if table alias can't be extracted from request
  */
 protected function _getTableFromRequest(Request $request)
 {
     $plugin = Hash::get($request->params, 'plugin');
     $controller = Hash::get($request->params, 'controller');
     $modelClass = ($plugin ? $plugin . '.' : '') . $controller;
     $this->modelFactory('Table', [$this->tableLocator(), 'get']);
     if (empty($modelClass)) {
         throw new OutOfBoundsException(__d('CakeDC/Users', 'Table alias is empty, please define a table alias, we could not extract a default table from the request'));
     }
     return $this->loadModel($modelClass);
 }
예제 #20
0
 /**
  * Generate a link if the target url is authorized for the logged in user
  *
  * @param type $title link's title.
  * @param type $url url that the user is making request.
  * @param array $options Array with option data.
  * @return string
  */
 public function link($title, $url = null, array $options = [])
 {
     $event = new Event(UsersAuthComponent::EVENT_IS_AUTHORIZED, $this, ['url' => $url]);
     $result = $this->_View->eventManager()->dispatch($event);
     if ($result->result) {
         $linkOptions = $options;
         unset($linkOptions['before'], $linkOptions['after']);
         return Hash::get($options, 'before') . $this->Html->link($title, $url, $linkOptions) . Hash::get($options, 'after');
     }
     return false;
 }
예제 #21
0
 public function user($key = null)
 {
     if (!array_key_exists('authUser', $this->_View->viewVars)) {
         throw new \RuntimeException('AuthUser helper needs AuthUser component to function');
     }
     $user = (array) $this->_View->viewVars['authUser'];
     if ($key === null) {
         return $user;
     }
     return Hash::get($user, $key);
 }
예제 #22
0
 /**
  * Get user_id
  * @return int
  */
 protected function _userId()
 {
     if (array_key_exists('userId', $this->_context)) {
         $userId = $this->_context['userId'] ? (int) $this->_context['userId'] : null;
         unset($this->_context['userId']);
         return $userId;
     }
     if (isset($_SESSION) && is_array($_SESSION)) {
         return Hash::get($_SESSION, $this->config('userId'));
     }
     return null;
 }
예제 #23
0
 /**
  * Accessor to the logged in user's properties
  *
  * @param string $key Key to read
  * @return mixed
  */
 public function user($key = null)
 {
     if ($this->sessionKey && $this->request->session()->check($this->sessionKey)) {
         $user = $this->request->session()->read($this->sessionKey);
     } else {
         return null;
     }
     if ($key === null) {
         return $user;
     }
     return Hash::get($user, $key);
 }
예제 #24
0
 /**
  * User authorize.
  *
  * @param array $user
  * @param Request $request
  * @return bool
  */
 public function authorize($user, Request $request)
 {
     $role = Hash::get($user, 'role.alias');
     if ($role == USER_ROLE_ADMIN) {
         return true;
     }
     $permission = PermissionExtract::getInstance($user, $request);
     if (!$request->param('plugin') && $request->param('controller') == 'Pages') {
         return true;
     }
     return $permission->isAllowed();
 }
예제 #25
0
 /**
  * Adds some rules for password confirm
  * @param Validator $validator Cake validator object.
  * @return Validator
  */
 public function validationPasswordConfirm(Validator $validator)
 {
     $validator->requirePresence('password_confirm', 'create')->notEmpty('password_confirm');
     $validator->add('password', 'custom', ['rule' => function ($value, $context) {
         $confirm = Hash::get($context, 'data.password_confirm');
         if (!is_null($confirm) && $value != $confirm) {
             return false;
         }
         return true;
     }, 'message' => __d('Users', 'Your password does not match your confirm password. Please try again'), 'on' => ['create', 'update'], 'allowEmpty' => false]);
     return $validator;
 }
 /**
  * Responds with JSON formatted data.
  *
  * @param mixed $data
  * @param array $options Valid keys are 'code' and 'message'.
  *
  * @return Cake\Network\Response
  */
 public function respondWithJson($data, array $options = [])
 {
     $reservedKeys = ['code', 'status', 'message', 'data', 'errors'];
     $code = Hash::get($options, 'code', 200);
     $status = $code < 400 ? 'success' : 'failure';
     $message = Hash::get($options, 'message', null);
     $dataField = $status === 'success' ? 'data' : 'errors';
     $json = json_encode(array_merge(['status' => $status, 'code' => $code, $dataField => $data, 'message' => $message], array_diff_key($options, array_flip($reservedKeys))));
     $this->response->type('json');
     $this->response->statusCode($code);
     $this->response->body($json);
     return $this->response;
 }
예제 #27
0
 /**
  * Generate a link if the target url is authorized for the logged in user
  *
  * @param string $title link's title.
  * @param string|array|null $url url that the user is making request.
  * @param array $options Array with option data. Extra options include
  * 'before' and 'after' to quickly inject some html code in the link, like icons etc
  * 'allowed' to manage if the link should be displayed, default is null to check isAuthorized
  * @return string|bool
  */
 public function link($title, $url = null, array $options = [])
 {
     $linkOptions = $options;
     unset($linkOptions['before'], $linkOptions['after'], $linkOptions['allowed']);
     $allowed = Hash::get($options, 'allowed');
     if ($allowed === false) {
         return false;
     }
     if ($allowed === true || $this->isAuthorized($url)) {
         return Hash::get($options, 'before') . parent::link($title, $url, $linkOptions) . Hash::get($options, 'after');
     }
     return false;
 }
예제 #28
0
 /**
  * Locks all the rows returned by the query.
  * This finder requires the `lockingUser` key in options and optionally the
  * `lockingSession`.
  *
  * @param Query $quert The Query to modify
  * @param array|ArrayObject $options The options containing the `lockingUser` key
  * @return Query
  */
 public function findAutoLock(Query $query, $options)
 {
     $by = Hash::get($options, 'lockingUser');
     $session = Hash::get($options, 'lockingSession');
     return $query->formatResults(function ($results) use($by, $session) {
         $results->filter(function ($r) {
             return $r instanceof LockableInterface;
         })->each(function ($r) use($by, $session) {
             $r->lock($by, $session);
             $this->_table->save($r);
         });
         return $results;
     });
 }
예제 #29
0
 /**
  * Returns the basepath for the current field/data combination.
  * If a `path` is specified in settings, then that will be used as
  * the replacement pattern
  *
  * @return string
  * @throws LogicException if a replacement is not valid for the current dataset
  */
 public function basepath()
 {
     $defaultPath = 'webroot{DS}files{DS}{model}{DS}{field}{DS}';
     $path = Hash::get($this->settings, 'path', $defaultPath);
     if (strpos($path, '{primaryKey}') !== false) {
         if ($this->entity->isNew()) {
             throw new LogicException('{primaryKey} substitution not allowed for new entities');
         }
         if (is_array($this->table->primaryKey())) {
             throw new LogicException('{primaryKey} substitution not valid for composite primary keys');
         }
     }
     $replacements = ['{primaryKey}' => $this->entity->get($this->table->primaryKey()), '{model}' => $this->table->alias(), '{relatedModel}' => $this->entity->model, '{table}' => $this->table->table(), '{field}' => $this->field, '{time}' => time(), '{microtime}' => microtime(), '{DS}' => DIRECTORY_SEPARATOR];
     return str_replace(array_keys($replacements), array_values($replacements), $path);
 }
예제 #30
0
 /**
  * Set the full base URL recursivelly for all the menu and their children.
  *
  * @param array $menu Given menu
  * @return array $menus
  */
 protected function _setFullBaseUrl(array $menu = [])
 {
     $menu = array_map(function ($v) {
         $url = Hash::get($v, 'url');
         $children = Hash::get($v, 'children');
         if ($url) {
             $v['url'] = UrlHelper::build($url, true);
         }
         if (is_array($children)) {
             $v['children'] = $this->_setFullBaseUrl($children);
         }
         return $v;
     }, $menu);
     return $menu;
 }