/** * undocumented function * * @return void * @access public */ static function generate($key = array(), $autoRefresh = true) { if (Common::isUuid($key)) { $key = array('user_id' => $key); } elseif (!isset($key['user_id'])) { $key['user_id'] = User::get('id'); } // to support emails, too // Assert::true(Common::isUuid($key['user_id'])); $_this = Common::getModel('AuthKey'); if (!Common::isUuid($key['auth_key_type_id']) && !empty($key['auth_key_type_id'])) { $key['auth_key_type_id'] = $_this->AuthKeyType->lookup($key['auth_key_type_id']); } Assert::true(Common::isUuid($key['auth_key_type_id'])); $recursive = -1; $sameTypeKey = $_this->find('first', array('conditions' => array('user_id' => $key['user_id'], 'auth_key_type_id' => $key['auth_key_type_id']), 'recursive' => -1)); if ($sameTypeKey) { if (!$autoRefresh) { return false; } $key['id'] = $sameTypeKey['AuthKey']['id']; } do { $key['key'] = Security::generateAuthKey(); } while (!$_this->isUnique(array('key' => $key['key']))); Assert::notEmpty($key['key']); $_this->create(); Assert::notEmpty($_this->save($key)); return $key['key']; }
function checkout_recur_paypal($type = -1) { $this->loadModel("SubscriptionType"); $this->Session->write("TOKEN", null); if ($type != -1) { $type = $this->SubscriptionType->find("first", array("conditions" => array("SubscriptionType.id" => $type), "recursive" => -1)); $paymentInfo["Payment"]["paymentType"] = "Sale"; $paymentInfo["Payment"]["currencyCode"] = "USD"; $paymentInfo["Payment"]["amount"] = $type["SubscriptionType"]["price"]; $paymentInfo["Payment"]["description"] = $type["SubscriptionType"]["name"]; $key = Security::generateAuthKey(); $this->Session->write("Payment.transaction", $key); $this->Session->write("Payment.type", $type); $this->Session->write("Payment.amount", $type["SubscriptionType"]["price"]); $paymentInfo["Payment"]["returnURL"] = "https://" . $_SERVER['SERVER_NAME'] . $this->base . "/subscription_transactions/success_recur_paypal/" . $key; $paymentInfo["Payment"]["cancelURL"] = "https://" . $_SERVER['SERVER_NAME'] . $this->base . "/subscription_transactions/cancel_paypal/" . $key; $paymentInfo["Payment"]["startDate"] = urlencode(date("Y-M-d") . "T" . date("h:m:s") . "Z"); $this->PaypalService->recurringPayment($paymentInfo); if ($this->Session->check("TOKEN")) { $this->PaypalService->redirectToPaypal($this->Session->read("TOKEN")); } else { $this->redirect("/subscribe"); } } else { $this->redirect("/subscribe"); } }
public function add() { $this->loadModel('Department'); $this->loadModel('Meeting'); $this->set('dept', $this->Department->find('all', array('fields' => array('id', 'description')))); if ($this->request->is('post')) { $this->Meeting->create(); // Initialize filename-variable $filename = null; $today = getdate(); if (!empty($this->request->data['Meeting']['upload']['tmp_name']) && is_uploaded_file($this->request->data['Meeting']['upload']['tmp_name'])) { // Strip path information $filename = substr(Security::generateAuthKey(), 0, 5) . '_' . basename($this->request->data['Meeting']['upload']['name']); move_uploaded_file($this->data['Meeting']['upload']['tmp_name'], WWW_ROOT . 'files' . DS . $filename); } //Set the file-name only to save in the database $this->request->data['Meeting']['upload'] = $filename; $this->request->data['Meeting']['upload_dir'] = WWW_ROOT . 'files' . DS . $filename; if ($this->Meeting->save($this->request->data)) { $this->Session->setFlash('Your post has been saved.'); $this->redirect('/meetings'); } else { $this->Session->setFlash('Unable to add your post.'); } } }
/** * Generates verification data for a Model. * * The verification key and code are two strings that can be used to verify a user is valid. * The verification timestamp can be used to check if the verification data has expired. * * @param Model $Model Model using this behavior * @param int $id The ID of the Model to generate verification data for * @return mixed On success Model::$data if its not empty or true, false on failure */ public function generateVerification(Model $Model, $id = null) { if ($id) { $Model->id = $id; } // No ID, so cannot save the verification data if (!$Model->getID()) { return false; } // Generate verification data $data = array($Model->alias => array($Model->primaryKey => $id, $this->settings['fields']['key'] => Security::generateAuthKey(), $this->settings['fields']['code'] => uniqid(), $this->settings['fields']['timestamp'] => date("Y-m-d H:i:s"), 'modified' => false)); return $Model->save($data, false, array($Model->primaryKey, $this->settings['fields']['key'], $this->settings['fields']['code'], $this->settings['fields']['timestamp'])); }
/** * add method * * @return void */ public function add() { if ($this->request->is('post')) { $this->request->data['User']['passport'] = Security::generateAuthKey(); $this->User->create(); if ($this->User->save($this->request->data)) { $this->Core->get_alert('ユーザーを追加しました。', 'success'); return $this->redirect(array('action' => 'index')); } else { $this->Core->get_alert('ユーザーを追加できませんでした。', 'danger'); } } $roles = $this->User->Role->find('list'); $this->set(compact('roles')); }
private function step3() { $missingDatabase = false; if (!($databaseConfig = $this->Session->read('database'))) { $missingDatabase = true; } if ($missingDatabase) { $this->Session->setFlash(__('MushRaider can\'t find your database settings, please complete this form to proceed to next step'), 'flash_error'); $this->redirect('/install/step/2'); } if (!empty($this->request->data['Config'])) { $siteInfos = array('siteTitle' => trim($this->request->data['Config']['sitetitle']), 'siteLanguage' => trim($this->request->data['Config']['sitelang']), 'adminemail' => trim($this->request->data['Config']['adminemail']), 'adminlogin' => trim($this->request->data['Config']['adminlogin']), 'adminpassword' => md5($this->request->data['Config']['adminpassword'])); if (!empty($siteInfos['siteTitle']) && !empty($siteInfos['adminlogin']) && !empty($siteInfos['adminpassword'])) { $settingsConfig = array(); $settingsConfig['language'] = $siteInfos['siteLanguage']; $settingsConfig['salt'] = Security::generateAuthKey(); $settingsConfig['cipherSeed'] = mt_rand() . mt_rand(); $error = false; if (!($mysqlLink = mysqli_connect($databaseConfig['host'], $databaseConfig['login'], $databaseConfig['password'], $databaseConfig['database'], $databaseConfig['port']))) { $error = true; } // Create tables $sqlReport = $this->Patcher->run_sql_file($mysqlLink, '../Config/Schema/sql/mushraider.sql', $databaseConfig['prefix']); if ($sqlReport['success'] != $sqlReport['total']) { $error = true; } // Add datas $sqlReport = $this->Patcher->run_sql_file($mysqlLink, '../Config/Schema/sql/mushraider_data.sql', $databaseConfig['prefix']); if ($sqlReport['success'] != $sqlReport['total']) { $error = true; } $mysqlLink = null; // No error, we continue by creating the admin user if (!$error) { Configure::write('Database', $this->Tools->quoteArray($databaseConfig)); Configure::dump('config.ini', 'configini', array('Database')); $siteSettings = array('settingsConfig' => $settingsConfig, 'siteInfos' => $siteInfos); $this->Session->write('siteSettings', $siteSettings); $this->redirect('/install/step/4'); } } // Error $this->Session->setFlash(__('MushRaider can\'t verify the settings, please be sure to fill all the fields to continue.'), 'flash_error'); } }
public function createCroogoFile() { $croogoConfigFile = APP . 'Config' . DS . 'croogo.php'; copy($croogoConfigFile . '.install', $croogoConfigFile); $File =& new File($croogoConfigFile); $salt = Security::generateAuthKey(); $seed = mt_rand() . mt_rand(); $contents = $File->read(); $contents = preg_replace('/(?<=Configure::write\\(\'Security.salt\', \')([^\' ]+)(?=\'\\))/', $salt, $contents); $contents = preg_replace('/(?<=Configure::write\\(\'Security.cipherSeed\', \')(\\d+)(?=\'\\))/', $seed, $contents); if (!$File->write($contents)) { CakeLog::critical('Unable to write your Config' . DS . 'croogo.php file. Please check the permissions.'); return false; } Configure::write('Security.salt', $salt); Configure::write('Security.cipherSeed', $seed); return true; }
private function __setNewSaltSeed() { // set new salt and seed value $File =& new File(APP . 'Config' . DS . 'core.php'); $salt = Security::generateAuthKey(); $seed = mt_rand() . mt_rand(); $contents = $File->read(); $contents = preg_replace('/(?<=Configure::write\\(\'Security.salt\', \')([^\' ]+)(?=\'\\))/', $salt, $contents); $contents = preg_replace('/(?<=Configure::write\\(\'Security.cipherSeed\', \')(\\d+)(?=\'\\))/', $seed, $contents); if (!$File->write($contents)) { $this->Flash->info(__('Unable to secure your application, your Config %s core.php file is not writable. Please check the permissions.', DS)); $this->log('Unable to secure your application, your Config %s core.php file is not writable. Please check the permissions.', DS); return false; } Configure::write('Security.salt', $salt); Configure::write('Security.cipherSeed', $seed); return true; }
/** * undocumented function * * @param string $id * @param string $forceCreate * @return void * @access public */ function serial($Model, $id, $forceCreate = false) { $field = $this->__settings[$Model->alias]['field']; $length = $this->__settings[$Model->alias]['length']; App::import('Core', 'Security'); if (!$forceCreate) { $key = $Model->lookup(compact('id'), $field, false); if (!empty($key)) { return $key; } } do { $key = Security::generateAuthKey(); $key = substr($key, 0, $length); } while (!$Model->isUnique(array($field => $key))); $Model->set(array('id' => $id, $field => $key)); $Model->save(); return $key; }
/** Brukes til å sende en epost med lenke til side for å få nytt passord Setter tmp_key i databasen, som sendes med i lenken @param @base_url er urlen til action "nytt passord". Denne må finnes fra controlleren @param $username er brukernavnet **/ function glemt_passord($username) { if (!is_string($username)) { return $this->FEIL_BRUKERNAVN; } $userData = $this->find('first', array('conditions' => array('Selger.navn' => $username))); if (!isset($userData['Selger'])) { return $this->FEIL_BRUKERNAVN; } if (!isset($userData['Selger']['epost'])) { return $this->INGEN_EPOST; } $epostAdr = $userData['Selger']['epost']; $tmp_key = Security::generateAuthKey(); $userData['Selger']['tmp_key'] = $tmp_key; $userData['Selger']['tmp_key_created'] = date('c'); $this->save($userData, false, array('tmp_key', 'tmp_key_created')); $email = new CakeEmail('default'); $email->viewVars(array('tmp_key' => $userData['Selger']['tmp_key'], 'user_id' => $userData['Selger']['nummer'], 'epost' => $userData['Selger']['epost'], 'navn' => $userData['Selger']['navn'])); $email->template('nytt_passord', 'vanlig')->emailFormat('html')->to($userData['Selger']['epost'])->from("*****@*****.**")->subject("Passord tilbakestilling")->send(); return $this->OK; }
/** * Finalize installation * * Prepares Config/settings.yml and update password for admin user * @param $user array user to create * @return $mixed if false, indicates processing failure */ public function finalize($user) { if (Configure::read('Install.installed') && Configure::read('Install.secured')) { return false; } copy(APP . 'Config' . DS . 'settings.yml.install', APP . 'Config' . DS . 'settings.yml'); // set new salt and seed value if (!Configure::read('Install.secured')) { $File =& new File(APP . 'Config' . DS . 'croogo.php'); $salt = Security::generateAuthKey(); $seed = mt_rand() . mt_rand(); $contents = $File->read(); $contents = preg_replace('/(?<=Configure::write\\(\'Security.salt\', \')([^\' ]+)(?=\'\\))/', $salt, $contents); $contents = preg_replace('/(?<=Configure::write\\(\'Security.cipherSeed\', \')(\\d+)(?=\'\\))/', $seed, $contents); if (!$File->write($contents)) { $this->log('Unable to write your Config' . DS . 'croogo.php file. Please check the permissions.'); return false; } Configure::write('Security.salt', $salt); Configure::write('Security.cipherSeed', $seed); } // create administrative user $User = ClassRegistry::init('User'); $User->Role->Behaviors->attach('Aliasable'); unset($User->validate['email']); $user['User']['name'] = $user['User']['username']; $user['User']['email'] = ''; $user['User']['timezone'] = 0; $user['User']['role_id'] = $User->Role->byAlias('admin'); $user['User']['status'] = true; $user['User']['activation_key'] = md5(uniqid()); $data = $User->create($user['User']); $saved = $User->save($data); if (!$saved) { $this->log('Unable to create administrative user. Validation errors:'); $this->log($User->validationErrors); } return $saved; }
private function __setNewSaltSeed() { // set new salt and seed value if (Configure::read('Security.salt') == 'zshlC2wMeCWMnRH8BmqmLQUFeBIT4uwBGSMS4k1w' || Configure::read('Security.cipherSeed') == '2973937642728344649949541921993430529846') { $File =& new File(APP . 'Config' . DS . 'core.php'); $salt = Security::generateAuthKey(); $seed = mt_rand() . mt_rand(); $contents = $File->read(); $contents = preg_replace('/(?<=Configure::write\\(\'Security.salt\', \')([^\' ]+)(?=\'\\))/', $salt, $contents); $contents = preg_replace('/(?<=Configure::write\\(\'Security.cipherSeed\', \')(\\d+)(?=\'\\))/', $seed, $contents); if (!$File->write($contents)) { $this->Session->setFlash(__('Unable to secure your application, your Config %s core.php file is not writable. Please check the permissions.', DS), 'flash_message_info'); $this->log('Unable to secure your application, your Config %s core.php file is not writable. Please check the permissions.', DS); return false; } Configure::write('Security.salt', $salt); Configure::write('Security.cipherSeed', $seed); } return true; }
/** * Use hashing user password. * * @inheritdoc */ public function beforeSave($options = array()) { $this->data[$this->alias]['password'] = AuthComponent::password($this->data[$this->alias]['password']); $this->data[$this->alias]['token'] = Security::generateAuthKey(); return true; }
public function forgot() { if ($this->request->data) { $user = $this->User->findByEmailAndIsActive($this->request->data['User']['email'], 1); if (!$user) { $this->Session->setFlash('User nicht gefunden.', 'flash_fail'); $this->redirect(array('controller' => 'users', 'action' => 'forgot')); } $newAuthKey = Security::generateAuthKey(); $this->User->id = $user['User']['id']; if ($this->User->saveField('activationkey', $newAuthKey)) { App::uses('CakeEmail', 'Network/Email'); $email = new CakeEmail('default'); $email->to($user['User']['email'])->subject('open reNose | Passwort ändern')->template('forgot')->emailFormat('html')->viewVars(array('data' => $user, 'newAuthKey' => $newAuthKey)); try { $email->send(); } catch (Exception $e) { $this->Session->setFlash('Fehler beim Verschicken der Aktivierungs Mail.', 'flash_fail'); } $this->Session->setFlash('E-Mail zur Passwortänderung wurde erfolgreich verschickt. Bitte prüfen Sie ihr E-Mail Postfach.', 'flash_success'); $this->redirect('/'); } } $this->set('title_for_layout', 'Passwort vergessen'); }
/** * testValidateAuthKey method * * @access public * @return void */ function testValidateAuthKey() { $authKey = Security::generateAuthKey(); $this->assertTrue(Security::validateAuthKey($authKey)); }
/** * Add authentication key for new form posts * * @param object $controller Instantiating controller * @return bool Success * @access private */ function __generateToken(&$controller) { if (!isset($controller->params['requested']) || $controller->params['requested'] != 1) { $authKey = Security::generateAuthKey(); $expires = strtotime('+' . Security::inactiveMins() . ' minutes'); $token = array('key' => $authKey, 'expires' => $expires, 'allowedControllers' => $this->allowedControllers, 'allowedActions' => $this->allowedActions, 'disabledFields' => $this->disabledFields); if (!isset($controller->data)) { $controller->data = array(); } if ($this->Session->check('_Token')) { $tData = unserialize($this->Session->read('_Token')); if (isset($tData['expires']) && $tData['expires'] > time() && isset($tData['key'])) { $token['key'] = $tData['key']; } } $controller->params['_Token'] = $token; $this->Session->write('_Token', serialize($token)); } return true; }
/** * Generates and writes 'Security.salt' * * @param string $path Project path * @return boolean Success * @access public */ function securitySalt($path) { $File = new File($path . 'config' . DS . 'core.php'); $contents = $File->read(); if (preg_match('/([\\t\\x20]*Configure::write\\(\\\'Security.salt\\\',[\\t\\x20\'A-z0-9]*\\);)/', $contents, $match)) { if (!class_exists('Security')) { require LIBS . 'security.php'; } $string = Security::generateAuthKey(); $result = str_replace($match[0], "\t" . 'Configure::write(\'Security.salt\', \'' . $string . '\');', $contents); if ($File->write($result)) { return true; } return false; } return false; }
/** * Step 4: finish * * @return void * @access public */ function finish() { $this->set('title_for_layout', __('Installation completed successfully', true)); $this->_check(); // set email address for admin Configure::Load('install'); $User = ClassRegistry::init('User'); $User->id = $User->field('id', array('user_name' => 'admin')); $User->saveField('email', 'admin@' . Configure::read('urls.domain')); // set new salt and seed value $File =& new File(CONFIGS . 'core.php'); if (!class_exists('Security')) { require LIBS . 'security.php'; } $salt = Security::generateAuthKey(); $seed = mt_rand() . mt_rand(); $contents = $File->read(); $contents = preg_replace('/(?<=Configure::write\\(\'Security.salt\', \')([^\' ]+)(?=\'\\))/', $salt, $contents); $contents = preg_replace('/(?<=Configure::write\\(\'Security.cipherSeed\', \')(\\d+)(?=\'\\))/', $seed, $contents); if (!$File->write($contents)) { return false; } // set password, hashed according to new salt value $User->saveField('password', Security::hash('password', 'sha256', $salt)); $this->_writeInstalled(); }
function finish() { $this->_check(); $this->set('title_for_layout', __('Installation completed sucessfully', true)); if (isset($this->params['named']['delete'])) { App::import('Core', 'Folder'); $this->folder = new Folder(); } copy(CONFIGS . 'settings.yml.install', CONFIGS . 'settings.yml'); $file =& new File(CONFIGS . 'settings.yml'); $settings = Spyc::YAMLLoad($file->read()); $settings['Install']['date'] = date(DATE_RFC822); $settings = Spyc::YAMLDump($settings, 4, 60); $file->write($settings); $File =& new File(CONFIGS . 'core.php'); if (!class_exists('Security')) { uses('security.php'); } $salt = Security::generateAuthKey(); $seed = mt_rand() . mt_rand(); $contents = $File->read(); $contents = preg_replace('/(?<=Configure::write\\(\'Security.salt\', \')([^\' ]+)(?=\'\\))/', $salt, $contents); $contents = preg_replace('/(?<=Configure::write\\(\'Security.cipherSeed\', \')([^\' ]+)(?=\'\\))/', $seed, $contents); if (!$File->write($contents)) { return false; } $this->redirect('/'); }
/** * Add authentication key for new form posts * * @param object $controller Instantiating controller * @return bool Success */ protected function _generateToken($controller) { if (isset($controller->request->params['requested']) && $controller->request->params['requested'] === 1) { if ($this->Session->check('_Token')) { $tokenData = $this->Session->read('_Token'); $controller->request->params['_Token'] = $tokenData; } return false; } $authKey = Security::generateAuthKey(); $token = array('key' => $authKey, 'allowedControllers' => $this->allowedControllers, 'allowedActions' => $this->allowedActions, 'disabledFields' => $this->disabledFields, 'csrfTokens' => array()); $tokenData = array(); if ($this->Session->check('_Token')) { $tokenData = $this->Session->read('_Token'); if (!empty($tokenData['csrfTokens']) && is_array($tokenData['csrfTokens'])) { $token['csrfTokens'] = $this->_expireTokens($tokenData['csrfTokens']); } } if ($this->csrfCheck && ($this->csrfUseOnce || empty($tokenData['csrfTokens']))) { $token['csrfTokens'][$authKey] = strtotime($this->csrfExpires); } $controller->request->params['_Token'] = $token; $this->Session->write('_Token', $token); return true; }
/** * Step 1 * Index * * @author Jun Nishikawa <*****@*****.**> * @return void * @codeCoverageIgnore **/ public function index() { // Initialize master database connection if (!$this->__saveDBConf($this->chooseDBByEnvironment())) { $this->Session->setFlash(__d('install', 'Failed to write %s. Please check permission.', array(APP . 'Config' . DS . 'database.php'))); return; } // Initialize application.yml Configure::write('Security.salt', Security::generateAuthKey()); Configure::write('Security.cipherSeed', mt_rand() . mt_rand() . mt_rand() . mt_rand()); Configure::write('Config.languageEnabled', array('en', 'ja')); if (isset($this->request->query['language'])) { Configure::write('Config.language', $this->request->query['language']); } Configure::write('NetCommons.installed', false); Configure::write('App.siteName', 'NetCommons'); Configure::write('App.siteDescription', 'NetCommons'); if (!$this->__saveAppConf()) { $this->Session->setFlash(__d('install', 'Failed to write %s. Please check permission.', array(APP . 'Config' . DS . 'application.yml'))); return; } if ($this->request->is('post')) { $this->redirect(array('action' => 'init_permission')); } }
/** * Step 3: finish * * Remind the user to delete 'install' plugin * Copy settings.yml file into place * * @return void * @access public */ public function finish() { $this->set('title_for_layout', __('Installation completed successfully', true)); if (isset($this->params['named']['delete'])) { App::import('Core', 'Folder'); $this->folder = new Folder(); if ($this->folder->delete(APP . 'plugins' . DS . 'install')) { $this->Session->setFlash(__('Installation files deleted successfully.', true), 'default', array('class' => 'success')); $this->redirect('/'); } else { return $this->Session->setFlash(__('Could not delete installation files.', true), 'default', array('class' => 'error')); } } $this->_check(); // set new salt and seed value copy(CONFIGS . 'settings.yml.install', CONFIGS . 'settings.yml'); $File =& new File(CONFIGS . 'core.php'); if (!class_exists('Security')) { require LIBS . 'security.php'; } $salt = Security::generateAuthKey(); $seed = mt_rand() . mt_rand(); $contents = $File->read(); $contents = preg_replace('/(?<=Configure::write\\(\'Security.salt\', \')([^\' ]+)(?=\'\\))/', $salt, $contents); $contents = preg_replace('/(?<=Configure::write\\(\'Security.cipherSeed\', \')(\\d+)(?=\'\\))/', $seed, $contents); if (!$File->write($contents)) { return false; } // set new password for admin, hashed according to new salt value $User = ClassRegistry::init('User'); $User->id = $User->field('id', array('username' => 'admin')); $User->saveField('password', Security::hash('password', null, $salt)); }
/** * Step 3, Database * * @param bool $skip * @return void */ public function database($skip = false) { $_step = 3; Configure::write('installStep', $_step); Configure::write('installPercentage', $_step / $this->totalInstallSteps * 100); if (!$this->__stepSuccess(array('license', 'server_test'), true)) { $this->redirect(array('action' => 'index')); } $configExists = file_exists(APP . 'Config' . DS . 'database.php'); $this->set('configExists', $configExists); if (!empty($this->data) || $configExists && $skip) { App::uses('ConnectionManager', 'Model'); $this->__clearCache(); $continueEmail = true; $continueDb = true; if (!$configExists) { $data = $this->data; $data['datasource'] = 'Database/Mysql'; $data['persistent'] = false; $data = Hash::merge($this->__defaultDbConfig, $data); $continueEmail = $this->__writeEmailFile($data); $continueDb = $this->__writeDatabaseFile($data); } if (!$continueEmail) { $this->Session->setFlash(__('Could not write email.php file! You will not be able to send user verification emails.'), null, null, 'error'); } if ($continueDb) { try { $db = ConnectionManager::getDataSource('default'); $data = $db->config; } catch (Exception $e) { $this->Session->setFlash(__('Could not connect to database.'), null, null, 'error'); if (!$configExists) { $this->__removeDatabaseFile(); } return; } App::uses('Model', 'Model'); App::uses('CakeSchema', 'Model'); $schema = new CakeSchema(array('name' => 'Xlrstats', 'file' => 'xlrstats.php')); $schema = $schema->load(); $execute = array(); $sources = $db->listSources(); foreach (array_keys($schema->tables) as $table) { if (in_array($data['prefix'] . $table, $sources)) { $this->Session->setFlash(__('A previous installation of XLRstats already exists, please empty your database!'), null, null, 'error'); if (!$configExists) { $this->__removeDatabaseFile(); $this->__removeEmailFile(); } return; } } foreach ($schema->tables as $table => $fields) { $create = $db->createSchema($schema, $table); $execute[] = $db->execute($create); $db->reconnect(); } $dataPath = APP . 'Config' . DS . 'Schema' . DS . 'data' . DS; $modelDataObjects = App::objects('class', $dataPath, false); foreach ($modelDataObjects as $model) { /** @noinspection PhpIncludeInspection */ include_once $dataPath . $model . '.php'; $model = new $model(); $Model = new Model(array('name' => get_class($model), 'table' => $model->table, 'ds' => 'default')); $Model->cacheSources = false; if (isset($model->records) && !empty($model->records)) { foreach ($model->records as $record) { $Model->create($record); $execute[] = $Model->save(); } } } if (!in_array(false, array_values($execute), true)) { App::uses('Security', 'Utility'); App::load('Security'); $salt = Security::generateAuthKey(); $seed = mt_rand() . mt_rand(); $file = APP . DS . 'Config' . DS . 'security.php'; $contents = "<?php\n"; $contents .= "Configure::write('Security.salt', '" . $salt . "');\n"; $contents .= "Configure::write('Security.cipherSeed', '" . $seed . "');\n"; file_put_contents($file, $contents); Cache::write('XlrInstallDatabase', 'success'); // fix: Security keys change //$this->Session->write('XlrInstallDatabase', 'success'); $this->__stepSuccess('database'); $this->redirect(array('action' => 'user_account')); } else { $this->Session->setFlash(__('Could not dump database.'), null, null, 'error'); } } else { $this->Session->setFlash(__('Could not write database.php file.'), null, null, 'error'); } } }
/** * application.ymlの初期値セット * * @param mixed $data 登録データ * @return bool */ public function installApplicationYaml($data) { // phpDocumentor Settings // Put author name to netcommons.php or netcommons.yaml /* $author = 'Noriko Arai, Ryuji Masukawa'; */ $author = 'Your Name <*****@*****.**>'; $header = <<<EOF * @author Noriko Arai <*****@*****.**> * @author {$author} * @link http://www.netcommons.org NetCommons Project * @license http://www.netcommons.org/license.txt NetCommons License * @copyright Copyright 2014, NetCommons Project EOF; Configure::write('PhpDocumentor.classHeader', $header); Configure::write('Security.salt', Security::generateAuthKey()); Configure::write('Security.cipherSeed', mt_rand() . mt_rand() . mt_rand() . mt_rand()); Configure::write('Config.languageEnabled', Hash::get($data, 'languageEnabled', ['en', 'ja'])); Configure::write('Config.language', Hash::get($data, 'language', 'ja')); Configure::write('NetCommons.installed', false); return $this->saveAppConf(); }
/** * undocumented function * * @param string $userId * @return void * @access public */ function referral_key($userId, $forceCreate = false) { App::import('Core', 'Security'); if (!$forceCreate) { $key = $this->lookup(array('id' => $userId), 'referral_key', false); if (!empty($key)) { return $key; } } do { $key = Security::generateAuthKey(); $key = substr($key, 0, 10); } while (!$this->isUnique(array('referral_key' => $key))); $this->set(array('id' => $userId, 'referral_key' => $key)); $this->save(); return $key; }
/** * Erzeugt einen neuen Benutzer. Ruft das entsprechende Formular auf und validiert die Daten * nachdem ein Benutzer mit dem Formular interagiert hat. * * @param keine */ public function create() { // wurden Daten ueber das Formular uebergeben? if (!empty($this->request->data["users"])) { // Setze das Datenmodel fuer die Validierung $this->User->set($this->request->data["users"]); // Rufe die Validierung des Datenmodels User auf und pruefe deren Ergebnis if (!$this->User->validates()) { $this->set('infoboxclass', 'danger'); // generiere Fehlermeldung $notice = ""; foreach ($this->User->validationErrors as $key => $value) { $notice .= '<p>' . $this->User->validationErrors[$key][0] . '</p>'; } $this->set('notice', $notice); return; } // erzeuge Strings fuer das Ablauf- und Freischaltungsdatum $valid_from = $this->request->data["users"]["valid_from"]["year"] . '-' . $this->request->data["users"]["valid_from"]["month"] . '-' . $this->request->data["users"]["valid_from"]["day"]; $valid_to = $this->request->data["users"]["valid_to"]["year"] . '-' . $this->request->data["users"]["valid_to"]["month"] . '-' . $this->request->data["users"]["valid_to"]["day"]; // Ist das Ablaufdatum frueher als das Freischaltungsdatum? if ($valid_from > $valid_to) { $this->set('infoboxclass', 'danger'); $this->set('notice', 'Fehler! Das Ablaufdatum liegt vor dem Freischaltungsdatum!'); return; } // Ist das Ablaufdatum gleich dem Freischaltungsdatum? if ($valid_from == $valid_to) { $this->set('infoboxclass', 'warning'); $this->set('notice', 'Achtung! Das Ablaufdatum ist gleich dem Freischaltungsdatum!'); return; } // generiere ein zufaelliges Passwort $password = Security::generateAuthKey(); $url = 'https://prsb.xsheep.de'; // erzeuge die Benachrichtigungsemail $mailtxt = "Hallo " . $this->request->data["users"]["forename"] . " " . $this->request->data["users"]["surname"] . ",\n\n" . "dir wurde ein Benutzeraccount für den Arbeitsgruppenorganisator des PRSB TU Berlin (" . $url . ") angelegt.\n\n" . "Deine Benutzerdaten sind:\n" . "E-Mail: " . $this->request->data["users"]["email"] . " (dient auch als Loginname)\n" . "Passwort: " . $password . "\n\n" . "Das Passwort kannst du nach deinem 1. Login ändern.\n\n" . "Viel Spaß und viele Grüße\n" . "Dein PRSB an der TU Berlin"; // Versende die Benachrichtigungsmail $email = new CakeEmail('smtp'); $email->to($this->request->data["users"]["email"]); $email->subject('Dein Benutzeraccount für den Arbeitsgruppenorganisator des PRSB TU Berlin'); $email->send($mailtxt); // hashe das Passwort //$password = Security::hash( $password, 'blowfish' ); // erzeuge Array gemaess dem Model $postData = array('password' => $password, 'username' => strtolower($this->request->data["users"]["email"]), 'forename' => $this->request->data["users"]["forename"], 'surname' => $this->request->data["users"]["surname"], 'valid_from' => $valid_from, 'valid_to' => $valid_to, 'role' => $this->request->data["users"]["role"]); // fuege den Benutzer in die Datenbank ein $this->User->save($postData); // setze View Informationen $this->set('infoboxclass', 'success'); $this->set('notice', '<p>Der Benutzeraccount wurde erfolgreich angelegt.</p>'); return; } }
/** * Manually add CSRF token information into the provided request object. * * @param CakeRequest $request The request object to add into. * @return bool */ public function generateToken(CakeRequest $request) { if (isset($request->params['requested']) && $request->params['requested'] === 1) { if ($this->Session->check('_Token')) { $request->params['_Token'] = $this->Session->read('_Token'); } return false; } $authKey = Security::generateAuthKey(); $token = array('key' => $authKey, 'allowedControllers' => $this->allowedControllers, 'allowedActions' => $this->allowedActions, 'unlockedFields' => array_merge($this->disabledFields, $this->unlockedFields), 'csrfTokens' => array()); $tokenData = array(); if ($this->Session->check('_Token')) { $tokenData = $this->Session->read('_Token'); if (!empty($tokenData['csrfTokens']) && is_array($tokenData['csrfTokens'])) { $token['csrfTokens'] = $this->_expireTokens($tokenData['csrfTokens']); } } if ($this->csrfUseOnce || empty($token['csrfTokens'])) { $token['csrfTokens'][$authKey] = strtotime($this->csrfExpires); } if (!$this->csrfUseOnce) { $csrfTokens = array_keys($token['csrfTokens']); $authKey = $csrfTokens[0]; $token['key'] = $authKey; $token['csrfTokens'][$authKey] = strtotime($this->csrfExpires); } $this->Session->write('_Token', $token); $request->params['_Token'] = array('key' => $token['key'], 'unlockedFields' => $token['unlockedFields']); return true; }
/** * Component startup. All security checking happens here. * * @param object $controller * @return unknown * @access public */ function startup(&$controller) { if (is_array($this->requirePost) && !empty($this->requirePost)) { if (in_array($controller->action, $this->requirePost)) { if (!$this->RequestHandler->isPost()) { if (!$this->blackHole($controller)) { return null; } } } } if (is_array($this->requireAuth) && !empty($this->requireAuth) && !empty($controller->params['form'])) { if (in_array($controller->action, $this->requireAuth)) { if (!isset($controller->params['data']['_Token'])) { if (!$this->blackHole($controller)) { return null; } } $token = $controller->params['data']['_Token']['key']; if ($this->Session->check('_Token')) { $tData = $this->Session->read('_Token'); if (!(intval($tData['expires']) > strtotime('now')) || $tData['key'] !== $token) { if (!$this->blackHole($controller)) { return null; } } if (!empty($tData['allowedControllers']) && !in_array($controller->params['controller'], $tData['allowedControllers']) || !empty($tData['allowedActions']) && !in_array($controller->params['action'], $tData['allowedActions'])) { if (!$this->blackHole($controller)) { return null; } } } else { if (!$this->blackHole($controller)) { return null; } } } } if (!isset($controller->params['requested']) || $controller->params['requested'] != 1) { // Add auth key for new form posts $authKey = Security::generateAuthKey(); $expires = strtotime('+' . Security::inactiveMins() . ' minutes'); $token = array('key' => $authKey, 'expires' => $expires, 'allowedControllers' => $this->allowedControllers, 'allowedActions' => $this->allowedActions); if (!isset($controller->params['data'])) { $controller->params['data'] = array(); } $controller->params['_Token'] = $token; $this->Session->write('_Token', $token); } }
/** * Generates and writes 'Security.cipherSeed' * * @param string $path Project path * @return bool Success */ public function securityCipherSeed($path) { $File = new File($path . 'Config' . DS . 'core.php'); $contents = $File->read(); if (preg_match('/([\\s]*Configure::write\\(\'Security.cipherSeed\',[\\s\'A-z0-9]*\\);)/', $contents, $match)) { App::uses('Security', 'Utility'); $string = substr(bin2hex(Security::generateAuthKey()), 0, 30); $result = str_replace($match[0], "\t" . 'Configure::write(\'Security.cipherSeed\', \'' . $string . '\');', $contents); if ($File->write($result)) { return true; } return false; } return false; }
/** * Resets for the email of a user ... */ private function emailReset() { $member = $this->Member->find("first", array("conditions" => array("Member.email" => $this->data["Member"]["forgot_email"]))); if ($member) { $reset = Security::generateAuthKey(); $member["Member"]["reset_code"] = $reset; $this->Member->save($member, false); $this->Email->from = "Qalanjo Mailer<*****@*****.**>"; $this->Email->to = $member["Member"]["email"]; $this->Email->subject = "Forgot Password"; $this->Email->replyTo = "*****@*****.**"; $this->Email->template = "simple_reset"; $this->Email->sendAs = "html"; $this->set('smtp_errors', $this->Email->smtpError); $this->set("member", $member); $this->Email->send(); $this->set("response", "true"); $this->render("/elements/responses", "ajax"); } else { $result["error"] = "Email <span class=\"account\">{$this->data["Member"]["forgot_email"]}</span> Was Not Found in Our System"; $this->set("response", json_encode($result)); $this->render("/elements/responses", "ajax"); } }