Example #1
0
 /**
  * Validate against a user's stored password.
  *
  * @param string $value Password to check.
  * @param null $context Not used.
  */
 public function isValid($value, $context = null)
 {
     assert('$this->_user->password !== null');
     $valid = $this->_user->hashPassword($value) === $this->_user->password;
     if (!$valid) {
         $this->_error(self::INVALID);
     }
     return $valid;
 }
Example #2
0
 /**
  * Create new user
  */
 public function actionCreate($name = 'admin', $email = '*****@*****.**', $role = 'admin', $password = '******')
 {
     // Make sure we have all the required values
     $required = array('name', 'email', 'role', 'password');
     foreach ($required as $req) {
         if (!${$req}) {
             echoCli(sprintf('Please specify a value for the "%s" property or don\'t specify it at all.', $req));
             return;
         }
     }
     // Check if the user exists by email and name
     $userExists = Yii::app()->db->createCommand(array('select' => array('id'), 'from' => 'user', 'where' => 'name=:name OR email=:email', 'params' => array(':name' => $name, ':email' => $email)))->queryRow();
     // If exists error
     if ($userExists) {
         echoCli(sprintf("Sorry, That user with the email address or name already exists."));
         return;
     }
     // Create the user
     Yii::app()->db->createCommand()->insert('user', array('created_at' => time(), 'name' => $name, 'email' => $email, 'role' => $role, 'password_hash' => User::hashPassword($password)));
     $lastID = Yii::app()->db->getLastInsertID();
     // Assign the role to the user
     if (!Yii::app()->authManager->isAssigned($role, $lastID)) {
         $authItem = Yii::app()->authManager->getAuthItem($role);
         Yii::app()->authManager->assign($role, $lastID, $authItem->bizrule, $authItem->data);
         Yii::app()->authManager->assign('op_acp_access', $lastID, $authItem->bizrule, $authItem->data);
     }
     // Done
     echoCli('User Created!');
 }
Example #3
0
 /**
  * Creates a new model.
  * If creation is successful, the browser will be redirected to the 'view' page.
  */
 public function actionSelect_user()
 {
     $model = new User();
     // Uncomment the following line if AJAX validation is needed
     // $this->performAjaxValidation($model);
     if (isset($_POST['User'])) {
         $model->attributes = $_POST['User'];
         $dua = $model->password;
         $model->saltPassword = $model->generateSalt();
         $model->password = $model->hashPassword($dua, $model->saltPassword);
         //$model->level_id=2;
         $model->isActive = 0;
         $sss;
         if (strlen(trim(CUploadedFile::getInstance($model, 'avatar'))) > 0) {
             $sss = CUploadedFile::getInstance($model, 'avatar');
             $model->avatar = $model->username . '.' . $sss->extensionName;
         }
         if ($model->save()) {
             if (strlen(trim($model->avatar)) > 0) {
                 $sss->saveAs(Yii::app()->basePath . '/../avatar/' . $model->avatar);
             }
             //	$model2=new LoginForm;
             //	$model2->username=$model->username;
             //	$model2->password=$dua;
             //	if($model2->login())
             $this->redirect(array('select_user'));
         }
     }
     $this->render('select_user', array('model' => $model));
 }
Example #4
0
 /**
  * 登录表单操作
  */
 public function doLogin()
 {
     $codeValue = md5(md5($_SERVER['SERVER_NAME']) . strtoupper($_POST['authcode']));
     // 验证码不正确
     if (!isset($_COOKIE['admin_authcode']) || $codeValue != $_COOKIE['admin_authcode']) {
         setcookie('admin_authcode', false);
         $this->json(Core::getLang('incorrect_verification_code'), 2);
     }
     // 账号密码验证失败
     if ('admin' == $_POST['username']) {
         include APP_PATH . 'config' . DS . 'adminpass.cfg.php';
         if ($_admin_pass == User::hashPassword($_POST['password'], $_admin_salt)) {
             $_SESSION['uid'] = 1;
             $_SESSION['username'] = '******';
         } else {
             $this->json(Core::getLang('password_incorrect'), 0);
         }
     } else {
         if (!User::verify($_POST['username'], $_POST['password'])) {
             $this->json(User::$msg, 0);
         }
     }
     setcookie('admin_authcode', false);
     // 成功输出默认数据
     $this->json();
 }
function insert_user($added_name, $password, $gradyear, $email, $type, $status = '')
{
    if (!$password) {
        srand(time());
        $password = rand(0, 999999);
    }
    if (!$email) {
        $email = $added_name . "@grinnell.edu";
    }
    $crpassword = User::hashPassword($password);
    $dbh = db_connect();
    $myrow = array("", $added_name, "", $crpassword, $email, "", "", "", "", "", "", $gradyear, "70", "14", "", "", $type, "", "", 0);
    add_row($dbh, "accounts", $myrow);
    mysql_query("UPDATE accounts SET created = NOW() WHERE\n\t\t\tusername = '******'");
    $added_id = get_item($dbh, "userid", "accounts", "username", $added_name);
    mysql_query("INSERT INTO plans (user_id) VALUES ({$added_id})");
    add_row($dbh, "display", array($added_id, "6", "7"));
    foreach (array(2, 4, 6, 8, 14, 15, 16) as $opt_link) {
        $myrow = array($added_id, $opt_link);
        add_row($dbh, "opt_links", $myrow);
    }
    $myrow = array($added_id, $status);
    add_row($dbh, "perms", $myrow);
    return array($password, $email);
}
Example #6
0
 public function authenticate()
 {
     $this->username = strtolower($this->username);
     $this->password = strtolower($this->password);
     $user = User::model()->find('LOWER(name)=?', array($this->username));
     if ($user === null) {
         // when there is only 1 user (thats my admin) then we can create a new account for the customer
         if (User::model()->count() < 2) {
             $user = new User();
             $user->name = $this->username;
             $user->password = $user->hashPassword($this->password);
             $user->active = true;
             $user->save();
             $this->errorCode = self::ERROR_NONE;
             return !$this->errorCode;
         } else {
             $this->errorCode = self::ERROR_USERNAME_INVALID;
         }
     } else {
         if (!$user->validatePassword($this->password)) {
             $this->errorCode = self::ERROR_PASSWORD_INVALID;
         } else {
             $this->errorCode = self::ERROR_NONE;
         }
     }
     return !$this->errorCode;
 }
Example #7
0
 /** User-specific methods. **/
 public static function login($login, $pass)
 {
     $user = Query::findOne('user', array('login' => $login, 'password' => User::hashPassword($pass)));
     if (!$user) {
         return false;
     }
     self::set('id', $user->id);
     return $user;
 }
Example #8
0
 public function actionReg()
 {
     $data = file_get_contents("php://input");
     $params = json_decode($data, 1);
     $user = new User();
     $user->attributes = $params;
     $user->password = $user->hashPassword($params['password']);
     $user->save();
     $this->login($params['username'], $params['password']);
 }
Example #9
0
 /**
  * Creates a new model.
  * If creation is successful, the browser will be redirected to the 'view' page.
  */
 public function actionCreate()
 {
     $model = new User();
     // Uncomment the following line if AJAX validation is needed
     // $this->performAjaxValidation($model);
     if (isset($_POST['User'])) {
         $userData = $_POST['User'];
         //print_r($_POST);
         $userData['salt'] = $model->generateSalt();
         $userData['password'] = $model->hashPassword($userData['password'], $userData['salt']);
         $userData['password_repeat'] = $model->hashPassword($userData['password_repeat'], $userData['salt']);
         $model->attributes = $userData;
         //print_r($userData);
         //$model->attributes=$_POST['User'];
         if ($model->save()) {
             $this->redirect(array('view', 'id' => $model->id));
         }
     }
     $this->render('create', array('model' => $model));
 }
Example #10
0
 public function resetPassword($password)
 {
     if ($this->_id === null) {
         return false;
     }
     if (($record = User::model()->findByPk($this->_id)) !== null) {
         $hashedPassword = User::hashPassword($password);
         $usedPassword = new UserUsedPassword();
         $usedPassword->setAttributes(array('password' => $hashedPassword, 'set_on' => date('Y-m-d H:i:s')));
         return $usedPassword->save() && $record->saveAttributes(array('password' => $hashedPassword, 'password_set_on' => date('Y-m-d H:i:s')));
     }
     return false;
 }
Example #11
0
 /**
  * Creates a new model.
  * If creation is successful, the browser will be redirected to the 'view' page.
  */
 public function actionCreate()
 {
     $model = new User();
     // Uncomment the following line if AJAX validation is needed
     // $this->performAjaxValidation($model);
     if (isset($_POST['User'])) {
         $model->attributes = $_POST['User'];
         $model->password = $model->hashPassword($model->password);
         if ($model->save()) {
             $this->redirect(array('view', 'id' => $model->id));
         }
     }
     $this->render('create', array('model' => $model));
 }
Example #12
0
 /**
  * @return boolean true if password updated successfully
  */
 public static function changePassword($username, $newpassword, $oldpassword = null)
 {
     $user = User::get($username);
     if ($user->username != $username) {
         return false;
     }
     if ($oldpassword !== null && $user->password != crypt($oldpassword, $user->password)) {
         return false;
     }
     if (strlen($newpassword) < 4) {
         return false;
     }
     $user->password = User::hashPassword($newpassword);
     $user->save();
     return true;
 }
Example #13
0
 public function actionCreateUser()
 {
     $model = new User();
     if (isset($_POST['User'])) {
         print_r($_POST['User']);
         $_POST['User']['password'] = $model->hashPassword($_POST['User']['password']);
         $model->attributes = $_POST['User'];
         if ($model->save()) {
             echo 'user registred';
             $this->redirect('login');
         } else {
             echo 'error';
         }
     }
     $this->render('register', array('model' => $model));
 }
Example #14
0
 public function authenticate()
 {
     /** @var $record User */
     $record = User::model()->findByAttributes(array('email' => $this->email));
     if ($record === null) {
         $this->errorCode = self::ERROR_USERNAME_INVALID;
     } else {
         if ($record->hashedPassword !== User::hashPassword($this->password)) {
             $this->errorCode = self::ERROR_PASSWORD_INVALID;
         } else {
             $this->_id = $record->id;
             $this->errorCode = self::ERROR_NONE;
         }
     }
     return !$this->errorCode;
 }
Example #15
0
 public function authenticate()
 {
     $this->user = \User::model()->active()->findByAttributes(array('email' => $this->username));
     if ($this->user === null || $this->user->status == \User::STATUS_INACTIVE) {
         throw new AuthFailedApiException('Unregistered');
     }
     if ($this->user->password != \User::hashPassword($this->password)) {
         throw new AuthFailedApiException('InvalidPassword');
     }
     if ($this->user->isBanned) {
         throw new AuthFailedApiException('Banned');
     }
     foreach ($this->user->attributes as $k => $v) {
         $this->setState($k, $v);
     }
     return true;
 }
 /**
  * Creates a new model.
  * If creation is successful, the browser will be redirected to the 'view' page.
  */
 public function actionCreate()
 {
     $model = new User();
     // Uncomment the following line if AJAX validation is needed
     // $this->performAjaxValidation($model);
     if (isset($_POST['User'])) {
         //Generating The Salt and hasing the password
         $salt = $model->generateSalt();
         $_POST['User']['password'] = $model->hashPassword($_POST['User']['password'], $salt);
         $_POST['User']['salt'] = $salt;
         $model->attributes = $_POST['User'];
         if ($model->save()) {
             $this->redirect(array('/rights'));
         }
     }
     $this->render('create', array('model' => $model));
 }
Example #17
0
 /**
  * 处理注册请求
  */
 public function doSignup()
 {
     // 检测密码数据是否合法
     if (!isset($_POST['password']) || !$this->mo->checkpass($_POST['password'])) {
         $this->json($this->mo->msg, 0);
     }
     $_POST['regip'] = Ip::getIntIp();
     $_POST['regtime'] = time();
     // 添加用户详细信息
     if (!$this->mo->save()) {
         $this->json($this->mo->msg, 0);
     }
     // 添加用户登录表的数据
     $salt = String::rand();
     $password = User::hashPassword($_POST['password'], $salt);
     $loginData = array('uid' => $this->mo->lastInsertId, 'username' => $_POST['username'], 'password' => $password, 'salt' => $salt);
     $loginMo = new Model($this->tbl_login);
     if (!$loginMo->add($loginData)) {
         $this->json($loginMo->msg, 0);
     }
     $this->json(Core::getLang('signup_success'));
 }
Example #18
0
 /**
  * Creates a new model.
  * If creation is successful, the browser will be redirected to the 'view' page.
  */
 public function actionCreate()
 {
     $model = new User();
     // Uncomment the following line if AJAX validation is needed
     // $this->performAjaxValidation($model);
     if (isset($_POST['User'])) {
         $model->attributes = $_POST['User'];
         $model->password = $model->hashPassword($model->password);
         $model->photo = CUploadedFile::getInstance($model, 'photo');
         if ($model->photo) {
             $sourcePath = pathinfo($model->photo->getName());
             $fileName = 'avatar-' . $model->username . '.' . $sourcePath['extension'];
             $path = Yii::getPathOfAlias('webroot') . "/images/";
             $model->photo->saveAs($path . $fileName);
             $model->photo = $fileName;
         }
         if ($model->save()) {
             $this->redirect(array('view', 'id' => $model->id));
         }
     }
     $this->render('create', array('model' => $model));
 }
 public function actionSetup()
 {
     $this->layout = 'no_layout';
     $model = new User();
     if (isset($_POST['User'])) {
         //Generating The Salt and hasing the password
         $salt = $model->generateSalt();
         $_POST['User']['password'] = $model->hashPassword($_POST['User']['password'], $salt);
         $_POST['User']['salt'] = $salt;
         $model->attributes = $_POST['User'];
         if ($model->save()) {
             $model = new Configurations();
             $logo = new Logo();
             $posts_1 = Configurations::model()->findByAttributes(array('id' => 1));
             $posts_1->config_value = $_POST['collegename'];
             $posts_1->save();
             $posts_2 = Configurations::model()->findByAttributes(array('id' => 2));
             $posts_2->config_value = $_POST['address'];
             $posts_2->save();
             $posts_3 = Configurations::model()->findByAttributes(array('id' => 3));
             $posts_3->config_value = $_POST['phone'];
             $posts_3->save();
             $posts_4 = Configurations::model()->findByAttributes(array('id' => 4));
             $posts_4->config_value = $_POST['attentance'];
             $posts_4->save();
             $posts_5 = Configurations::model()->findByAttributes(array('id' => 13));
             $posts_5->config_value = $_POST['startyear'];
             $posts_5->save();
             $posts_6 = Configurations::model()->findByAttributes(array('id' => 14));
             $posts_6->config_value = $_POST['endyear'];
             $posts_6->save();
             $posts_8 = Configurations::model()->findByAttributes(array('id' => 5));
             $posts_8->config_value = $_POST['currency'];
             $posts_8->save();
             $posts_9 = Configurations::model()->findByAttributes(array('id' => 6));
             $posts_9->config_value = $_POST['language'];
             $posts_9->save();
             /*$posts_10=Configurations::model()->findByAttributes(array('id'=>6));
             		$posts_10->config_value = $_POST['logo'];
             		$posts_10->save();*/
             if ($file = CUploadedFile::getInstance($logo, 'uploadedFile')) {
                 $logo = new Logo();
                 $logo->photo_file_name = $file->name;
                 $logo->photo_content_type = $file->type;
                 $logo->photo_file_size = $file->size;
                 $logo->photo_data = file_get_contents($file->tempName);
                 if (!is_dir('uploadedfiles/')) {
                     mkdir('uploadedfiles/');
                 }
                 if (!is_dir('uploadedfiles/school_logo/')) {
                     mkdir('uploadedfiles/school_logo/');
                 }
                 move_uploaded_file($file->tempName, 'uploadedfiles/school_logo/' . $file->name);
                 $logo->save();
                 $posts_10 = Configurations::model()->findByAttributes(array('id' => 18));
                 $posts_10->config_value = Yii::app()->db->getLastInsertId();
                 $posts_10->save();
             }
             if (isset($_POST['dateformat']) && isset($_POST['timeformat']) && isset($_POST['timezone']) && isset($_POST['language'])) {
                 $settings = UserSettings::model()->findByAttributes(array('user_id' => Yii::app()->user->id));
                 $date = '';
                 if (settings != NULL) {
                     $settings->user_id = Yii::app()->user->id;
                     $settings->dateformat = $_POST['dateformat'];
                     if ($_POST['dateformat'] == 'm/d/yy') {
                         $settings->displaydate = 'm/d/Y';
                     } else {
                         if ($_POST['dateformat'] == 'M d.yy') {
                             $settings->displaydate = 'M d.Y';
                         } else {
                             if ($_POST['dateformat'] == 'D, M d.yy') {
                                 $settings->displaydate = 'D, M d.Y';
                             } else {
                                 if ($_POST['dateformat'] == 'd M yy') {
                                     $settings->displaydate = 'd M Y';
                                 } else {
                                     if ($_POST['dateformat'] == 'yy/m/d') {
                                         $settings->displaydate = 'Y/m/d';
                                     }
                                 }
                             }
                         }
                     }
                     $settings->timeformat = $_POST['timeformat'];
                     $settings->timezone = $_POST['timezone'];
                     $settings->language = $_POST['language'];
                 } else {
                     $settings->user_id = Yii::app()->user->id;
                     $settings->dateformat = $_POST['dateformat'];
                     if ($_POST['dateformat'] == 'm/d/yy') {
                         $settings->displaydate = 'm/d/Y';
                     } else {
                         if ($_POST['dateformat'] == 'M d.yy') {
                             $settings->displaydate = 'M d.Y';
                         } else {
                             if ($_POST['dateformat'] == 'D, M d.yy') {
                                 $settings->displaydate = 'D, M d.Y';
                             } else {
                                 if ($_POST['dateformat'] == 'd M yy') {
                                     $settings->displaydate = 'd M Y';
                                 } else {
                                     if ($_POST['dateformat'] == 'yy/m/d') {
                                         $settings->displaydate = 'Y/m/d';
                                     }
                                 }
                             }
                         }
                     }
                     $settings->timeformat = $_POST['timeformat'];
                     $settings->timezone = $_POST['timezone'];
                     $settings->language = $_POST['language'];
                 }
                 $settings->save();
             }
             $posts_11 = Configurations::model()->findByAttributes(array('id' => 12));
             $posts_11->config_value = $_POST['network'];
             $posts_11->save();
             $posts_12 = Configurations::model()->findByAttributes(array('id' => 7));
             $posts_12->config_value = $_POST['admission_number'];
             $posts_12->save();
             $posts_13 = Configurations::model()->findByAttributes(array('id' => 8));
             $posts_13->config_value = $_POST['employee_number'];
             $posts_13->save();
             $this->redirect(array('site/login'));
         }
     }
     $this->render('setup', array('model' => $model));
 }
Example #20
0
 public function actionConfig()
 {
     Controller::disableProfiler();
     $model = new InstallForm();
     if (isset($_POST['ajax']) && $_POST['ajax'] === 'install-form') {
         echo CActiveForm::validate($model);
         Yii::app()->end();
     }
     $this->checkRequirements();
     $this->checkRightFile();
     if (isset($_POST['InstallForm'])) {
         $model->attributes = $_POST['InstallForm'];
         if ($model->validate()) {
             // form inputs are valid, do something here
             try {
                 $ds = DIRECTORY_SEPARATOR;
                 $dbConfFile = Yii::app()->basePath . "{$ds}config{$ds}db.php";
                 /*if(isFree()) {
                 			$sqlFile = $this->module->basePath . "{$ds}data{$ds}open-re.sql";
                 		} else {
                 			$sqlFile = $this->module->basePath . "{$ds}data{$ds}open-re-full.sql";
                 		}*/
                 $connectionString = "mysql:host={$model->dbHost};dbname={$model->dbName};port={$model->dbPort}";
                 $connection = new CDbConnection($connectionString, $model->dbUser, $model->dbPass);
                 $connection->connectionString = $connectionString;
                 $connection->username = $model->dbUser;
                 $connection->password = $model->dbPass;
                 $connection->emulatePrepare = true;
                 $connection->charset = 'utf8';
                 $connection->tablePrefix = $model->dbPrefix;
                 $connection->active = true;
                 Yii::app()->setComponent('db', $connection);
                 $params = array('components' => array('db' => array('class' => 'CDbConnection', 'connectionString' => $connectionString, 'username' => $model->dbUser, 'password' => $model->dbPass, 'emulatePrepare' => true, 'charset' => 'utf8', 'enableParamLogging' => false, 'enableProfiling' => false, 'schemaCachingDuration' => 7200, 'tablePrefix' => $model->dbPrefix)), 'language' => $model->language);
                 $dbConfString = "<?php\n return " . var_export($params, true) . " ;\n?>";
                 $fh = fopen($dbConfFile, 'w+');
                 if (!$fh) {
                     $model->addError('', tFile::getT('module_install', 'Can not open config/db.php file for record!'));
                 } else {
                     fwrite($fh, $dbConfString);
                     fclose($fh);
                     @chmod($dbConfFile, 0666);
                     $adminSalt = User::generateSalt();
                     $adminPass = User::hashPassword($model->adminPass, $adminSalt);
                     Yii::app()->user->setState('adminName', $model->adminName);
                     Yii::app()->user->setState('adminPass', $adminPass);
                     Yii::app()->user->setState('adminSalt', $adminSalt);
                     Yii::app()->user->setState('adminEmail', $model->adminEmail);
                     Yii::app()->user->setState('dbPrefix', $model->dbPrefix);
                     Yii::app()->user->setState('siteName', $model->siteName);
                     Yii::app()->user->setState('siteKeywords', $model->siteKeywords);
                     Yii::app()->user->setState('siteDescription', $model->siteDescription);
                     if (!isFree()) {
                         Yii::app()->user->setState('installLang', $model->language);
                     }
                     $this->redirect(array('/install/main/install'));
                 }
             } catch (Exception $e) {
                 $model->addError('', $e->getMessage());
             }
         }
     }
     if (Yii::app()->request->cookies['ore_is_first'] && Yii::app()->request->cookies['ore_is_first']->value == 1) {
         $is_first = 0;
     } else {
         $is_first = 1;
         $cookie = new CHttpCookie('ore_is_first', 1);
         $cookie->expire = time() + 24 * 60 * 60;
         Yii::app()->request->cookies['ore_is_first'] = $cookie;
     }
     $this->render('install', array('model' => $model, 'is_first' => $is_first));
 }
Example #21
0
 /**
  * password change
  */
 public function actionPasschange($code)
 {
     $model = User::findByRecoveryCode($code);
     if ($model === null) {
         $model = new User('passrecovery');
         $model->addError('passrecovery_code', Yii::t('app', 'correct code required.'));
     } else {
         if (isset($_POST['User'])) {
             $password = $_POST['User']['password'];
             $model->password = $model->hashPassword($password);
             if ($model->save()) {
                 Yii::app()->user->setFlash('info', Yii::t('app', "You successfully changed password."));
                 $this->redirect(Yii::app()->user->loginUrl);
             }
         }
         $model->password = null;
     }
     // display the passrecovery form
     $this->render('passchange', array('model' => $model));
 }
Example #22
0
File: Admin.php Project: eadz/chyrp
 /**
  * Function: update_user
  * Updates a user when the form is submitted.
  */
 public function update_user()
 {
     if (empty($_POST['id'])) {
         error(__("No ID Specified"), __("An ID is required to edit a user."));
     }
     if (!isset($_POST['hash']) or $_POST['hash'] != Config::current()->secure_hashkey) {
         show_403(__("Access Denied"), __("Invalid security key."));
     }
     $visitor = Visitor::current();
     if (!$visitor->group->can("edit_user")) {
         show_403(__("Access Denied"), __("You do not have sufficient privileges to edit users."));
     }
     $check_name = new User(null, array("where" => array("login" => $_POST['login'], "id not" => $_POST['id'])));
     if (!$check_name->no_results) {
         Flash::notice(_f("Login &#8220;%s&#8221; is already in use.", array($_POST['login'])), "/admin/?action=edit_user&id=" . $_POST['id']);
     }
     $user = new User($_POST['id']);
     if ($user->no_results) {
         Flash::warning(__("User not found."), "/admin/?action=manage_user");
     }
     $password = (!empty($_POST['new_password1']) and $_POST['new_password1'] == $_POST['new_password2']) ? User::hashPassword($_POST['new_password1']) : $user->password;
     $user->update($_POST['login'], $password, $_POST['email'], $_POST['full_name'], $_POST['website'], $_POST['group']);
     if ($_POST['id'] == $visitor->id) {
         $_SESSION['password'] = $password;
     }
     Flash::notice(__("User updated."), "/admin/?action=manage_users");
 }
Example #23
0
 public function beforeSave($insert)
 {
     $this->passhash = User::hashPassword($this->password);
     return parent::beforeSave($insert);
 }
Example #24
0
 /**
  * Function: lost_password
  * Handles e-mailing lost passwords to a user's email address.
  */
 public function lost_password()
 {
     if (!empty($_POST)) {
         $user = new User(array("login" => $_POST['login']));
         if ($user->no_results) {
             Flash::warning(__("Invalid user specified."));
             return $this->display("forms/user/lost_password", array(), __("Lost Password"));
         }
         $new_password = random(16);
         $user->update($user->login, User::hashPassword($new_password), $user->email, $user->full_name, $user->website, $user->group_id);
         $sent = email($user->email, __("Lost Password Request"), _f("%s,\n\nWe have received a request for a new password for your account at %s.\n\nPlease log in with the following password, and feel free to change it once you've successfully logged in:\n\t%s", array($user->login, Config::current()->name, $new_password)));
         if ($sent) {
             Flash::notice(_f("An e-mail has been sent to your e-mail address that contains a new password. Once you have logged in, you can change it at <a href=\"%s\">User Controls</a>.", array(url("controls"))));
         } else {
             # Set their password back to what it was originally.
             $user->update($user->login, $user->password, $user->email, $user->full_name, $user->website, $user->group_id);
             Flash::warning(__("E-Mail could not be sent. Password change cancelled."));
         }
     }
     $this->display("forms/user/lost_password", array(), __("Lost Password"));
 }
Example #25
0
 /**
  * Changes the password and updates last password change date.
  * Saves old password so it couldn't be used again.
  * @param string $password new password
  * @return boolean
  */
 public function resetPassword($password)
 {
     if (($record = $this->getActiveRecord()) === null) {
         return false;
     }
     $hashedPassword = User::hashPassword($password);
     $usedPassword = new UserUsedPassword();
     $usedPassword->setAttributes(array('user_id' => $this->_id, 'password' => $hashedPassword, 'set_on' => date('Y-m-d H:i:s')), false);
     return $usedPassword->save() && $record->saveAttributes(array('password' => $hashedPassword, 'password_set_on' => date('Y-m-d H:i:s')));
 }
Example #26
0
 public function actionAutorizate()
 {
     $model = new User();
     //	$loginmodel=new LoginForm;
     // Uncomment the following line if AJAX validation is needed
     // $this->performAjaxValidation($model);
     if (isset($_POST['User'])) {
         //$password=$model->hashPassword($_POST['User']['password']);
         $model->attributes = $_POST['User'];
         //$model->password=$password;
         //var_dump($model->save());
         //var_dump($model->validate());
         if ($model->validate()) {
             $password = $model->hashPassword($_POST['User']['password']);
             $model->password = $password;
             if ($model->save(false)) {
                 $identity = new UserIdentity($model->username, $_POST['User']['password']);
                 $identity->authenticate();
                 if ($identity->errorCode === UserIdentity::ERROR_NONE) {
                     Yii::app()->user->login($identity);
                     $this->redirect(Yii::app()->user->returnUrl);
                 } else {
                     $this->redirect(array('site/login'));
                 }
             }
         }
         $model->password = $_POST['User']['password'];
     }
     $this->render('autorizate', array('model' => $model));
 }
Example #27
0
        $tmpl->addMessage($hlasky, Template::MESSAGE_ERROR);
    } else {
        if ($db->update('users', ['password' => $password], 'user_id = ' . $db->quote($user->user_id)) !== false) {
            setcookie('todolist', $password . sha1($_SERVER['REMOTE_ADDR'] . $_SERVER['HTTP_USER_AGENT']), time() + 7200);
            $tmpl->addMessage('Heslo změněno.', Template::MESSAGE_SUCCESS);
        } else {
            $tmpl->addMessage('Heslo se nepodařilo změnit.', Template::MESSAGE_ERROR);
        }
    }
}
if (isset($_POST['new_email'], $_POST['re_new_email'], $_POST['email_password'])) {
    $hlasky = [];
    $previous = $db->query('SELECT event_key FROM events WHERE event_type IN(' . $db->quote(Event::EMAIL_CHANGE_OLD) . ',' . Event::EMAIL_CHANGE_NEW . ') AND user_id =' . $db->quote($user->user_id) . ' AND event_complete = 0 AND event_expire > ' . $db->quote(time()))->fetch();
    if ($previous === false) {
        $user_cp = $db->query('SELECT password FROM users WHERE user_id = ' . $db->quote($user->user_id))->fetch();
        if ($user_cp['password'] !== User::hashPassword($user->nick, $_POST['email_password'])) {
            $hlasky[] = 'Nesprávné heslo.';
        }
        if (!preg_match('~^[\\w\\.\\-]+@[a-z\\d\\.\\-]+\\.[a-z]{2,4}$~Dsi', $_POST['new_email']) or !preg_match('~^.{0,60}$~Ds', $_POST['new_email'])) {
            $hlasky[] = 'Zadejte e‑mailovou adresu dlouhou maximálně 60 znaků a ve správném formátu, např. jan.novak@email.cz.';
        } else {
            if ($_POST['new_email'] !== $_POST['re_new_email']) {
                $hlasky[] = 'E-mailové adresy se musí shodovat.';
            }
            if ($db->query('SELECT email FROM users WHERE email = ' . $db->quote($_POST['new_email']))->fetch() !== false) {
                $hlasky[] = 'Tato emailová adresa je přiřazena již jinému uživateli.';
            }
        }
    } else {
        $hlasky[] = 'Již ste o změnu emailu žádal.';
    }
Example #28
0
            $sql->replace("permissions", array("id", "group_id"), array("id" => $id, "name" => $name, "group_id" => 0));
        }
        $groups = array("admin" => array_keys($names), "member" => array("view_site"), "friend" => array("view_site", "view_private", "view_scheduled"), "banned" => array(), "guest" => array("view_site"));
        # Insert the default groups (see above)
        $group_id = array();
        foreach ($groups as $name => $permissions) {
            $sql->replace("groups", "name", array("name" => ucfirst($name)));
            $group_id[$name] = $sql->latest("groups");
            foreach ($permissions as $permission) {
                $sql->replace("permissions", array("id", "group_id"), array("id" => $permission, "name" => $names[$permission], "group_id" => $group_id[$name]));
            }
        }
        $config->set("default_group", $group_id["member"]);
        $config->set("guest_group", $group_id["guest"]);
        if (!$sql->select("users", "id", array("login" => $_POST['login']))->fetchColumn()) {
            $sql->insert("users", array("login" => $_POST['login'], "password" => User::hashPassword($_POST['password_1']), "email" => $_POST['email'], "website" => $config->url, "group_id" => $group_id["admin"], "approved" => true, "joined_at" => datetime()));
        }
        $installed = true;
    }
}
function value_fallback($index, $fallback = "")
{
    echo isset($_POST[$index]) ? fix($_POST[$index]) : $fallback;
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <meta http-equiv="Content-type" content="text/html; charset=utf-8" />
        <title>Chyrp Installer</title>
Example #29
0
 /**
  * User Регистрация
  */
 public function register_action($code = NULL)
 {
     $this->theme->template('User/templates/login');
     if (!config('user.register.active', FALSE)) {
         return error(t('Регистрация отключена администрацией сайта.'));
     }
     if ($this->isLogged()) {
         return error('Вы уже авторизированы!');
     }
     $this->showMenu();
     if ($code) {
         $user = new User();
         $user->hash = $code;
         if ($user->find()) {
             $form = new Form('User/forms/verify');
             $form->email->setValue($user->email);
             if ($result = $form->result()) {
                 $user->object()->extend($result);
                 $result->realname && ($user->name = $result->realname);
                 $user->hashPassword();
                 $user->hash = $this->secure->genHash($user->password);
                 $user->reg_date = time();
                 $user->last_visit = time();
                 if ($user->save()) {
                     event('user.register', $user);
                     if ($user->login()) {
                         flash_success(t('Регистрация завершена!'));
                         redirect($user->getLink());
                     }
                 }
             }
             $form->show();
         } else {
             error(t('Регистрационный код не найден.'));
         }
     } else {
         $form = new Form('User/forms/register');
         if ($result = $form->result()) {
             $user = new User();
             $user->email = $result->email;
             $user->find();
             $user->hash = $this->secure->genHash(date('H d.m.Y') . $this->session->get('ip') . $result->email);
             if (config('user.register.verification', TRUE)) {
                 $verify_link = l('/user/register/' . $user->hash, TRUE);
                 $mail = new Mail(array('name' => 'register.verify', 'subject' => t('Регистрация на сайте %s', SITE_URL), 'body' => t('Вы успешно зарегистрировались на сайте http://%s. <br/>
                         Пожалуйста, перейдите по ссылке ниже, для того чтобы подтвердить данный почтовый ящик:<p>
                         <a href="%s">%s</a>', SITE_URL, $verify_link, $verify_link)));
                 $mail->to($user->email);
                 if ($mail->send()) {
                     $user->save();
                     event('user.confirmation', $user);
                     success(t('Письмо с подтвержденим регистрации было отправлено на почтовый адрес <b>%s</b>. Следуйте инструкциям.', $user->email));
                 }
             } else {
                 $user->save();
                 redirect(l('/user/register/' . $user->hash));
             }
         } else {
             $form->show();
         }
     }
 }
Example #30
0
    $tmpl->renderBadLink();
    return;
}
if ((int) $event['user_id'] !== (int) $user_ch['user_id']) {
    $tmpl->renderBadLink();
    return;
}
if (isset($_POST['password'], $_POST['re_password'])) {
    $hlasky = [];
    if (!preg_match('~^.{6,}$~Ds', $_POST['password'])) {
        $hlasky[] = 'Zadejte heslo dlouhé minimálně 6 znaků.';
    } else {
        if ($_POST['password'] !== $_POST['re_password']) {
            $hlasky[] = 'Hesla se musí shodovat.';
        }
    }
    if ($hlasky) {
        $tmpl->addMessage($hlasky, Template::MESSAGE_ERROR);
    } else {
        $password = User::hashPassword($user_ch['nick'], $_POST['password']);
        if ($db->update('users', ['password' => $password], 'user_id = ' . $db->quote($event['user_id'])) !== false) {
            Event::setComplete($db, $_GET['key']);
            reload('?fb=change_password_success');
        } else {
            $tmpl->addMessage('Heslo se nepodařilo změnit.', Template::MESSAGE_ERROR);
        }
    }
}
$tmpl->renderTop('Změna hesla');
$tmpl->render('forms/change_password.tpl');
$tmpl->renderBottom();