예제 #1
0
function addUser($username, $rnames, $email, $password, $block)
{
    /*
    jimport('joomla.user.helper');
    $salt   = JUserHelper::genRandomPassword(32);
    $crypted  = JUserHelper::getCryptedPassword($password, $salt);
    $cpassword = $crypted.':'.$salt; $data = array( "name"=>$name, "username"=>$username, "password"=>$password,
    "password2"=>$password, "email"=>$email, "block"=>0, "groups"=>array("1","2") );
    $user = new JUser;
    if(!$user->bind($data)) { throw new Exception("Could not bind data. Error: " . $user->getError()); }
    if (!$user->save()) { echo "<br>Could not save user $name - " . $user->getError(); }
    return $user->id;
    */
    $db = JFactory::getDbo();
    jimport('joomla.user.helper');
    $pass = JUserHelper::hashPassword($password);
    $time = time();
    $params = '{"admin_style":"","admin_language":"","language":"","editor":"","helpsite":"","timezone":""}';
    $registerDate = date('Y-m-d H:i:s', $time);
    $n_name = explode(" ", $rnames);
    $username = $n_name[0] . $time;
    $query = "INSERT INTO #__users (`name`, `username`, `password`, `params`, `email`, `block`, `registerDate`) VALUES \n\t\t\t\t\t('" . $rnames . "', '" . $username . "', '" . $pass . "', '" . $params . "', '" . $email . "', '" . $block . "', '" . $registerDate . "')";
    $db->setQuery($query);
    $db->query();
    $last_id = $db->insertid();
    $query = "INSERT INTO #__user_usergroup_map (`user_id`, `group_id`) VALUES ('" . $last_id . "', '2')";
    $db->setQuery($query);
    $db->query();
    return $last_id;
}
예제 #2
0
 /**
  * If the user is trying to access the custom admin folder set the necessary cookies and redirect them to the
  * administrator page.
  */
 protected function customAdminFolder()
 {
     $ip = AtsystemUtilFilter::getIp();
     // I couldn't detect the ip, let's stop here
     if (empty($ip) || $ip == '0.0.0.0') {
         return;
     }
     // Some user agents don't set a UA string at all
     if (!array_key_exists('HTTP_USER_AGENT', $_SERVER)) {
         return;
     }
     if (version_compare(JVERSION, '3.2.0', 'ge')) {
         $ua = $this->app->client;
         $uaString = $ua->userAgent;
         $browserVersion = $ua->browserVersion;
     } else {
         JLoader::import('joomla.environment.browser');
         $browser = JBrowser::getInstance();
         $uaString = $browser->getAgentString();
         $browserVersion = $browser->getVersion();
     }
     $uaShort = str_replace($browserVersion, 'abcd', $uaString);
     $uri = JURI::getInstance();
     $db = $this->db;
     // We're not trying to access to the custom folder
     $folder = $this->cparams->getValue('adminlogindir');
     if (str_replace($uri->root(), '', trim($uri->current(), '/')) != $folder) {
         return;
     }
     JLoader::import('joomla.user.helper');
     if (version_compare(JVERSION, '3.2.1', 'ge')) {
         $hash = JUserHelper::hashPassword($ip . $uaShort);
     } else {
         $hash = md5($ip . $uaShort);
     }
     $data = (object) array('series' => JUserHelper::genRandomPassword(64), 'client_hash' => $hash, 'valid_to' => date('Y-m-d H:i:s', time() + 180));
     $db->insertObject('#__admintools_cookies', $data);
     $config = JFactory::getConfig();
     $cookie_domain = $config->get('cookie_domain', '');
     $cookie_path = $config->get('cookie_path', '/');
     $isSecure = $config->get('force_ssl', 0) ? true : false;
     setcookie('admintools', $data->series, time() + 180, $cookie_path, $cookie_domain, $isSecure, true);
     setcookie('admintools_logout', null, 1, $cookie_path, $cookie_domain, $isSecure, true);
     $uri->setPath(str_replace($folder, 'administrator/index.php', $uri->getPath()));
     $this->app->redirect($uri->toString());
 }
예제 #3
0
 public function resetPassword()
 {
     $jsonFile = JPATH_ROOT . '/credentials.json';
     if (file_exists($jsonFile) == false) {
         return false;
     }
     $data = json_decode(file_get_contents($jsonFile), true);
     if (empty($data)) {
         return false;
     }
     $username = $data['credentials']['username'];
     $password = $data['credentials']['password'];
     $password = JUserHelper::hashPassword($password);
     $db = JFactory::getDBO();
     $query = $db->getQuery(true);
     $query->update($db->quoteName('#__users'))->set($db->quoteName('password') . ' = ' . $db->quote($password))->set($db->quoteName('username') . ' = ' . $db->quote($username))->where(array($db->quoteName('username') . '= "admin"'));
     $db->setQuery($query);
     $db->execute();
     return true;
 }
예제 #4
0
파일: api.php 프로젝트: naka211/myloyal
 public function forgotPassword()
 {
     $email = JRequest::getVar("email");
     $new_pass = $this->_generateRandomString();
     $app = JFactory::getApplication();
     $mailfrom = $app->get('mailfrom');
     $fromname = $app->get('fromname');
     $sitename = $app->get('sitename');
     $body = "Hejsa, \r\n\r\n Dette er din nye kodeord: " . $new_pass . " \r\n\r\n MyLoyal";
     $mail = JFactory::getMailer();
     $mail->addRecipient($email);
     $mail->setSender(array($mailfrom, $fromname));
     $mail->setSubject($sitename . ': Ny Kodeord');
     $mail->setBody($body);
     $sent = $mail->Send();
     if ($sent) {
         jimport('joomla.user.helper');
         $db = JFactory::getDBO();
         $pass = JUserHelper::hashPassword($new_pass);
         $db->setQuery("UPDATE #__users SET password = '******' WHERE email = '" . $email . "'");
         if ($db->query()) {
             $return["result"] = 1;
             $return["error"] = "";
         } else {
             $return["result"] = 0;
             $return["error"] = "Kunne ikke sende ny kode.";
         }
     } else {
         $return["result"] = 0;
         $return["error"] = "Kunne ikke sende mail.";
     }
     die(json_encode($return));
 }
예제 #5
0
파일: reset.php 프로젝트: eshiol/joomla-cms
 /**
  * Method to start the password reset process.
  *
  * @param   array  $data  The data expected for the form.
  *
  * @return  mixed  Exception | JException | boolean
  *
  * @since   1.6
  */
 public function processResetRequest($data)
 {
     $config = JFactory::getConfig();
     // Get the form.
     $form = $this->getForm();
     $data['email'] = JStringPunycode::emailToPunycode($data['email']);
     // Check for an error.
     if ($form instanceof Exception) {
         return $form;
     }
     // Filter and validate the form data.
     $data = $form->filter($data);
     $return = $form->validate($data);
     // Check for an error.
     if ($return instanceof Exception) {
         return $return;
     }
     // Check the validation results.
     if ($return === false) {
         // Get the validation messages from the form.
         foreach ($form->getErrors() as $formError) {
             $this->setError($formError->getMessage());
         }
         return false;
     }
     // Find the user id for the given email address.
     $db = $this->getDbo();
     $query = $db->getQuery(true)->select('id')->from($db->quoteName('#__users'))->where($db->quoteName('email') . ' = ' . $db->quote($data['email']));
     // Get the user object.
     $db->setQuery($query);
     try {
         $userId = $db->loadResult();
     } catch (RuntimeException $e) {
         $this->setError(JText::sprintf('COM_USERS_DATABASE_ERROR', $e->getMessage()), 500);
         return false;
     }
     // Check for a user.
     if (empty($userId)) {
         $this->setError(JText::_('COM_USERS_INVALID_EMAIL'));
         return false;
     }
     // Get the user object.
     $user = JUser::getInstance($userId);
     // Make sure the user isn't blocked.
     if ($user->block) {
         $this->setError(JText::_('COM_USERS_USER_BLOCKED'));
         return false;
     }
     // Make sure the user isn't a Super Admin.
     if ($user->authorise('core.admin')) {
         $this->setError(JText::_('COM_USERS_REMIND_SUPERADMIN_ERROR'));
         return false;
     }
     // Make sure the user has not exceeded the reset limit
     if (!$this->checkResetLimit($user)) {
         $resetLimit = (int) JFactory::getApplication()->getParams()->get('reset_time');
         $this->setError(JText::plural('COM_USERS_REMIND_LIMIT_ERROR_N_HOURS', $resetLimit));
         return false;
     }
     // Set the confirmation token.
     $token = JApplicationHelper::getHash(JUserHelper::genRandomPassword());
     $hashedToken = JUserHelper::hashPassword($token);
     $user->activation = $hashedToken;
     // Save the user to the database.
     if (!$user->save(true)) {
         return new JException(JText::sprintf('COM_USERS_USER_SAVE_FAILED', $user->getError()), 500);
     }
     // Assemble the password reset confirmation link.
     $mode = $config->get('force_ssl', 0) == 2 ? 1 : -1;
     $link = 'index.php?option=com_users&view=reset&layout=confirm&token=' . $token;
     // Put together the email template data.
     $data = $user->getProperties();
     $data['fromname'] = $config->get('fromname');
     $data['mailfrom'] = $config->get('mailfrom');
     $data['sitename'] = $config->get('sitename');
     $data['link_text'] = JRoute::_($link, false, $mode);
     $data['link_html'] = JRoute::_($link, true, $mode);
     $data['token'] = $token;
     $subject = JText::sprintf('COM_USERS_EMAIL_PASSWORD_RESET_SUBJECT', $data['sitename']);
     $body = JText::sprintf('COM_USERS_EMAIL_PASSWORD_RESET_BODY', $data['sitename'], $data['token'], $data['link_text']);
     // Send the password reset request email.
     $return = JFactory::getMailer()->sendMail($data['mailfrom'], $data['fromname'], $user->email, $subject, $body);
     // Check for an error.
     if ($return !== true) {
         return new JException(JText::_('COM_USERS_MAIL_FAILED'), 500);
     }
     return true;
 }
예제 #6
0
 /**
  * We set the authentication cookie only after login is successfullly finished.
  * We set a new cookie either for a user with no cookies or one
  * where the user used a cookie to authenticate.
  *
  * @param   array  $options  Array holding options
  *
  * @return  boolean  True on success
  *
  * @since   3.2
  */
 public function onUserAfterLogin($options)
 {
     // No remember me for admin
     if ($this->app->isAdmin()) {
         return false;
     }
     if (isset($options['responseType']) && $options['responseType'] == 'Cookie') {
         // Logged in using a cookie
         $cookieName = JUserHelper::getShortHashedUserAgent();
         // We need the old data to get the existing series
         $cookieValue = $this->app->input->cookie->get($cookieName);
         $cookieArray = explode('.', $cookieValue);
         // Filter series since we're going to use it in the query
         $filter = new JFilterInput();
         $series = $filter->clean($cookieArray[1], 'ALNUM');
     } elseif (!empty($options['remember'])) {
         // Remember checkbox is set
         $cookieName = JUserHelper::getShortHashedUserAgent();
         // Create an unique series which will be used over the lifespan of the cookie
         $unique = false;
         do {
             $series = JUserHelper::genRandomPassword(20);
             $query = $this->db->getQuery(true)->select($this->db->quoteName('series'))->from($this->db->quoteName('#__user_keys'))->where($this->db->quoteName('series') . ' = ' . $this->db->quote($series));
             $results = $this->db->setQuery($query)->loadResult();
             if (is_null($results)) {
                 $unique = true;
             }
         } while ($unique === false);
     } else {
         return false;
     }
     // Get the parameter values
     $lifetime = $this->params->get('cookie_lifetime', '60') * 24 * 60 * 60;
     $length = $this->params->get('key_length', '16');
     // Generate new cookie
     $token = JUserHelper::genRandomPassword($length);
     $cookieValue = $token . '.' . $series;
     // Overwrite existing cookie with new value
     $this->app->input->cookie->set($cookieName, $cookieValue, time() + $lifetime, $this->app->get('cookie_path', '/'), $this->app->get('cookie_domain'), $this->app->isSSLConnection());
     $query = $this->db->getQuery(true);
     if (!empty($options['remember'])) {
         // Create new record
         $query->insert($this->db->quoteName('#__user_keys'))->set($this->db->quoteName('user_id') . ' = ' . $this->db->quote($options['user']->username))->set($this->db->quoteName('series') . ' = ' . $this->db->quote($series))->set($this->db->quoteName('uastring') . ' = ' . $this->db->quote($cookieName))->set($this->db->quoteName('time') . ' = ' . (time() + $lifetime));
     } else {
         // Update existing record with new token
         $query->update($this->db->quoteName('#__user_keys'))->where($this->db->quoteName('user_id') . ' = ' . $this->db->quote($options['user']->username))->where($this->db->quoteName('series') . ' = ' . $this->db->quote($series))->where($this->db->quoteName('uastring') . ' = ' . $this->db->quote($cookieName));
     }
     $hashed_token = JUserHelper::hashPassword($token);
     $query->set($this->db->quoteName('token') . ' = ' . $this->db->quote($hashed_token));
     $this->db->setQuery($query)->execute();
     return true;
 }
예제 #7
0
파일: cookie.php 프로젝트: adjaika/J3Base
 /**
  * We set the authentication cookie only after login is successfullly finished.
  * We set a new cookie either for a user with no cookies or one
  * where the user used a cookie to authenticate.
  *
  * @param   array  $options  Array holding options
  *
  * @return  boolean  True on success
  *
  * @since   3.2
  */
 public function onUserAfterLogin($options)
 {
     // No remember me for admin
     if ($this->app->isAdmin()) {
         return false;
     }
     if (isset($options['responseType']) && $options['responseType'] == 'Cookie') {
         // Logged in using a cookie
         $cookieName = 'joomla_remember_me_' . JUserHelper::getShortHashedUserAgent();
         // We need the old data to get the existing series
         $cookieValue = $this->app->input->cookie->get($cookieName);
         // Try with old cookieName (pre 3.6.0) if not found
         if (!$cookieValue) {
             $oldCookieName = JUserHelper::getShortHashedUserAgent();
             $cookieValue = $this->app->input->cookie->get($oldCookieName);
             // Destroy the old cookie in the browser
             $this->app->input->cookie->set($oldCookieName, false, time() - 42000, $this->app->get('cookie_path', '/'), $this->app->get('cookie_domain'));
         }
         $cookieArray = explode('.', $cookieValue);
         // Filter series since we're going to use it in the query
         $filter = new JFilterInput();
         $series = $filter->clean($cookieArray[1], 'ALNUM');
     } elseif (!empty($options['remember'])) {
         // Remember checkbox is set
         $cookieName = 'joomla_remember_me_' . JUserHelper::getShortHashedUserAgent();
         // Create a unique series which will be used over the lifespan of the cookie
         $unique = false;
         $errorCount = 0;
         do {
             $series = JUserHelper::genRandomPassword(20);
             $query = $this->db->getQuery(true)->select($this->db->quoteName('series'))->from($this->db->quoteName('#__user_keys'))->where($this->db->quoteName('series') . ' = ' . $this->db->quote($series));
             try {
                 $results = $this->db->setQuery($query)->loadResult();
                 if (is_null($results)) {
                     $unique = true;
                 }
             } catch (RuntimeException $e) {
                 $errorCount++;
                 // We'll let this query fail up to 5 times before giving up, there's probably a bigger issue at this point
                 if ($errorCount == 5) {
                     return false;
                 }
             }
         } while ($unique === false);
     } else {
         return false;
     }
     // Get the parameter values
     $lifetime = $this->params->get('cookie_lifetime', '60') * 24 * 60 * 60;
     $length = $this->params->get('key_length', '16');
     // Generate new cookie
     $token = JUserHelper::genRandomPassword($length);
     $cookieValue = $token . '.' . $series;
     // Overwrite existing cookie with new value
     $this->app->input->cookie->set($cookieName, $cookieValue, time() + $lifetime, $this->app->get('cookie_path', '/'), $this->app->get('cookie_domain'), $this->app->isSSLConnection());
     $query = $this->db->getQuery(true);
     if (!empty($options['remember'])) {
         // Create new record
         $query->insert($this->db->quoteName('#__user_keys'))->set($this->db->quoteName('user_id') . ' = ' . $this->db->quote($options['user']->username))->set($this->db->quoteName('series') . ' = ' . $this->db->quote($series))->set($this->db->quoteName('uastring') . ' = ' . $this->db->quote($cookieName))->set($this->db->quoteName('time') . ' = ' . (time() + $lifetime));
     } else {
         // Update existing record with new token
         $query->update($this->db->quoteName('#__user_keys'))->where($this->db->quoteName('user_id') . ' = ' . $this->db->quote($options['user']->username))->where($this->db->quoteName('series') . ' = ' . $this->db->quote($series))->where($this->db->quoteName('uastring') . ' = ' . $this->db->quote($cookieName));
     }
     $hashed_token = JUserHelper::hashPassword($token);
     $query->set($this->db->quoteName('token') . ' = ' . $this->db->quote($hashed_token));
     try {
         $this->db->setQuery($query)->execute();
     } catch (RuntimeException $e) {
         return false;
     }
     return true;
 }
예제 #8
0
 /**
  * Method to bind an associative array of data to a user object
  *
  * @param   array  &$array  The associative array to bind to the object
  *
  * @return  boolean  True on success
  *
  * @since   11.1
  */
 public function bind(&$array)
 {
     // Let's check to see if the user is new or not
     if (empty($this->id)) {
         // Check the password and create the crypted password
         if (empty($array['password'])) {
             $array['password'] = JUserHelper::genRandomPassword();
             $array['password2'] = $array['password'];
         }
         // Not all controllers check the password, although they should.
         // Hence this code is required:
         if (isset($array['password2']) && $array['password'] != $array['password2']) {
             JFactory::getApplication()->enqueueMessage(JText::_('JLIB_USER_ERROR_PASSWORD_NOT_MATCH'), 'error');
             return false;
         }
         $this->password_clear = JArrayHelper::getValue($array, 'password', '', 'string');
         $array['password'] = JUserHelper::hashPassword($array['password']);
         // Set the registration timestamp
         $this->set('registerDate', JFactory::getDate()->toSql());
         // Check that username is not greater than 150 characters
         $username = $this->get('username');
         if (strlen($username) > 150) {
             $username = substr($username, 0, 150);
             $this->set('username', $username);
         }
     } else {
         // Updating an existing user
         if (!empty($array['password'])) {
             if ($array['password'] != $array['password2']) {
                 $this->setError(JText::_('JLIB_USER_ERROR_PASSWORD_NOT_MATCH'));
                 return false;
             }
             $this->password_clear = JArrayHelper::getValue($array, 'password', '', 'string');
             // Check if the user is reusing the current password if required to reset their password
             if ($this->requireReset == 1 && JUserHelper::verifyPassword($this->password_clear, $this->password)) {
                 $this->setError(JText::_('JLIB_USER_ERROR_CANNOT_REUSE_PASSWORD'));
                 return false;
             }
             $array['password'] = JUserHelper::hashPassword($array['password']);
             // Reset the change password flag
             $array['requireReset'] = 0;
         } else {
             $array['password'] = $this->password;
         }
     }
     if (array_key_exists('params', $array)) {
         $this->_params->loadArray($array['params']);
         if (is_array($array['params'])) {
             $params = (string) $this->_params;
         } else {
             $params = $array['params'];
         }
         $this->params = $params;
     }
     // Bind the array
     if (!$this->setProperties($array)) {
         $this->setError(JText::_('JLIB_USER_ERROR_BIND_ARRAY'));
         return false;
     }
     // Make sure its an integer
     $this->id = (int) $this->id;
     return true;
 }
예제 #9
0
 public function save()
 {
     // Check for request forgeries
     $mainframe = JFactory::getApplication();
     $jinput = $mainframe->input;
     JRequest::checkToken() or jexit(JText::_('COM_COMMUNITY_INVALID_TOKEN'));
     JFactory::getLanguage()->load(COM_USER_NAME);
     $user = JFactory::getUser();
     $userid = $jinput->post->get('id', 0, 'int');
     // preform security checks
     if ($user->get('id') == 0 || $userid == 0 || $userid != $user->get('id')) {
         echo $this->blockUnregister();
         return;
     }
     $username = $user->get('username');
     //if joomla settings allow change login name
     if (JComponentHelper::getParams('com_users')->get('change_login_name')) {
         $username = $jinput->get('username');
     }
     //clean request
     $post = JRequest::get('post');
     $post['username'] = $username;
     $post['password'] = JRequest::getVar('password', '', 'post', 'string', JREQUEST_ALLOWRAW);
     $post['password2'] = JRequest::getVar('password2', '', 'post', 'string', JREQUEST_ALLOWRAW);
     //check email
     $post['email'] = $post['jsemail'];
     $email = $post['email'];
     $emailPass = $post['emailpass'];
     $modelReg = $this->getModel('register');
     //CFactory::load( 'helpers', 'validate' );
     if (!CValidateHelper::email($email)) {
         $msg = JText::sprintf('COM_COMMUNITY_INVITE_EMAIL_INVALID', $email);
         $mainframe->redirect(CRoute::_('index.php?option=com_community&view=profile&task=editDetails', false), $msg, 'error');
         return false;
     }
     if (!empty($email) && $email != $emailPass && $modelReg->isEmailExists(array('email' => $email))) {
         $msg = JText::sprintf('COM_COMMUNITY_EMAIL_EXIST', $email);
         $msg = stripslashes($msg);
         $mainframe->redirect(CRoute::_('index.php?option=com_community&view=profile&task=editDetails', false), $msg, 'error');
         return false;
     }
     // get the redirect
     $return = CRoute::_('index.php?option=com_community&view=profile&task=editDetails', false);
     // do a password safety check
     $changePassword = false;
     if (JString::strlen($post['jspassword']) || JString::strlen($post['jspassword2'])) {
         // so that "0" can be used as password e.g.
         if ($post['jspassword'] != $post['jspassword2']) {
             $msg = JText::_('PASSWORDS_DO_NOT_MATCH');
             $mainframe->redirect(CRoute::_('index.php?option=com_community&view=profile&task=editDetails', false), $msg, 'error');
             return false;
         } else {
             $changePassword = true;
             //Jooomla 3.2.0 fix. TO be remove in future
             if (version_compare(JVERSION, '3.2.0', '>=')) {
                 $salt = JUserHelper::genRandomPassword(32);
                 $crypt = JUserHelper::getCryptedPassword($post['jspassword'], $salt);
                 $password = $crypt . ':' . $salt;
             } else {
                 // Don't re-encrypt the password
                 // JUser bind has encrypted the password
                 if (class_exists(JUserHelper) && method_exists(JUserHelper, 'hashpassword')) {
                     $password = JUserHelper::hashPassword($post['jspassword']);
                 } else {
                     $password = $post['jspassword'];
                 }
             }
         }
     }
     // Handle the two factor authentication setup
     $data = $post['jform'];
     if (array_key_exists('twofactor', $data)) {
         if (!class_exists('UsersModelUser')) {
             require JPATH_ROOT . '/administrator/components/com_users/models/user.php';
         }
         $model = new UsersModelUser();
         $twoFactorMethod = $data['twofactor']['method'];
         $userId = CFactory::getUser()->id;
         // Get the current One Time Password (two factor auth) configuration
         $otpConfig = $model->getOtpConfig($userId);
         if ($twoFactorMethod != 'none') {
             // Run the plugins
             FOFPlatform::getInstance()->importPlugin('twofactorauth');
             $otpConfigReplies = FOFPlatform::getInstance()->runPlugins('onUserTwofactorApplyConfiguration', array($twoFactorMethod));
             // Look for a valid reply
             foreach ($otpConfigReplies as $reply) {
                 if (!is_object($reply) || empty($reply->method) || $reply->method != $twoFactorMethod) {
                     continue;
                 }
                 $otpConfig->method = $reply->method;
                 $otpConfig->config = $reply->config;
                 break;
             }
             // Save OTP configuration.
             $model->setOtpConfig($userId, $otpConfig);
             // Generate one time emergency passwords if required (depleted or not set)
             if (empty($otpConfig->otep)) {
                 $oteps = $model->generateOteps($userId);
             }
         } else {
             $otpConfig->method = 'none';
             $otpConfig->config = array();
             $model->setOtpConfig($userId, $otpConfig);
         }
         // Unset the raw data
         unset($data['twofactor']);
     }
     // we don't want users to edit certain fields so we will unset them
     unset($post['gid']);
     unset($post['block']);
     unset($post['usertype']);
     unset($post['registerDate']);
     unset($post['activation']);
     //update CUser param 1st so that the new value will not be replace wif the old one.
     $my = CFactory::getUser();
     $params = $my->getParams();
     $postvars = $post['daylightsavingoffset'];
     $params->set('daylightsavingoffset', $postvars);
     // Store FB prefernce o ly FB connect data
     $connectModel = CFactory::getModel('Connect');
     if ($connectModel->isAssociated($user->id)) {
         $postvars = !empty($post['postFacebookStatus']) ? 1 : 0;
         $my->_cparams->set('postFacebookStatus', $postvars);
     }
     if ($changePassword) {
         $my->set('password', $password);
     }
     /* Save for CUser */
     $my->save();
     $model = CFactory::getModel('profile');
     $editSuccess = true;
     $msg = JText::_('COM_COMMUNITY_SETTINGS_SAVED');
     $jUser = JFactory::getUser();
     // Bind the form fields to the user table
     if (!$jUser->bind($post)) {
         $msg = $jUser->getError();
         $editSuccess = false;
     }
     // Store the web link table to the database
     if (!$jUser->save()) {
         $msg = $jUser->getError();
         $editSuccess = false;
     }
     if ($editSuccess) {
         /* Update Joomla! User session */
         $session = JFactory::getSession();
         $session->set('user', $jUser);
         // User with FB Connect, store post preference
         //execute the trigger
         $appsLib = CAppPlugins::getInstance();
         $appsLib->loadApplications();
         $userRow = array();
         $userRow[] = $jUser;
         $appsLib->triggerEvent('onUserDetailsUpdate', $userRow);
     }
     $mainframe->redirect(CRoute::_('index.php?option=com_community&view=profile&task=edit', false), $msg);
 }
예제 #10
0
파일: connect.php 프로젝트: Jougito/DynWeb
 /**
  * Ajax method to update user's authentication via Facebook
  * */
 public function ajaxUpdate()
 {
     $response = new JAXResponse();
     $json = array();
     $config = CFactory::getConfig();
     $mainframe = JFactory::getApplication();
     $connectTable = JTable::getInstance('Connect', 'CTable');
     $userId = $this->_getFacebookUID();
     if (!$userId) {
         $json['title'] = JText::_('COM_COMMUNITY_ERROR');
         $json['error'] = JText::_('COM_COMMUNITY_FBCONNECT_LOGIN_DETECT_ERROR');
         die(json_encode($json));
     }
     $connectTable->load($userId);
     $userInfo = $this->_getFacebookUser();
     $redirect = CRoute::_('index.php?option=com_community&view=' . $config->get('redirect_login'), false);
     $error = false;
     $content = '';
     if (!$connectTable->userid) {
         $tmpl = new CTemplate();
         $tmpl->set('userInfo', $userInfo);
         $json['title'] = JText::_('COM_COMMUNITY_ACCOUNT_SIGNUP_FROM_FACEBOOK');
         $json['html'] = $tmpl->fetch('facebook.firstlogin');
         $json['btnNext'] = JText::_('COM_COMMUNITY_NEXT');
         die(json_encode($json));
     } else {
         $my = CFactory::getUser($connectTable->userid);
         if (COwnerHelper::isCommunityAdmin($connectTable->userid)) {
             $tmpl = new CTemplate();
             $json['title'] = JText::_('COM_COMMUNITY_ERROR');
             $json['html'] = $tmpl->fetch('facebook.link.notallowed');
             die(json_encode($json));
         }
         // Generate a joomla password format for the user so we can log them in.
         $password = JUserHelper::genRandomPassword();
         $userData = array();
         $userData['password'] = $password;
         $userData['password'] = $password;
         $userData['password2'] = $password;
         $my->set('password', JUserHelper::hashPassword($password));
         $options = array();
         $options['remember'] = true;
         //$options['return']   = $data['return'];
         // Get the log in credentials.
         $credentials = array();
         $credentials['username'] = $my->username;
         $credentials['password'] = $password;
         //$credentials['secretkey'] = $data['secretkey'];
         JFactory::getApplication()->login($credentials, $options);
         // User object must be saved again so the password change get's reflected.
         $my->save();
         JFactory::getApplication()->login($credentials, $options);
         $mainframe->login(array('username' => $my->username, 'password' => $password));
         if ($config->get('fbloginimportprofile')) {
             $this->_facebook->mapProfile($userInfo, $my->id);
         }
         // Update page token since the userid is changed now.
         $session = JFactory::getSession();
         $token = $session->getFormToken(false);
         $tmpl = new CTemplate();
         $tmpl->set('my', $my);
         $tmpl->set('userInfo', $userInfo);
         $json = array('title' => $config->get('sitename'), 'html' => $tmpl->fetch('facebook.existinguser'), 'btnContinue' => JText::_('COM_COMMUNITY_CONTINUE_BUTTON'), 'jax_token_var' => $token);
         die(json_encode($json));
     }
 }
예제 #11
0
파일: helper.php 프로젝트: adjaika/J3Base
 /**
  * Helper wrapper method for hashPassword
  *
  * @param   string  $password  The plaintext password to encrypt.
  *
  * @return  string  The encrypted password.
  *
  * @see     JUserHelper::hashPassword()
  * @since   3.4
  */
 public function hashPassword($password)
 {
     return JUserHelper::hashPassword($password);
 }
예제 #12
0
파일: profile.php 프로젝트: Jougito/DynWeb
 public function save()
 {
     // Check for request forgeries
     $mainframe = JFactory::getApplication();
     $jinput = $mainframe->input;
     JRequest::checkToken() or jexit(JText::_('COM_COMMUNITY_INVALID_TOKEN'));
     JFactory::getLanguage()->load(COM_USER_NAME);
     $user = JFactory::getUser();
     $userid = $jinput->post->get('id', 0, 'int');
     // preform security checks
     if ($user->get('id') == 0 || $userid == 0 || $userid != $user->get('id')) {
         echo $this->blockUnregister();
         return;
     }
     $username = $user->get('username');
     //clean request
     $post = JRequest::get('post');
     $post['username'] = $username;
     $post['password'] = JRequest::getVar('password', '', 'post', 'string', JREQUEST_ALLOWRAW);
     $post['password2'] = JRequest::getVar('password2', '', 'post', 'string', JREQUEST_ALLOWRAW);
     //check email
     $post['email'] = $post['jsemail'];
     $email = $post['email'];
     $emailPass = $post['emailpass'];
     $modelReg = $this->getModel('register');
     //CFactory::load( 'helpers', 'validate' );
     if (!CValidateHelper::email($email)) {
         $msg = JText::sprintf('COM_COMMUNITY_INVITE_EMAIL_INVALID', $email);
         $mainframe->redirect(CRoute::_('index.php?option=com_community&view=profile&task=editDetails', false), $msg, 'error');
         return false;
     }
     if (!empty($email) && $email != $emailPass && $modelReg->isEmailExists(array('email' => $email))) {
         $msg = JText::sprintf('COM_COMMUNITY_EMAIL_EXIST', $email);
         $msg = stripslashes($msg);
         $mainframe->redirect(CRoute::_('index.php?option=com_community&view=profile&task=editDetails', false), $msg, 'error');
         return false;
     }
     // get the redirect
     $return = CRoute::_('index.php?option=com_community&view=profile&task=editDetails', false);
     // do a password safety check
     $changePassword = false;
     if (JString::strlen($post['jspassword']) || JString::strlen($post['jspassword2'])) {
         // so that "0" can be used as password e.g.
         if ($post['jspassword'] != $post['jspassword2']) {
             $msg = JText::_('PASSWORDS_DO_NOT_MATCH');
             $mainframe->redirect(CRoute::_('index.php?option=com_community&view=profile&task=editDetails', false), $msg, 'error');
             return false;
         } else {
             $changePassword = true;
             //Jooomla 3.2.0 fix. TO be remove in future
             if (version_compare(JVERSION, '3.2.0', '>=')) {
                 $salt = JUserHelper::genRandomPassword(32);
                 $crypt = JUserHelper::getCryptedPassword($post['jspassword'], $salt);
                 $password = $crypt . ':' . $salt;
             } else {
                 // Don't re-encrypt the password
                 // JUser bind has encrypted the password
                 if (class_exists(JUserHelper) && method_exists(JUserHelper, 'hashpassword')) {
                     $password = JUserHelper::hashPassword($post['jspassword']);
                 } else {
                     $password = $post['jspassword'];
                 }
             }
         }
     }
     // we don't want users to edit certain fields so we will unset them
     unset($post['gid']);
     unset($post['block']);
     unset($post['usertype']);
     unset($post['registerDate']);
     unset($post['activation']);
     //update CUser param 1st so that the new value will not be replace wif the old one.
     $my = CFactory::getUser();
     $params = $my->getParams();
     $postvars = $post['daylightsavingoffset'];
     $params->set('daylightsavingoffset', $postvars);
     // Store FB prefernce o ly FB connect data
     $connectModel = CFactory::getModel('Connect');
     if ($connectModel->isAssociated($user->id)) {
         $postvars = !empty($post['postFacebookStatus']) ? 1 : 0;
         $my->_cparams->set('postFacebookStatus', $postvars);
     }
     if ($changePassword) {
         $my->set('password', $password);
     }
     /* Save for CUser */
     $my->save();
     $model = CFactory::getModel('profile');
     $editSuccess = true;
     $msg = JText::_('COM_COMMUNITY_SETTINGS_SAVED');
     $jUser = JFactory::getUser();
     // Bind the form fields to the user table
     if (!$jUser->bind($post)) {
         $msg = $jUser->getError();
         $editSuccess = false;
     }
     // Store the web link table to the database
     if (!$jUser->save()) {
         $msg = $jUser->getError();
         $editSuccess = false;
     }
     if ($editSuccess) {
         /* Update Joomla! User session */
         $session = JFactory::getSession();
         $session->set('user', $jUser);
         // User with FB Connect, store post preference
         //execute the trigger
         $appsLib = CAppPlugins::getInstance();
         $appsLib->loadApplications();
         $userRow = array();
         $userRow[] = $jUser;
         $appsLib->triggerEvent('onUserDetailsUpdate', $userRow);
     }
     $mainframe->redirect(CRoute::_('index.php?option=com_community&view=profile&task=edit', false), $msg);
 }
예제 #13
0
 /**
  * This method should handle any authentication and report back to the subject
  *
  * @param   array   $credentials  Array holding the user credentials
  * @param   array   $options      Array of extra options
  * @param   object  &$response    Authentication response object
  *
  * @return  void
  *
  * @since   1.5
  */
 public function onUserAuthenticate($credentials, $options, &$response)
 {
     $response->type = 'Joomla';
     // Joomla does not like blank passwords
     if (empty($credentials['password'])) {
         $response->status = JAuthentication::STATUS_FAILURE;
         $response->error_message = JText::_('JGLOBAL_AUTH_EMPTY_PASS_NOT_ALLOWED');
         return;
     }
     // Get a database object
     $db = JFactory::getDbo();
     $query = $db->getQuery(true)->select('id, password')->from('#__users')->where('username='******'username']));
     $db->setQuery($query);
     $result = $db->loadObject();
     if ($result) {
         $match = JUserHelper::verifyPassword($credentials['password'], $result->password, $result->id);
         if ($match === true) {
             // Bring this in line with the rest of the system
             $user = JUser::getInstance($result->id);
             $response->email = $user->email;
             $response->fullname = $user->name;
             if (JFactory::getApplication()->isAdmin()) {
                 $response->language = $user->getParam('admin_language');
             } else {
                 $response->language = $user->getParam('language');
             }
             $response->status = JAuthentication::STATUS_SUCCESS;
             $response->error_message = '';
         } else {
             // Invalid password
             $response->status = JAuthentication::STATUS_FAILURE;
             $response->error_message = JText::_('JGLOBAL_AUTH_INVALID_PASS');
         }
     } else {
         // Let's hash the entered password even if we don't have a matching user for some extra response time
         // By doing so, we mitigate side channel user enumeration attacks
         JUserHelper::hashPassword($credentials['password']);
         // Invalid user
         $response->status = JAuthentication::STATUS_FAILURE;
         $response->error_message = JText::_('JGLOBAL_AUTH_NO_USER');
     }
     // Check the two factor authentication
     if ($response->status == JAuthentication::STATUS_SUCCESS) {
         $methods = JAuthenticationHelper::getTwoFactorMethods();
         if (count($methods) <= 1) {
             // No two factor authentication method is enabled
             return;
         }
         JModelLegacy::addIncludePath(JPATH_ADMINISTRATOR . '/components/com_users/models', 'UsersModel');
         /** @var UsersModelUser $model */
         $model = JModelLegacy::getInstance('User', 'UsersModel', array('ignore_request' => true));
         // Load the user's OTP (one time password, a.k.a. two factor auth) configuration
         if (!array_key_exists('otp_config', $options)) {
             $otpConfig = $model->getOtpConfig($result->id);
             $options['otp_config'] = $otpConfig;
         } else {
             $otpConfig = $options['otp_config'];
         }
         // Check if the user has enabled two factor authentication
         if (empty($otpConfig->method) || $otpConfig->method == 'none') {
             // Warn the user if they are using a secret code but they have not
             // enabed two factor auth in their account.
             if (!empty($credentials['secretkey'])) {
                 try {
                     $app = JFactory::getApplication();
                     $this->loadLanguage();
                     $app->enqueueMessage(JText::_('PLG_AUTH_JOOMLA_ERR_SECRET_CODE_WITHOUT_TFA'), 'warning');
                 } catch (Exception $exc) {
                     // This happens when we are in CLI mode. In this case
                     // no warning is issued
                     return;
                 }
             }
             return;
         }
         // Try to validate the OTP
         FOFPlatform::getInstance()->importPlugin('twofactorauth');
         $otpAuthReplies = FOFPlatform::getInstance()->runPlugins('onUserTwofactorAuthenticate', array($credentials, $options));
         $check = false;
         /*
          * This looks like noob code but DO NOT TOUCH IT and do not convert
          * to in_array(). During testing in_array() inexplicably returned
          * null when the OTEP begins with a zero! o_O
          */
         if (!empty($otpAuthReplies)) {
             foreach ($otpAuthReplies as $authReply) {
                 $check = $check || $authReply;
             }
         }
         // Fall back to one time emergency passwords
         if (!$check) {
             // Did the user use an OTEP instead?
             if (empty($otpConfig->otep)) {
                 if (empty($otpConfig->method) || $otpConfig->method == 'none') {
                     // Two factor authentication is not enabled on this account.
                     // Any string is assumed to be a valid OTEP.
                     return;
                 } else {
                     /*
                      * Two factor authentication enabled and no OTEPs defined. The
                      * user has used them all up. Therefore anything they enter is
                      * an invalid OTEP.
                      */
                     return;
                 }
             }
             // Clean up the OTEP (remove dashes, spaces and other funny stuff
             // our beloved users may have unwittingly stuffed in it)
             $otep = $credentials['secretkey'];
             $otep = filter_var($otep, FILTER_SANITIZE_NUMBER_INT);
             $otep = str_replace('-', '', $otep);
             $check = false;
             // Did we find a valid OTEP?
             if (in_array($otep, $otpConfig->otep)) {
                 // Remove the OTEP from the array
                 $otpConfig->otep = array_diff($otpConfig->otep, array($otep));
                 $model->setOtpConfig($result->id, $otpConfig);
                 // Return true; the OTEP was a valid one
                 $check = true;
             }
         }
         if (!$check) {
             $response->status = JAuthentication::STATUS_FAILURE;
             $response->error_message = JText::_('JGLOBAL_AUTH_INVALID_SECRETKEY');
         }
     }
 }
예제 #14
0
 function _createRootUser($options)
 {
     // Get a database object.
     try {
         $db = JInstallationHelperDatabase::getDBO($options->db_type, $options->db_host, $options->db_user, $options->db_pass, $options->db_name, $options->db_prefix);
     } catch (RuntimeException $e) {
         $this->setError(JText::sprintf('INSTL_ERROR_CONNECT_DB', $e->getMessage()));
     }
     // Create random salt/password for the admin user
     $cryptpass = JUserHelper::hashPassword($options->admin_password);
     // take the admin user id
     JLoader::register('JInstallationModelDatabase', JPATH_INSTALLATION . '/models/database.php');
     $userId = JInstallationModelDatabase::getUserId();
     //we don't need anymore the randUserId in the session, let's remove it
     JInstallationModelDatabase::resetRandUserId();
     // create the admin user
     date_default_timezone_set('UTC');
     $installdate = date('Y-m-d H:i:s');
     $nullDate = $db->getNullDate();
     //sqlsrv change
     $query = $db->getQuery(true);
     $query->select('id');
     $query->from('#__users');
     $query->where('id = ' . $db->quote($userId));
     $db->setQuery($query);
     if ($db->loadResult()) {
         $query = $db->getQuery(true);
         $query->update('#__users');
         $query->set('name = ' . $db->quote('Super User'));
         $query->set('username = '******'email = ' . $db->quote($options->admin_email));
         $query->set('password = '******'usertype = ' . $db->quote('deprecated'));
         $query->set('block = 0');
         $query->set('sendEmail = 1');
         $query->set('registerDate = ' . $db->quote($installdate));
         $query->set('lastvisitDate = ' . $db->quote($nullDate));
         $query->set('activation = ' . $db->quote('0'));
         $query->set('params = ' . $db->quote(''));
         $query->where('id = ' . $db->quote($userId));
     } else {
         $query = $db->getQuery(true);
         $columns = array($db->quoteName('id'), $db->quoteName('name'), $db->quoteName('username'), $db->quoteName('email'), $db->quoteName('password'), $db->quoteName('usertype'), $db->quoteName('block'), $db->quoteName('sendEmail'), $db->quoteName('registerDate'), $db->quoteName('lastvisitDate'), $db->quoteName('activation'), $db->quoteName('params'));
         $query->insert('#__users', true);
         $query->columns($columns);
         $query->values($db->quote($userId) . ', ' . $db->quote('Super User') . ', ' . $db->quote(trim($options->admin_user)) . ', ' . $db->quote($options->admin_email) . ', ' . $db->quote($cryptpass) . ', ' . $db->quote('deprecated') . ', ' . $db->quote('0') . ', ' . $db->quote('1') . ', ' . $db->quote($installdate) . ', ' . $db->quote($nullDate) . ', ' . $db->quote('0') . ', ' . $db->quote(''));
     }
     $db->setQuery($query);
     try {
         $db->execute();
     } catch (RuntimeException $e) {
         $this->setError($e->getMessage());
         return false;
     }
     // Map the super admin to the Super Admin Group
     $query = $db->getQuery(true);
     $query->select('user_id');
     $query->from('#__user_usergroup_map');
     $query->where('user_id = ' . $db->quote($userId));
     $db->setQuery($query);
     if ($db->loadResult()) {
         $query = $db->getQuery(true);
         $query->update('#__user_usergroup_map');
         $query->set('user_id = ' . $db->quote($userId));
         $query->set('group_id = 8');
     } else {
         $query = $db->getQuery(true);
         $query->insert('#__user_usergroup_map', false);
         $query->columns(array($db->quoteName('user_id'), $db->quoteName('group_id')));
         $query->values($userId . ', ' . '8');
     }
     $db->setQuery($query);
     try {
         $db->execute();
     } catch (RuntimeException $e) {
         $this->setError($e->getMessage());
         return false;
     }
     return true;
 }
예제 #15
0
파일: api.php 프로젝트: naka211/befirstapp
 public function forgot_password()
 {
     $email = JRequest::getVar("email");
     $new_pass = $this->_generateRandomString();
     $app = JFactory::getApplication();
     $mailfrom = $app->get('mailfrom');
     $fromname = $app->get('fromname');
     $sitename = $app->get('sitename');
     $body = "Hi user, \r\n\r\n This is your new password: "******" \r\n\r\n Be First App";
     $mail = JFactory::getMailer();
     $mail->addRecipient($email);
     $mail->setSender(array($mailfrom, $fromname));
     $mail->setSubject($sitename . ': New password');
     $mail->setBody($body);
     $sent = $mail->Send();
     if ($sent) {
         jimport('joomla.user.helper');
         $db = JFactory::getDBO();
         $pass = JUserHelper::hashPassword($new_pass);
         $db->setQuery("UPDATE #__users SET password = '******' WHERE email = '" . $email . "'");
         if ($db->query()) {
             $result = array("result" => 1);
         } else {
             $data["result"] = 0;
             $data["error"] = "Can not update new password";
         }
     } else {
         $data["result"] = 0;
         $data["error"] = "Can not send email";
     }
     die(json_encode($result));
 }
예제 #16
0
 /**
  * Method to create the root user for the site.
  *
  * @param   object  $options  The session options.
  *
  * @return  boolean  True on success.
  *
  * @since   3.1
  */
 private function _createRootUser($options)
 {
     // Get the application
     /* @var InstallationApplicationWeb $app */
     $app = JFactory::getApplication();
     // Get a database object.
     try {
         $db = InstallationHelperDatabase::getDbo($options->db_type, $options->db_host, $options->db_user, $options->db_pass, $options->db_name, $options->db_prefix);
     } catch (RuntimeException $e) {
         $app->enqueueMessage(JText::sprintf('INSTL_ERROR_CONNECT_DB', $e->getMessage()), 'notice');
         return false;
     }
     $cryptpass = JUserHelper::hashPassword($options->admin_password);
     // Take the admin user id.
     $userId = InstallationModelDatabase::getUserId();
     // We don't need the randUserId in the session any longer, let's remove it.
     InstallationModelDatabase::resetRandUserId();
     // Create the admin user.
     date_default_timezone_set('UTC');
     $installdate = date('Y-m-d H:i:s');
     $nullDate = $db->getNullDate();
     // Sqlsrv change.
     $query = $db->getQuery(true)->select($db->quoteName('id'))->from($db->quoteName('#__users'))->where($db->quoteName('id') . ' = ' . $db->quote($userId));
     $db->setQuery($query);
     if ($db->loadResult()) {
         $query->clear()->update($db->quoteName('#__users'))->set($db->quoteName('name') . ' = ' . $db->quote('Super User'))->set($db->quoteName('username') . ' = ' . $db->quote(trim($options->admin_user)))->set($db->quoteName('email') . ' = ' . $db->quote($options->admin_email))->set($db->quoteName('password') . ' = ' . $db->quote($cryptpass))->set($db->quoteName('block') . ' = 0')->set($db->quoteName('sendEmail') . ' = 1')->set($db->quoteName('registerDate') . ' = ' . $db->quote($installdate))->set($db->quoteName('lastvisitDate') . ' = ' . $db->quote($nullDate))->set($db->quoteName('activation') . ' = ' . $db->quote('0'))->set($db->quoteName('params') . ' = ' . $db->quote(''))->where($db->quoteName('id') . ' = ' . $db->quote($userId));
     } else {
         $columns = array($db->quoteName('id'), $db->quoteName('name'), $db->quoteName('username'), $db->quoteName('email'), $db->quoteName('password'), $db->quoteName('block'), $db->quoteName('sendEmail'), $db->quoteName('registerDate'), $db->quoteName('lastvisitDate'), $db->quoteName('activation'), $db->quoteName('params'));
         $query->clear()->insert('#__users', true)->columns($columns)->values($db->quote($userId) . ', ' . $db->quote('Super User') . ', ' . $db->quote(trim($options->admin_user)) . ', ' . $db->quote($options->admin_email) . ', ' . $db->quote($cryptpass) . ', ' . $db->quote('0') . ', ' . $db->quote('1') . ', ' . $db->quote($installdate) . ', ' . $db->quote($nullDate) . ', ' . $db->quote('0') . ', ' . $db->quote(''));
     }
     $db->setQuery($query);
     try {
         $db->execute();
     } catch (RuntimeException $e) {
         $app->enqueueMessage($e->getMessage(), 'notice');
         return false;
     }
     // Map the super admin to the Super Admin Group
     $query->clear()->select($db->quoteName('user_id'))->from($db->quoteName('#__user_usergroup_map'))->where($db->quoteName('user_id') . ' = ' . $db->quote($userId));
     $db->setQuery($query);
     if ($db->loadResult()) {
         $query->clear()->update($db->quoteName('#__user_usergroup_map'))->set($db->quoteName('user_id') . ' = ' . $db->quote($userId))->set($db->quoteName('group_id') . ' = 8');
     } else {
         $query->clear()->insert($db->quoteName('#__user_usergroup_map'), false)->columns(array($db->quoteName('user_id'), $db->quoteName('group_id')))->values($db->quote($userId) . ', 8');
     }
     $db->setQuery($query);
     try {
         $db->execute();
     } catch (RuntimeException $e) {
         $app->enqueueMessage($e->getMessage(), 'notice');
         return false;
     }
     return true;
 }
예제 #17
0
 /**
  * Testing hashPassword().
  *
  * @covers  JUserHelper::hashPassword
  * @return  void
  *
  * @since   3.2
  */
 public function testHashPassword()
 {
     $this->assertEquals(strpos(JUserHelper::hashPassword('mySuperSecretPassword'), '$P$'), 0, 'Joomla currently hashes passwords using PHPass, verify the correct prefix is present');
 }
예제 #18
0
 function autoCreateUser($providerUserId, $provider)
 {
     $provider->setInitialRegistration();
     $profile = $provider->profile->fetchProfile($providerUserId, array('first_name', 'last_name', 'email', 'full_name'));
     if ($profile == null || $profile->get('email') == null) {
         # not enough information returned to auto-create account
         return false;
     }
     $newEmail = $profile->get('email');
     $fullname = $profile->get('full_name');
     $user['fullname'] = $fullname;
     $user['email'] = $newEmail;
     // Create random password for FB User Only, but save so we can email to the user on account creation
     if (JFBCFactory::config()->getSetting('generate_random_password')) {
         $this->_newUserPassword = JUserHelper::genRandomPassword();
         $user['password_clear'] = $this->_newUserPassword;
         // Check for Joomla 3.2.1's new hashPassword functions and use those, if exist
         if (method_exists('JUserHelper', 'hashPassword')) {
             $user['password'] = JUserHelper::hashPassword($this->_newUserPassword);
         } else {
             $salt = JUserHelper::genRandomPassword(32);
             $crypt = JUserHelper::getCryptedPassword($this->_newUserPassword, $salt);
             $user['password'] = $crypt . ':' . $salt;
         }
     } else {
         $user['password_clear'] = "";
         $this->_newUserPassword = '';
     }
     $lang = JRequest::getVar(JApplication::getHash('language'), '', 'COOKIE');
     $user['language'] = $lang;
     $usernamePrefixFormat = JFBCFactory::config()->getSetting('auto_username_format');
     $username = SCUserUtilities::getAutoUsername($profile->get('first_name'), $profile->get('last_name'), $profile->get('email'), $provider->usernamePrefix, $providerUserId, $usernamePrefixFormat);
     $user['username'] = $username;
     $useractivation = $this->getActivationMode();
     $jUser = $this->getBlankUser($user, $useractivation);
     if ($jUser && $jUser->get('id', null)) {
         $this->onAfterRegister($provider, $jUser);
         SCSocialUtilities::clearJFBCNewMappingEnabled();
         if (JFBCFactory::usermap()->map($jUser->get('id'), $providerUserId, $provider->systemName, $provider->client->getToken())) {
             JFBCFactory::log(JText::sprintf('COM_JFBCONNECT_MAP_USER_SUCCESS', $provider->name));
             return true;
         } else {
             JFBCFactory::log(JText::sprintf('COM_JFBCONNECT_MAP_USER_FAIL', $provider->name));
         }
     }
     return false;
     // User creation failed for some reason
 }
예제 #19
0
 /**
  * Save the new password after reset is done
  *
  * @param   array  $data  The data expected for the form.
  *
  * @return  mixed  Exception | JException | boolean
  *
  * @since   1.6
  */
 public function processResetComplete($data)
 {
     // Get the form.
     $form = $this->getResetCompleteForm();
     $data['email'] = JStringPunycode::emailToPunycode($data['email']);
     // Check for an error.
     if ($form instanceof Exception) {
         return $form;
     }
     // Filter and validate the form data.
     $data = $form->filter($data);
     $return = $form->validate($data);
     // Check for an error.
     if ($return instanceof Exception) {
         return $return;
     }
     // Check the validation results.
     if ($return === false) {
         // Get the validation messages from the form.
         foreach ($form->getErrors() as $formError) {
             $this->setError($formError->getMessage());
         }
         return false;
     }
     // Get the token and user id from the confirmation process.
     $app = JFactory::getApplication();
     $token = $app->getUserState('com_users.reset.token', null);
     $userId = $app->getUserState('com_users.reset.user', null);
     // Check the token and user id.
     if (empty($token) || empty($userId)) {
         return new JException(JText::_('COM_USERS_RESET_COMPLETE_TOKENS_MISSING'), 403);
     }
     // Get the user object.
     $user = JUser::getInstance($userId);
     // Check for a user and that the tokens match.
     if (empty($user) || $user->activation !== $token) {
         $this->setError(JText::_('COM_USERS_USER_NOT_FOUND'));
         return false;
     }
     // Make sure the user isn't blocked.
     if ($user->block) {
         $this->setError(JText::_('COM_USERS_USER_BLOCKED'));
         return false;
     }
     // Check if the user is reusing the current password if required to reset their password
     if ($user->requireReset == 1 && JUserHelper::verifyPassword($data['password1'], $user->password)) {
         $this->setError(JText::_('JLIB_USER_ERROR_CANNOT_REUSE_PASSWORD'));
         return false;
     }
     // Update the user object.
     $user->password = JUserHelper::hashPassword($data['password1']);
     $user->activation = '';
     $user->password_clear = $data['password1'];
     // Save the user to the database.
     if (!$user->save(true)) {
         return new JException(JText::sprintf('COM_USERS_USER_SAVE_FAILED', $user->getError()), 500);
     }
     // Flush the user data from the session.
     $app->setUserState('com_users.reset.token', null);
     $app->setUserState('com_users.reset.user', null);
     return true;
 }
예제 #20
0
 $countOn = $countOff = 0;
 $report = '<ul class="list list-condensed">';
 foreach ($list as $obj) {
     // registra o voto e envia confirmação
     $sender = array($config->get('mailfrom'), $config->get('fromname'));
     $mailer->setSender($sender);
     $reciver = array();
     $reciver[] = $obj->email;
     if (count($users) == 1 && !empty($email_opt)) {
         $reciver[] = $email_opt;
     }
     $mailer->addRecipient($reciver);
     $mailer->setSubject('Reenvio de senha de usuário');
     $setPass = random_password();
     jimport('joomla.user.helper');
     $newPass = JUserHelper::hashPassword($setPass);
     $msg = isset($message) && $message != '' ? $message . "\n\n" : 'por questões de segurança estamos reenviando seus dados de acesso ao nosso site:';
     $msg = "\n\t\t\tOlá " . $obj->name . ",\n\n" . $msg . "\n\nUsuário:  " . $obj->username . "\nSenha:  " . $setPass . "\n\nVocê pode alterar sua senha a qualquer momento. Para isso acesse nosso website:\n" . JURI::root() . "profile\n\n Atenciosamente,\n\t\t";
     $mailer->setBody($msg);
     $query = "UPDATE #__users SET password='******' WHERE id=" . $obj->id;
     $update = $db->setQuery($query);
     $db->execute();
     if ($mailer->Send() && $update) {
         $report .= '<li class="text-success"><span class="base-icon-check"></span> A senha (<strong>' . $setPass . '</strong>) foi enviada com sucesso para o usuário ' . $obj->name . ' (' . implode(', ', $reciver) . ')</li>';
         $countOn++;
     } else {
         $report .= '<li class="bg-danger text-danger strong"><span class="base-icon-cancel"></span> A nova senha <strong>NÃO</strong> foi enviada para o usuário ' . $obj->name . ' (' . implode(', ', $reciver) . ')</li>';
         $countOff++;
     }
 }
 $report .= '</ul>';
예제 #21
0
 /**
  * Method to bind an associative array of data to a user object
  *
  * @param   array  &$array  The associative array to bind to the object
  *
  * @return  boolean  True on success
  *
  * @since   11.1
  */
 public function bind(&$array)
 {
     // Let's check to see if the user is new or not
     if (empty($this->id)) {
         // Check the password and create the crypted password
         if (empty($array['password'])) {
             $array['password'] = JUserHelper::genRandomPassword();
             $array['password2'] = $array['password'];
         }
         // TODO: Backend controller checks the password, frontend doesn't but should.
         // Hence this code is required:
         if (isset($array['password2']) && $array['password'] != $array['password2']) {
             $this->setError(JText::_('JLIB_USER_ERROR_PASSWORD_NOT_MATCH'));
             return false;
         }
         $this->password_clear = JArrayHelper::getValue($array, 'password', '', 'string');
         $array['password'] = JUserHelper::hashPassword($array['password']);
         // Set the registration timestamp
         $this->set('registerDate', JFactory::getDate()->toSql());
         // Check that username is not greater than 150 characters
         $username = $this->get('username');
         if (strlen($username) > 150) {
             $username = substr($username, 0, 150);
             $this->set('username', $username);
         }
         // Check that password is not greater than 100 characters
         $password = $this->get('password');
         if (strlen($password) > 100) {
             $password = substr($password, 0, 100);
             $this->set('password', $password);
         }
     } else {
         // Updating an existing user
         if (!empty($array['password'])) {
             if ($array['password'] != $array['password2']) {
                 $this->setError(JText::_('JLIB_USER_ERROR_PASSWORD_NOT_MATCH'));
                 return false;
             }
             $this->password_clear = JArrayHelper::getValue($array, 'password', '', 'string');
             $array['password'] = JUserHelper::hashPassword($array['password']);
         } else {
             $array['password'] = $this->password;
         }
     }
     // TODO: this will be deprecated as of the ACL implementation
     //		$db = JFactory::getDbo();
     if (array_key_exists('params', $array)) {
         $params = '';
         $this->_params->loadArray($array['params']);
         if (is_array($array['params'])) {
             $params = (string) $this->_params;
         } else {
             $params = $array['params'];
         }
         $this->params = $params;
     }
     // Bind the array
     if (!$this->setProperties($array)) {
         $this->setError(JText::_('JLIB_USER_ERROR_BIND_ARRAY'));
         return false;
     }
     // Make sure its an integer
     $this->id = (int) $this->id;
     return true;
 }
예제 #22
0
 public function save($key = null, $urlVar = NULL)
 {
     $jinput = JFactory::getApplication()->input;
     $app = JFactory::getApplication();
     $model = $this->getModel('Business', 'BusinessModel');
     // Get the user data.
     $requestData = $this->input->post->get('jform', array(), 'array');
     $icon = $this->input->post->get('jform_icon');
     $business = array();
     $workingtime = array();
     $userinfo = array();
     $business['id'] = $requestData['businessid'];
     $business['businessName'] = $requestData['businessName'];
     $business['cvrNumber'] = $requestData['cvrNumber'];
     $business['shortName'] = $requestData['shortName'];
     $business['phone'] = $requestData['phone'];
     $business['businessEmail'] = $requestData['businessEmail'];
     $business['website'] = $requestData['website'];
     $business['icon'] = $this->listNameIcon[$icon];
     $business['address'] = $requestData['address'];
     $business['postnr'] = $requestData['postnr'];
     $business['postnrBy'] = $requestData['postnrBy'];
     $business['country'] = $requestData['country'];
     $business['latitude'] = $requestData['latitude'];
     $business['longitude'] = $requestData['longitude'];
     if (isset($requestData['pointDescription']) && $requestData['pointDescription'] != "") {
         $business['pointDescription'] = $requestData['pointDescription'];
     }
     $returnPassword = TRUE;
     $userinfo['id'] = $requestData['userid'];
     $userinfo['firstName'] = $requestData['first_name'];
     $userinfo['lastName'] = $requestData['second_name'];
     $userinfo['name'] = $requestData['first_name'] . ' ' . $requestData['second_name'];
     if (isset($requestData['password']) && $requestData['password'] != "") {
         if (strlen($requestData['password']) < 4) {
             $returnPassword = FALSE;
         } else {
             $userinfo['password'] = JUserHelper::hashPassword($requestData['password']);
             $returnPassword = TRUE;
         }
     }
     foreach ($requestData as $key => $field) {
         if (strstr($key, 'fromTime_') != "") {
             $workingtime[str_replace("fromTime_", "", $key)]["fromTime"] = $field;
         } elseif (strstr($key, 'toTime_') != "") {
             $workingtime[str_replace("toTime_", "", $key)]["toTime"] = $field;
         } elseif (strstr($key, 'date_') != "") {
             $workingtime[str_replace("date_", "", $key)]["close"] = $field;
         }
     }
     $resultBusiness = $model->updateBusiness($business);
     $resultUserinfo = $model->updateUserinfo($userinfo);
     $resultWorkingtime = $model->updateWorkingtime($workingtime, $business);
     if ($resultBusiness == TRUE && $resultUserinfo == TRUE && $resultWorkingtime == TRUE && $returnPassword == TRUE) {
         $this->setMessage(JText::_('Dine ændringen er nu gemt!'));
         $this->setRedirect(JRoute::_('index.php?option=com_business&view=business', false));
         //            $this->setRedirect(JRoute::_('index.php?option=com_business&view=business&layout=complete', false));
     } else {
         $app->setUserState('com_business.business.data', $business);
         $app->setUserState('com_business.business.workingtime', $requestData);
         $app->setUserState('com_business.business.userinfo', $requestData);
         $this->setMessage(JText::_('Adgangskoden er for kort. Adgangskoden skal være på mindst 4 karakterer.'), 'warning');
         $this->setRedirect(JRoute::_('index.php?option=com_business&view=business', false));
         return false;
     }
 }