/** * testHash method * * @return void */ public function testHash() { $_hashType = Security::$hashType; $key = 'someKey'; $hash = 'someHash'; $this->assertSame(40, strlen(Security::hash($key, null, false))); $this->assertSame(40, strlen(Security::hash($key, 'sha1', false))); $this->assertSame(40, strlen(Security::hash($key, null, true))); $this->assertSame(40, strlen(Security::hash($key, 'sha1', true))); $result = Security::hash($key, null, $hash); $this->assertSame($result, 'e38fcb877dccb6a94729a81523851c931a46efb1'); $result = Security::hash($key, 'sha1', $hash); $this->assertSame($result, 'e38fcb877dccb6a94729a81523851c931a46efb1'); $hashType = 'sha1'; Security::setHash($hashType); $this->assertSame($hashType, Security::$hashType); $this->assertSame(40, strlen(Security::hash($key, null, true))); $this->assertSame(40, strlen(Security::hash($key, null, false))); $this->assertSame(32, strlen(Security::hash($key, 'md5', false))); $this->assertSame(32, strlen(Security::hash($key, 'md5', true))); $hashType = 'md5'; Security::setHash($hashType); $this->assertSame($hashType, Security::$hashType); $this->assertSame(32, strlen(Security::hash($key, null, false))); $this->assertSame(32, strlen(Security::hash($key, null, true))); $this->assertSame(64, strlen(Security::hash($key, 'sha256', false))); $this->assertSame(64, strlen(Security::hash($key, 'sha256', true))); Security::setHash($_hashType); }
/** * Index Login method API URL /api/login method: POST * @return json response */ public function login() { try { $user = $this->Auth->identify(); if ($user) { $user = $this->Users->get($user['id']); if (!$user) { } } else { throw new UnauthorizedException("Invalid login"); } // Generate user Auth token $authentication = $this->Authentications->newEntity(); $authentication->auth_token = Security::hash($user->id . $user->email, 'sha1', true); $authentication->user_id = $user->id; $authentication->ip = $this->request->clientIp(); $this->Authentications->save($authentication); $this->Auth->setUser($user->toArray()); } catch (UnauthorizedException $e) { throw new UnauthorizedException($e->getMessage(), 401); } $this->set('user', $this->Auth->user()); $this->set('token', $authentication->auth_token); $this->set('_serialize', ['user', 'token']); }
public function setContentsFile() { $this->__contentsFileSettings(); foreach ($this->__contentsFileSettings['fields'] as $field => $field_setting) { $file_info = $this->{$field}; if (!empty($file_info) && array_key_exists('error', $file_info) && $file_info['error'] != UPLOAD_ERR_NO_FILE) { $file_set = ['model' => $this->_registryAlias, 'model_id' => $this->id, 'field_name' => $field, 'file_name' => $file_info['name'], 'file_content_type' => $file_info['type'], 'file_size' => $file_info['size'], 'file_error' => $file_info['error']]; //$file_infoにtmp_nameがいるときはtmpディレクトリへのファイルのコピーを行う if (!empty($file_info['tmp_name'])) { $tmp_file_name = Security::hash(rand() . Time::now()->i18nFormat('YYYY/MM/dd HH:ii:ss') . $file_info['name']); if ($this->__getExt($file_info['name']) !== null) { $tmp_file_name .= '.' . $this->__getExt($file_info['name']); } if (!copy($file_info['tmp_name'], $field_setting['cacheTempDir'] . $tmp_file_name)) { //エラー } $file_set['tmp_file_name'] = $tmp_file_name; } //これを残して次に引き渡したくないので unset($this->{$field}); $this->{'contents_file_' . $field} = $file_set; } } return $this; }
function ajax_login() { if ($this->request->is('ajax')) { $email = $this->request->data['email']; $password = Security::hash($this->request->data['password'], 'sha1', true); $user = $this->Users->find()->where(['email' => $email, 'password' => $password, 'status <>' => USER_STATUS_DELETED])->first(); if ($user) { if ($user->status == USER_STATUS_ACTIVE) { $user->auth_token = \Core::randomCode(); // if 'remember me' checked, save cookie /*if(isset($this->request->data['User']['remember'])) { $this->Cookie->write('CookieRemember', $user->auth_token, null, '30 days'); } else { $this->Cookie->delete('CookieRemember'); }*/ if ($this->Users->save($user)) { $this->request->session()->write('Core.Users', $user); $this->ajax['status'] = AJAX_STATUS_SUCCESS; $this->ajax['redirect'] = $this->request->webroot . 'admin/users/index'; } } else { $this->ajax['status'] = AJAX_STATUS_ERROR; $this->ajax['error'] = __('your account has been blocked'); } } else { $this->ajax['status'] = AJAX_STATUS_ERROR; $this->ajax['error'] = __('invalid email or password'); } } }
public function beforeSave(Event $event) { $entity = $event->data['entity']; if ($entity->isNew()) { $entity->api_key = Security::hash(Text::uuid()); } return true; }
/** * Signs the url with a salted hash * * @throws \RuntimeException * @param array $options * @return string */ public function hash($options) { $mediaSalt = Configure::read('Imagine.salt'); if (empty($mediaSalt)) { throw new \RuntimeException(__d('imagine', 'Please configure {0} using {1}', 'Imagine.salt', 'Configure::write(\'Imagine.salt\', \'YOUR-SALT-VALUE\')')); } ksort($options); return urlencode(Security::hash(serialize($options) . $mediaSalt)); }
/** * Initialization hook method. * * Use this method to add common initialization code like loading components. * * @return void */ public function initialize() { parent::initialize(); $this->loadComponent('Auth', ['authenticate' => ['ByuApi', 'CasAuth.Cas' => ['hostname' => 'cas.byu.edu', 'uri' => 'cas']]]); $this->loadComponent('AuthUser'); $this->loadComponent('Flash'); if ($this->request->query('debug') && !Configure::read('debug')) { $user = $this->Auth->user(); if (!empty($user['roles']['admin'])) { $this->loadComponent('Cookie'); $this->Cookie->configKey('cake_manual_debug', 'encryption', false); $this->Cookie->write('cake_manual_debug', $user['username'] . 'debug|' . Security::hash($user['username'] . 'debug')); } } }
/** * Attempting to make a password beefer'upper */ public function index() { if ($this->request->is(['post', 'put', 'patch'])) { $userId = $this->request->session()->read('User.id'); $this->loadModel('Users'); $user = $this->Users->get($userId); $input = $this->request->data['input']; $hash1 = Security::hash($input, 'sha512', $user->username); $hash2 = Security::hash($hash1, 'sha512', $user->username . $hash1); $hash3 = Security::hash($hash2, 'sha512', $hash2 . $hash1); $hash4 = Security::hash($hash3, 'sha512', $hash1 . $hash2); $hash5 = Security::hash($hash4, 'sha512', $hash2 . $hash3); $hash6 = Security::hash($hash5, 'sha512', $hash3 . $hash4); $hash7 = Security::hash($hash6, 'sha512', $hash4 . $hash5); $output = $hash7; $this->set(compact('output')); } }
/** * main() method. * * @return bool|int Success or error code. */ public function main() { $members = $this->Passwords->find('list', ['keyField' => 'id', 'valueField' => 'password']); if ($members) { $members = $members->toArray(); } $allMembers = $this->Members->find('all'); $count = count($allMembers->toArray()); $index = 1; foreach ($allMembers as $item) { if ($members[$item->id]) { $password = $members[$item->id]; } else { $password = '******'; } $password = Security::hash($password, 'sha1', true); $member = $this->Members->patchEntity($item, ['password' => $password], ['validate' => false]); $this->Members->save($member); $this->out($index . ' / ' . $count); $index++; } }
function login() { $requestData = $this->getRequestData(['email', 'password']); $email = $requestData['email']; $password = Security::hash($requestData['password'], 'sha1', true); $user = $this->Users->find()->where(['email' => $email, 'password' => $password, 'status <>' => USER_STATUS_DELETED])->first(); if ($user) { if ($user->status == USER_STATUS_ACTIVE) { $user->auth_token = \Core::randomCode(); if ($this->Users->save($user)) { $this->Output['status'] = API_STATUS_SUCCESS; $this->Output['token'] = $user->auth_token; } } else { $this->Output['status'] = API_STATUS_ERROR; $this->Output['error_code'] = ERROR_EXCEPTION_USER_BLOCK; } } else { $this->Output['status'] = API_STATUS_ERROR; $this->Output['error_code'] = ERROR_EXCEPTION_USER_INVALID; } }
/** * Generate the token data for the provided inputs. * * @param string $url The URL the form is being submitted to. * @param array $fields If set specifies the list of fields to use when * generating the hash. * @param array $unlockedFields The list of fields that are excluded from * field validation. * @return array The token data. */ protected function _buildFieldToken($url, $fields, $unlockedFields = []) { $locked = []; foreach ($fields as $key => $value) { if (is_numeric($value)) { $value = (string) $value; } if (!is_int($key)) { $locked[$key] = $value; unset($fields[$key]); } } sort($unlockedFields, SORT_STRING); sort($fields, SORT_STRING); ksort($locked, SORT_STRING); $fields += $locked; $locked = implode(array_keys($locked), '|'); $unlocked = implode($unlockedFields, '|'); $hashParts = [$url, serialize($fields), $unlocked, Security::salt()]; $fields = Security::hash(implode('', $hashParts), 'sha1'); return ['fields' => urlencode($fields . ':' . $locked), 'unlocked' => urlencode($unlocked)]; }
/** * Index Login method API URL /api/login method: POST * @return json response */ public function index() { try { if (!isset($this->request->data['username'])) { throw new UnauthorizedException("Please enter your username"); } if (!isset($this->request->data['password'])) { throw new UnauthorizedException("Please enter your password"); } $username = $this->request->data['username']; $password = $this->request->data['password']; // Check for user credentials $users = TableRegistry::get('Users'); $user = $users->find()->where(['username' => $username, 'password' => $password])->first(); //$this->User->find('login', ['username'=>$username, 'password'=>$password]); if (!$user) { throw new UnauthorizedException("Invalid login"); } // if everything is OK set Auth session with user data //debug($token); //but first generate and insert token into user before put into Auth $token = Security::hash($user->id . $user->username, 'sha1', true); //TODO - maybe need tmestamp on this so saving token doesn't work outside current session //debug($user); $user['token'] = $token; $this->Auth->setUser($user->toArray()); // Generate user Auth token // $token = Security::hash($user->id.$user->username, 'sha1', true); //TODO - maybe need tmestamp on this so saving token doesn't work outside current session // Add user token into Auth session $this->request->session()->write('Auth.User.token', $token); //add token into // return Auth token $this->response->header('Authorization', 'Bearer ' . $token); } catch (UnauthorizedException $e) { throw new UnauthorizedException($e->getMessage(), 401); } $this->set('user', $this->Auth->user()); $this->set('_serialize', ['user']); }
/** * {@inheritDoc} */ public function authenticate(Request $request, Response $response) { $result = parent::authenticate($request, $response); if (!$result) { // fail? try using "username" as "email" $this->_config['fields']['username'] = '******'; if (!empty($request->data['username'])) { $request->data['email'] = $request->data['username']; } $result = parent::authenticate($request, $response); } if ($result && !empty($request->data['remember'])) { $controller = $this->_registry->getController(); if (empty($controller->Cookie)) { $controller->loadComponent('Cookie'); } // user information array $user = json_encode($result); // used to check that user's info array is authentic $hash = Security::hash($user, 'sha1', true); $controller->Cookie->write('User.Cookie', json_encode(compact('user', 'hash'))); } return $result; }
/** * testIdentify method * * @return void */ public function testIdentify() { $AuthLoginFormAuthenticate = $this->getMock('Cake\\Controller\\Component\\Auth\\FormAuthenticate', ['authenticate'], [], '', false); $this->Auth->authenticate = ['AuthLoginForm' => ['userModel' => 'AuthUsers']]; $this->Auth->setAuthenticateObject(0, $AuthLoginFormAuthenticate); $this->Auth->request->data = ['AuthUsers' => ['username' => 'mark', 'password' => Security::hash('cake', null, true)]]; $user = ['id' => 1, 'username' => 'mark']; $AuthLoginFormAuthenticate->expects($this->once())->method('authenticate')->with($this->Auth->request)->will($this->returnValue($user)); $result = $this->Auth->identify(); $this->assertEquals($user, $result); $this->assertSame($AuthLoginFormAuthenticate, $this->Auth->authenticationProvider()); }
/** * Generate authorization hash. * * @return string Hash */ public static function generateAuthKey() { return Security::hash(String::uuid()); }
/** * Test that values like Foo.0.1 * * @return void * @triggers Controller.startup $this->Controller */ public function testValidateNestedNumericSets() { $event = new Event('Controller.startup', $this->Controller); $this->Controller->Security->startup($event); $unlocked = ''; $hashFields = ['TaxonomyData']; $fields = urlencode(Security::hash('/articles/index' . serialize($hashFields) . $unlocked . Security::salt())); $this->Controller->request->data = ['TaxonomyData' => [1 => [[2]], 2 => [[3]]], '_Token' => compact('fields', 'unlocked')]; $result = $this->Controller->Security->validatePost($this->Controller); $this->assertTrue($result); }
public function forgot() { $this->set('title', __d('users', 'Forgot password')); /** @var $usersTable UsersTable */ $usersTable = TableRegistry::get('Pie/Users.Users'); /** @var User $user */ $user = $usersTable->newEntity(); if ($this->request->is(['post', 'put'])) { $validator = new Validator(); $validator->add('email', ['validEmail' => ['rule' => 'email', 'message' => __d('users', 'Please enter a valid email address.')]]); $errors = $validator->errors($this->request->data); $user->errors($errors); if (empty($errors)) { /** @var $user User */ $user = $usersTable->find()->where(['status' => 1, 'email' => $this->request->data('email')])->contain('UserDetails')->first(); if (is_null($user)) { $this->Flash->set(__d('users', 'Your not registered or account is deactivate.'), ['element' => 'error']); return $this->redirect($this->request->referer()); } $resetKey = Security::hash(microtime(true), 'sha256', true); $done = false; if (array_key_exists('reset_key', $user->getDetails())) { $userDetailsTable = TableRegistry::get('Pie/Users.UserDetails'); if ($userDetailsTable->updateAll(['value' => $resetKey], ['id' => $user->getDetails()['reset_key']->id])) { $done = true; } } else { $user->set('details', [new UserDetail(['user_id' => $user->get('id'), 'key' => 'reset_key', 'value' => $resetKey])]); if ($usersTable->save($user)) { $done = true; } } if ($done) { $this->getMailer('Pie/Users.User')->set(['resetKey' => $resetKey, 'resetUrl' => Router::url(['_full' => true, 'plugin' => 'Pie/Users', 'controller' => 'Users', 'action' => 'reset', $resetKey])])->send('forgot', [$user]); $this->Flash->set(__d('users', 'An email has been sent with instructions to reset your password.'), ['element' => 'success']); return $this->redirect($this->referer()); } } $this->Flash->set(__('Error occurred. Please, try again.'), ['element' => 'error']); } $this->set(['user' => $user]); }
/** * Set the cookie in the response. * * Also sets the request->params['_csrfToken'] so the newly minted * token is available in the request data. * * @param \Cake\Network\Request $request The request object. * @param \Cake\Network\Response $response The response object. * @return void */ protected function _setCookie(Request $request, Response $response) { $value = Security::hash(Text::uuid(), 'sha1', true); $request->params['_csrfToken'] = $value; $response->cookie(['name' => $this->_config['cookieName'], 'value' => $value, 'expiry' => $this->_config['expiry'], 'path' => $request->webroot, 'secure' => $this->_config['secure']]); }
/** * Validate submitted form * * @param Controller $controller Instantiating controller * @return bool true if submitted form is valid */ protected function _validatePost(Controller $controller) { if (empty($controller->request->data)) { return true; } $check = $controller->request->data; if (!isset($check['_Token']) || !isset($check['_Token']['fields']) || !isset($check['_Token']['unlocked'])) { return false; } $locked = ''; $token = urldecode($check['_Token']['fields']); $unlocked = urldecode($check['_Token']['unlocked']); if (strpos($token, ':')) { list($token, $locked) = explode(':', $token, 2); } unset($check['_Token'], $check['_csrfToken']); $locked = explode('|', $locked); $unlocked = explode('|', $unlocked); $lockedFields = []; $fields = Hash::flatten($check); $fieldList = array_keys($fields); $multi = []; foreach ($fieldList as $i => $key) { if (preg_match('/(\\.\\d+){1,10}$/', $key)) { $multi[$i] = preg_replace('/(\\.\\d+){1,10}$/', '', $key); unset($fieldList[$i]); } else { $fieldList[$i] = (string) $key; } } if (!empty($multi)) { $fieldList += array_unique($multi); } $unlockedFields = array_unique(array_merge((array) $this->config('disabledFields'), (array) $this->_config['unlockedFields'], $unlocked)); foreach ($fieldList as $i => $key) { $isLocked = is_array($locked) && in_array($key, $locked); if (!empty($unlockedFields)) { foreach ($unlockedFields as $off) { $off = explode('.', $off); $field = array_values(array_intersect(explode('.', $key), $off)); $isUnlocked = $field === $off; if ($isUnlocked) { break; } } } if ($isUnlocked || $isLocked) { unset($fieldList[$i]); if ($isLocked) { $lockedFields[$key] = $fields[$key]; } } } sort($unlocked, SORT_STRING); sort($fieldList, SORT_STRING); ksort($lockedFields, SORT_STRING); $fieldList += $lockedFields; $unlocked = implode('|', $unlocked); $hashParts = [$controller->request->here(), serialize($fieldList), $unlocked, Security::salt()]; $check = Security::hash(implode('', $hashParts), 'sha1'); return $token === $check; }
/** * Test that security hashes for postLink include the url. * * @return void */ public function testPostLinkSecurityHash() { $hash = Security::hash('/posts/delete/1' . serialize([]) . '' . Security::salt()); $hash .= '%3A'; $this->Form->request->params['_Token']['key'] = 'test'; $result = $this->Form->postLink('Delete', '/posts/delete/1'); $expected = ['form' => ['method' => 'post', 'action' => '/posts/delete/1', 'name', 'style' => 'display:none;'], ['input' => ['type' => 'hidden', 'name' => '_method', 'value' => 'POST']], 'div' => ['style' => 'display:none;'], ['input' => ['type' => 'hidden', 'name' => '_Token[fields]', 'value' => $hash]], ['input' => ['type' => 'hidden', 'name' => '_Token[unlocked]', 'value' => '']], '/div', '/form', 'a' => ['href' => '#', 'onclick' => 'preg:/document\\.post_\\w+\\.submit\\(\\); event\\.returnValue = false; return false;/'], 'Delete', '/a']; $this->assertHtml($expected, $result); }
/** * Test initialize method * * @return void */ public function test_file保存リサイズ() { //デモ画像をtmpディレクトリにコピーしておく $demo_filepath = $this->demoFileDir . 'demo1.png'; $rand = Security::hash(rand()); copy($demo_filepath, CONTENTS_FILE_CACHE_PATH . $rand); $fileinfo = ['model' => 'Posts', 'model_id' => null, 'field_name' => 'img', 'file_name' => 'demo1.png', 'file_content_type' => 'image/png', 'file_size' => filesize($demo_filepath), 'file_error' => (int) 0, 'tmp_file_name' => $rand]; $entity = $this->Posts->newEntity(); $entity->name = 'test'; $entity->contents_file_img = $fileinfo; $this->assertTrue((bool) $this->Posts->save($entity)); //保存データのチェック $last_id = $entity->id; $check_data = $this->Posts->get($last_id); //fileについてデータが正常に取得できているかどうか $assert_data = ['model' => 'Posts', 'model_id' => $last_id, 'field_name' => 'img', 'file_name' => 'demo1.png', 'file_content_type' => 'image/png', 'file_size' => (string) filesize($demo_filepath)]; $this->assertTrue($check_data->contents_file_img === $assert_data); //ファイルが指定の個所にアップロードされており、同一ファイルか $uploaded_filepath = CONTENTS_FILE_PATH . '/Posts/' . $last_id . '/img'; $this->assertTrue(file_exists($uploaded_filepath)); $origin_fp = fopen($demo_filepath, 'r'); $origin_cont = fread($origin_fp, filesize($demo_filepath)); fclose($origin_fp); $upload_fp = fopen($uploaded_filepath, 'r'); $upload_cont = fread($upload_fp, filesize($uploaded_filepath)); fclose($upload_fp); $this->assertEquals($origin_fp, $upload_fp); //リサイズ画像が上がっているか $resize_filepath1 = CONTENTS_FILE_PATH . '/Posts/' . $last_id . '/contents_file_resize_img/300_0'; $resize_filepath2 = CONTENTS_FILE_PATH . '/Posts/' . $last_id . '/contents_file_resize_img/300_400'; $this->assertTrue(file_exists($resize_filepath1)); $this->assertTrue(file_exists($resize_filepath2)); $image1 = ImageCreateFromPNG($resize_filepath1); $image1_x = ImageSX($image1); //リサイズのチェック $this->assertEquals($image1_x, 300); ImageDestroy($image1); $image2 = ImageCreateFromPNG($resize_filepath2); $image2_x = ImageSX($image2); $image2_y = ImageSY($image2); //リサイズのチェック $this->assertTrue($image2_x == 300 && $image2_y <= 400 || $image2_x <= 300 && $image2_y == 400); ImageDestroy($image2); }
public function sign_in_brand() { $session = $this->request->session(); if ($session->read('user') == true) { return $this->redirect(['controller' => 'Offers', 'action' => 'index']); } $user = $this->Users->newEntity(); if ($this->request->is('post')) { $data = $this->request->data; $check_user = $this->Users->findByUsername($data['username'])->toArray(); // On vérifie qu'il n'existe pas déjà un user avec le même username if (!$check_user) { // On prépare l'insertion du User en BDD $data['id_facebook'] = ''; $data['password'] = Security::hash($data['password'], 'sha1', true); $user = $this->Users->patchEntity($user, $data); if ($this->Users->save($user)) { $session = $this->request->session(); // On créé les cookies // $this->Cookie->config('path', '/'); // $this->Cookie->config([ // 'expires' => '+10 days', // 'httpOnly' => true // ]); // $this->Cookie->write('user', true); // $this->Cookie->write('username', $data['username']); // $this->Cookie->write('password', $data['password']); $user = $this->Users->find()->where(['username' => $data['username']])->toArray(); $data['user_id'] = $user[0]['id']; $data['id'] = $user[0]['id']; $brand = $this->Brands->newEntity(); $brand = $this->Brands->patchEntity($brand, $data); if (!$this->Brands->save($brand)) { $this->Flash->error(__('The brand could not be saved. Please, try again.')); } $brand = $brand = $this->Brands->find('all')->where(['user_id' => $data['user_id']])->toArray()[0]; $brand_id = $brand->id; $session->write('brand_id', $brand_id); // Si c'est bon, on met dans la session que l'utilisateur est admin, il n'aura plus besoin de s'authentifier $this->writeSession($data, $brand); } } else { $this->Flash->error(__('Cet username a déjà été pris.')); return $this->redirect(['action' => 'sign_in']); } return $this->redirect(['controller' => 'Home', 'action' => 'index']); } $activities = $this->Activities->find('all')->toArray(); $this->set(array('activities' => $activities)); $this->set('_serialize', ['activities']); }
/** * Sends the user an email to confirm that the correct address has been entered * **/ private function _confirmEmail($user, $emailId) { // Generate a hash $hash = Security::hash(date('Y-m-Y-i-s') . $user['username'] . $_SERVER['REMOTE_ADDR']); // Save hash and reset time to user's record $save = $this->Users->get($user['id']); $save->reset_hash = $hash; $save->reset_time = date('Y-m-d H:i:s'); $this->Users->save($save); // Email a link including the hash to the user $to = $this->request->data['email']; $message = 'Please click on this link to confirm your email address and activate your account:' . PHP_EOL . PHP_EOL . 'http://' . $_SERVER['HTTP_HOST'] . '/users/checkEmail/' . $hash . '/' . $user['id'] . '/' . $emailId . PHP_EOL . PHP_EOL . ' -Vooderbot'; $email = new Email('default'); $email->transport('mailjet')->from(['*****@*****.**' => 'Vooders.com'])->to($to)->subject('Confirm your email address')->send($message); // Set flash and redirect $this->Flash->success(__('Thank you - we have sent you a link to confirm your email address.')); }
/** * creates a unique hash for User * * @param User $user the user entity * @return string */ public function getHash(User $user) { $vars = [$user->email, $user->id, $user->password, $user->modified, $user->status]; $secretStr = implode('', $vars); $hash = \Cake\Utility\Security::hash($secretStr, 'sha512', true); return $hash; }
protected function _getAuthHash() { return substr(Security::hash($this->id . $this->email, null, true), 0, 8); }
/** * Generates password hash. * * @param string $password Plain text password to hash. * @return string Password hash * @link http://book.cakephp.org/2.0/en/core-libraries/components/authentication.html#hashing-passwords */ public function hash($password) { return Security::hash($password, $this->_config['hashType'], true); }
function forgotPassword() { $this->layout = 'login'; if (!empty($this->request->data)) { if (empty($this->request->data['email'])) { $this->Flash->error('Please enter your email address.'); } else { $email = $this->request->data['email']; // Match users to their email $query = $this->Users->find('all', ['conditions' => ['Users.email' => $email]]); //i wanna look email colummn under use $user = $query->first(); if ($user) { $key = Security::hash(Text::uuid(), 'sha512', true); $hash = sha1($user['User']['username'] . rand(0, 100)); $url = Router::url(['controller' => 'users', 'action' => 'resetPassword'], true) . '/' . $key . '#' . $hash; $ms = $url; $ms = wordwrap($ms, 1000); $user['tokenhash'] = $key; if ($this->Users->save($user)) { //============Email================// /* SMTP Options */ $email = new Email('default'); $toemail = $user['email']; $email->template('reset_password')->emailFormat('html')->to($toemail)->subject('Reset your Better Windows password')->from('*****@*****.**')->viewVars(['ms' => $ms])->send(); $this->Flash->success('A link has been generated. Please check your email.'); //============EndEmail=============// } else { $this->Flash->error('Error generating reset link.'); } } else { $this->Flash->error('Email does not exist.'); } } } }
/** * Create a new, pretty (as in moderately, not beautiful - that can't be guaranteed ;-) random client secret * * @return void */ public function generateSecret() { $this->client_secret = Security::hash(Text::uuid(), 'sha1', true); $this->_original['client_secret'] = $this->client_secret; }
/** * Generates a hidden field with a security hash based on the fields used in * the form. * * If $secureAttributes is set, these HTML attributes will be merged into * the hidden input tags generated for the Security Component. This is * especially useful to set HTML5 attributes like 'form'. * * @param array $fields If set specifies the list of fields to use when * generating the hash, else $this->fields is being used. * @param array $secureAttributes will be passed as HTML attributes into the hidden * input elements generated for the Security Component. * @return string|null A hidden input field with a security hash */ public function secure(array $fields = [], array $secureAttributes = []) { if (empty($this->request['_Token'])) { return null; } $locked = []; $unlockedFields = $this->_unlockedFields; foreach ($fields as $key => $value) { if (is_numeric($value)) { $value = (string) $value; } if (!is_int($key)) { $locked[$key] = $value; unset($fields[$key]); } } sort($unlockedFields, SORT_STRING); sort($fields, SORT_STRING); ksort($locked, SORT_STRING); $fields += $locked; $locked = implode(array_keys($locked), '|'); $unlocked = implode($unlockedFields, '|'); $hashParts = [$this->_lastAction, serialize($fields), $unlocked, Security::salt()]; $fields = Security::hash(implode('', $hashParts), 'sha1'); $tokenFields = array_merge($secureAttributes, ['value' => urlencode($fields . ':' . $locked)]); $out = $this->hidden('_Token.fields', $tokenFields); $tokenUnlocked = array_merge($secureAttributes, ['value' => urlencode($unlocked)]); $out .= $this->hidden('_Token.unlocked', $tokenUnlocked); return $this->formatTemplate('hiddenBlock', ['content' => $out]); }
/** * Returns a hash for use in the emailed link to /reset-password * * @param int $userId User ID * @param int $timestamp Timestamp * @return string */ public function getPasswordResetHash($userId, $timestamp) { return Security::hash($userId . $timestamp, 'sha1', true); }