public function onAfterInitialise() { // No remember me for admin if (!App::isSite()) { return; } if (User::isGuest()) { $hash = App::hash('JLOGIN_REMEMBER'); if ($str = Request::getString($hash, '', 'cookie', 1 | 2)) { $credentials = array(); $goodCookie = true; $filter = JFilterInput::getInstance(); // Create the encryption key, apply extra hardening using the user agent string. // Since we're decoding, no UA validity check is required. $privateKey = App::hash(@$_SERVER['HTTP_USER_AGENT']); $crypt = new \Hubzero\Encryption\Encrypter(new \Hubzero\Encryption\Cipher\Simple(), new \Hubzero\Encryption\Key('simple', $privateKey, $privateKey)); try { $str = $crypt->decrypt($str); if (!is_string($str)) { throw new Exception('Decoded cookie is not a string.'); } $cookieData = json_decode($str); if (null === $cookieData) { throw new Exception('JSON could not be docoded.'); } if (!is_object($cookieData)) { throw new Exception('Decoded JSON is not an object.'); } // json_decoded cookie could be any object structure, so make sure the // credentials are well structured and only have user and password. if (isset($cookieData->username) && is_string($cookieData->username)) { $credentials['username'] = $filter->clean($cookieData->username, 'username'); } else { throw new Exception('Malformed username.'); } if (isset($cookieData->password) && is_string($cookieData->password)) { $credentials['password'] = $filter->clean($cookieData->password, 'string'); } else { throw new Exception('Malformed password.'); } // We're only doing this for the site app, so we explicitly set the action here $return = App::get('auth')->login($credentials, array('silent' => true, 'action' => 'core.login.site')); if (!$return) { throw new Exception('Log-in failed.'); } } catch (Exception $e) { $cookie_domain = Config::get('cookie_domain', ''); $cookie_path = Config::get('cookie_path', '/'); // Clear the remember me cookie setcookie(App::hash('JLOGIN_REMEMBER'), false, time() - 86400, $cookie_path, $cookie_domain); Log::warning('A remember me cookie was unset for the following reason: ' . $e->getMessage()); } } } }
/** * Retrieve a cookie * * @param (string) $namespace - make sure the cookie name is unique * @return (object) $cookie data **/ public static function eat($namespace) { $hash = \App::hash(\App::get('client')->name . ':' . $namespace); $key = \App::hash(''); $crypt = new \Hubzero\Encryption\Encrypter(new \Hubzero\Encryption\Cipher\Simple(), new \Hubzero\Encryption\Key('simple', $key, $key)); if ($str = \App::get('request')->getString($hash, '', 'cookie', JREQUEST_ALLOWRAW | JREQUEST_NOTRIM)) { $sstr = $crypt->decrypt($str); $cookie = @unserialize($sstr); return (object) $cookie; } return false; }
/** * This method should handle any login logic and report back to the subject * * @param array $user holds the user data * @param array $options array holding options (remember, autoregister, group) * @return boolean True on success */ public function onLoginUser($user, $options = array()) { jimport('joomla.user.helper'); $xuser = User::getRoot(); // get user from session (might be tmp_user, can't fetch from db) if ($xuser->get('guest')) { // joomla user plugin hasn't run or something went very badly $plugins = Plugin::byType('user'); $xuser_order = false; $joomla_order = false; $i = 0; foreach ($plugins as $plugin) { if ($plugin->name == 'xusers') { $xuser_order = $i; } if ($plugin->name == 'joomla') { $joomla_order = $i; } $i++; } if ($joomla_order === false) { return new Exception(Lang::txt('E_JOOMLA_USER_PLUGIN_MISCONFIGURED'), 500); } if ($xuser_order <= $joomla_order) { return new Exception(Lang::txt('E_HUBZERO_USER_PLUGIN_MISCONFIGURED'), 500); } return new Exception(Lang::txt('E_JOOMLA_USER_PLUGIN_FAILED'), 500); } // log login to auth log Log::auth($xuser->get('id') . ' [' . $xuser->get('username') . '] ' . $_SERVER['REMOTE_ADDR'] . ' login'); // correct apache log data apache_note('auth', 'login'); // Log attempt to the database Hubzero\User\User::oneOrFail($xuser->get('id'))->logger()->auth()->save(['username' => $xuser->get('username'), 'status' => 'success']); // update session tracking with new data $session = App::get('session'); $session->set('tracker.user_id', $xuser->get('id')); $session->set('tracker.username', $xuser->get('username')); if ($session->get('tracker.sid') == '') { $session->set('tracker.sid', $session->getId()); } $session->set('tracker.psid', $session->get('tracker.sid')); if ($session->get('tracker.rsid') == '') { $session->set('tracker.rsid', $session->getId()); } if ($session->get('tracker.user_id') != $xuser->get('id') || $session->get('tracker.ssid') == '') { $session->set('tracker.ssid', $session->getId()); } if (empty($user['type'])) { $session->clear('session.authenticator'); } else { $session->set('session.authenticator', $user['type']); } if (isset($options['silent']) && $options['silent']) { $session->set('session.source', 'cookie'); } else { $session->set('session.source', 'user'); } // update tracking data with changes related to login jimport('joomla.utilities.utility'); $hash = App::hash(App::get('client')->name . ':tracker'); $key = \App::hash(''); $crypt = new \Hubzero\Encryption\Encrypter(new \Hubzero\Encryption\Cipher\Simple(), new \Hubzero\Encryption\Key('simple', $key, $key)); $tracker = array(); $tracker['user_id'] = $session->get('tracker.user_id'); $tracker['username'] = $session->get('tracker.username'); $tracker['sid'] = $session->getId(); $tracker['rsid'] = $session->get('tracker.rsid', $tracker['sid']); $tracker['ssid'] = $session->get('tracker.ssid', $tracker['sid']); $cookie = $crypt->encrypt(serialize($tracker)); $lifetime = time() + 365 * 24 * 60 * 60; // Determine whether cookie should be 'secure' or not $secure = false; $forceSsl = \Config::get('force_ssl', false); if (\App::isAdmin() && $forceSsl >= 1) { $secure = true; } else { if (\App::isSite() && $forceSsl == 2) { $secure = true; } } setcookie($hash, $cookie, $lifetime, '/', '', $secure, true); /* Mark registration as incomplete so it gets checked on next page load */ $username = $xuser->get('username'); if (isset($user['auth_link']) && is_object($user['auth_link'])) { $hzal = $user['auth_link']; } else { $hzal = null; } if ($xuser->get('tmp_user')) { $email = $xuser->get('email'); if ($username[0] == '-') { $username = trim($username, '-'); if ($hzal) { $xuser->set('username', 'guest;' . $username); $xuser->set('email', $hzal->email); } } } else { if ($username[0] == '-') { $username = trim($username, '-'); if ($hzal) { $hzal->user_id = $xuser->get('id'); $hzal->update(); } } } if ($hzal) { $xuser->set('auth_link_id', $hzal->id); $session->set('linkaccount', true); } $session->set('registration.incomplete', true); // Check if quota exists for the user $params = Component::params('com_members'); if ($params->get('manage_quotas', false)) { require_once PATH_CORE . DS . 'components' . DS . 'com_members' . DS . 'tables' . DS . 'users_quotas.php'; require_once PATH_CORE . DS . 'components' . DS . 'com_members' . DS . 'tables' . DS . 'quotas_classes.php'; $quota = new \Components\Members\Tables\UsersQuotas($this->database); $quota->load(array('user_id' => $xuser->get('id'))); if (!$quota->id) { $class = new \Components\Members\Tables\QuotasClasses($this->database); $class->load(array('alias' => 'default')); if ($class->id) { $quota->set('user_id', $xuser->get('id')); $quota->set('class_id', $class->id); $quota->set('soft_blocks', $class->soft_blocks); $quota->set('hard_blocks', $class->hard_blocks); $quota->set('soft_files', $class->soft_files); $quota->set('hard_files', $class->hard_files); $quota->store(); } } else { if ($quota->class_id) { // Here, we're checking to make sure their class matches their actual quota values $class = new \Components\Members\Tables\QuotasClasses($this->database); $class->load($quota->class_id); if ($quota->get('soft_blocks') != $class->get('soft_blocks') || $quota->get('hard_blocks') != $class->get('hard_blocks') || $quota->get('soft_files') != $class->get('soft_files') || $quota->get('hard_files') != $class->get('hard_files')) { $quota->set('user_id', $xuser->get('id')); $quota->set('class_id', $class->id); $quota->set('soft_blocks', $class->soft_blocks); $quota->set('hard_blocks', $class->hard_blocks); $quota->set('soft_files', $class->soft_files); $quota->set('hard_files', $class->hard_files); $quota->store(); } } } } return true; }
if (strstr($b, ':')) { $b = explode(':', $b); $bits[] = trim($b[0]) . '="' . trim($b[1]) . '"'; } } } $attributes = implode(' ', $bits); } // Formats that can be previewed via Google viewer $docs = array('pdf', 'doc', 'docx', 'xls', 'xlsx', 'ppt', 'pptx', 'pages', 'ai', 'psd', 'tiff', 'dxf', 'eps', 'ps', 'ttf', 'xps', 'svg'); $html5video = array("mp4", "m4v", "webm", "ogv"); $token = ''; if (!User::isGuest()) { $session_id = App::get('session')->getId(); $key = App::hash(@$_SERVER['HTTP_USER_AGENT']); $crypter = new \Hubzero\Encryption\Encrypter(new \Hubzero\Encryption\Cipher\Simple(), new \Hubzero\Encryption\Key('simple', $key, $key)); $token = base64_encode($crypter->encrypt($session_id)); } $downloadUrl = Route::url('index.php?option=com_publications&id=' . $this->publication->id . '&task=serve&aid=' . $this->aid . '&render=download&token=' . $token); $viewUrl = Route::url('index.php?option=com_publications&id=' . $this->publication->id . '&task=serve&aid=' . $this->aid . '&render=download&disposition=inline&token=' . $token); ?> <div class="sample"> <p><?php echo Lang::txt('COM_PUBLICATIONS_PUBLICATION') . ': <strong>' . $this->publication->title . '</strong>'; ?> <?php if ($this->primary->role != 1) { echo ' Supporting Doc: <strong>' . $this->primary->path . '</strong>'; } ?> </p>
/** * Hook for after app initialization * * @return void */ public function onAfterInitialise() { // Get the session object $session = App::get('session'); if ($session->isNew()) { $tracker = array(); // Transfer tracking cookie data to session jimport('joomla.utilities.utility'); jimport('joomla.user.helper'); $hash = App::hash(App::get('client')->name . ':tracker'); $key = App::hash(''); $crypt = new \Hubzero\Encryption\Encrypter(new \Hubzero\Encryption\Cipher\Simple(), new \Hubzero\Encryption\Key('simple', $key, $key)); if ($str = Request::getString($hash, '', 'cookie', 1 | 2)) { $sstr = $crypt->decrypt($str); $tracker = @unserialize($sstr); if ($tracker === false) { //Create the encryption key, apply extra hardening using the user agent string $key = App::hash(@$_SERVER['HTTP_USER_AGENT']); $crypt = new \Hubzero\Encryption\Encrypter(new \Hubzero\Encryption\Cipher\Simple(), new \Hubzero\Encryption\Key('simple', $key, $key)); $sstr = $crypt->decrypt($str); $tracker = @unserialize($sstr); } } if (!is_array($tracker)) { $tracker = array(); } if (empty($tracker['user_id'])) { $session->clear('tracker.user_id'); } else { $session->set('tracker.user_id', $tracker['user_id']); } if (empty($tracker['username'])) { $session->clear('tracker.username'); } else { $session->set('tracker.username', $tracker['username']); } if (empty($tracker['sid'])) { $session->clear('tracker.psid'); } else { $session->set('tracker.psid', $tracker['sid']); } $session->set('tracker.sid', $session->getId()); if (empty($tracker['ssid'])) { $session->set('tracker.ssid', $session->getId()); } else { $session->set('tracker.ssid', $tracker['ssid']); } if (empty($tracker['rsid'])) { $session->set('tracker.rsid', $session->getId()); } else { $session->set('tracker.rsid', $tracker['rsid']); } // log tracking cookie detection to auth log $username = empty($tracker['username']) ? '-' : $tracker['username']; $user_id = empty($tracker['user_id']) ? 0 : $tracker['user_id']; App::get('log')->logger('auth')->info($username . ' ' . (isset($_SERVER['REMOTE_ADDR']) ? $_SERVER['REMOTE_ADDR'] : '') . ' detect'); // set new tracking cookie with current data $tracker = array(); $tracker['user_id'] = $session->get('tracker.user_id'); $tracker['username'] = $session->get('tracker.username'); $tracker['sid'] = $session->get('tracker.sid'); $tracker['rsid'] = $session->get('tracker.rsid'); $tracker['ssid'] = $session->get('tracker.ssid'); $cookie = $crypt->encrypt(serialize($tracker)); $lifetime = time() + 365 * 24 * 60 * 60 * 10; // Determine whether cookie should be 'secure' or not $secure = false; $forceSsl = \Config::get('force_ssl', false); if (\App::isAdmin() && $forceSsl >= 1) { $secure = true; } else { if (\App::isSite() && $forceSsl == 2) { $secure = true; } } setcookie($hash, $cookie, $lifetime, '/', '', $secure, true); } // all page loads set apache log data if (strpos(php_sapi_name(), 'apache') !== false) { apache_note('jsession', $session->getId()); if (User::get('id') != 0) { apache_note('auth', 'session'); apache_note('userid', User::get('id')); } else { if (!empty($tracker['user_id'])) { apache_note('auth', 'cookie'); apache_note('userid', $tracker['user_id']); apache_note('tracker', $tracker['rsid']); } } } }
/** * Login authentication function. * * Username and encoded password are passed the onUserLogin event which * is responsible for the user validation. A successful validation updates * the current session record with the user's details. * * Username and encoded password are sent as credentials (along with other * possibilities) to each observer (authentication plugin) for user * validation. Successful validation will update the current session with * the user details. * * @param array $credentials Array('username' => string, 'password' => string) * @param array $options Array('remember' => boolean) * @return boolean True on success. */ public function login($credentials, $options = array()) { $guard = new Guard($this->app); $response = $guard->authenticate($credentials, $options); if ($response->status === Status::SUCCESS) { // validate that the user should be able to login (different to being authenticated) // this permits authentication plugins blocking the user $authorisations = $guard->authorise($response, $options); $denied_states = array(Status::EXPIRED, Status::DENIED); foreach ($authorisations as $authorisation) { if (in_array($authorisation->status, $denied_states)) { // Trigger onUserAuthorisationFailure Event. $this->app['dispatcher']->trigger('user.onUserAuthorisationFailure', array((array) $authorisation)); // If silent is set, just return false. if (isset($options['silent']) && $options['silent']) { return false; } // Return the error. switch ($authorisation->status) { case Status::EXPIRED: return new Exception($this->app['language']->txt('JLIB_LOGIN_EXPIRED'), 102002, E_WARNING); break; case Status::DENIED: return new Exception($this->app['language']->txt('JLIB_LOGIN_DENIED'), 102003, E_WARNING); break; default: return new Exception($this->app['language']->txt('JLIB_LOGIN_AUTHORISATION'), 102004, E_WARNING); break; } } } // OK, the credentials are authenticated and user is authorised. Lets fire the onLogin event. $results = $this->app['dispatcher']->trigger('user.onUserLogin', array((array) $response, $options)); // If any of the user plugins did not successfully complete the login routine // then the whole method fails. // // Any errors raised should be done in the plugin as this provides the ability // to provide much more information about why the routine may have failed. if (!in_array(false, $results, true)) { // Set the remember me cookie if enabled. if (isset($options['remember']) && $options['remember']) { // Create the encryption key, apply extra hardening using the user agent string. $privateKey = $this->app->hash(@$_SERVER['HTTP_USER_AGENT']); $crypt = new \Hubzero\Encryption\Encrypter(new \Hubzero\Encryption\Cipher\Simple(), new \Hubzero\Encryption\Key('simple', $privateKey, $privateKey)); $rcookie = $crypt->encrypt(json_encode($credentials)); $lifetime = time() + 365 * 24 * 60 * 60; // Use domain and path set in config for cookie if it exists. $cookie_domain = $this->app['config']->get('cookie_domain', ''); $cookie_path = $this->app['config']->get('cookie_path', '/'); // Check for SSL connection $secure = isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on' || getenv('SSL_PROTOCOL_VERSION'); setcookie($this->app->hash('JLOGIN_REMEMBER'), $rcookie, $lifetime, $cookie_path, $cookie_domain, $secure, true); } return true; } } // Trigger onUserLoginFailure Event. $this->app['dispatcher']->trigger('user.onUserLoginFailure', array((array) $response)); // If silent is set, just return false. if (isset($options['silent']) && $options['silent']) { return false; } // If status is success, any error will have been raised by the user plugin if ($response->status !== Status::SUCCESS) { return new Exception($response->error_message, 102001, E_WARNING); } return false; }
/** * Download a file * Runs through various permissions checks to ensure user has access * * @return void */ public function downloadTask() { // Incoming $id = Request::getInt('id', 0); $alias = Request::getVar('alias', ''); $d = Request::getVar('d', 'inline'); //make sure we have a proper disposition if ($d != "inline" && $d != "attachment") { $d = "inline"; } // Load the resource $resource = new Resource($this->database); if ($alias && !$resource->loadAlias($alias)) { App::abort(404, Lang::txt('COM_RESOURCES_RESOURCE_NOT_FOUND')); return; } elseif (substr($id, 0, 4) == '9999') { $resource->id = $id; $resource->standalone = 1; $resource->path = null; $resource->created = Date::of('now')->format('Y-m-d 00:00:00'); } elseif (!$resource->load($id)) { App::abort(404, Lang::txt('COM_RESOURCES_RESOURCE_NOT_FOUND')); return; } // Check if the resource is for logged-in users only and the user is logged-in if ($token = Request::getVar('token', '', 'get')) { $token = base64_decode($token); $key = App::hash(@$_SERVER['HTTP_USER_AGENT']); $crypter = new \Hubzero\Encryption\Encrypter(new \Hubzero\Encryption\Cipher\Simple(), new \Hubzero\Encryption\Key('simple', $key, $key)); $session_id = $crypter->decrypt($token); $session = \Hubzero\Session\Helper::getSession($session_id); $user = User::getInstance($session->userid); $user->guest = 0; $user->id = $session->userid; $user->usertype = $session->usertype; } else { $user = User::getRoot(); } if ($resource->access == 1 && $user->get('guest')) { App::abort(403, Lang::txt('COM_RESOURCES_ALERTNOTAUTH')); return; } // Check if the resource is "private" and the user is allowed to view it if ($resource->access == 4 || $resource->access == 3 || !$resource->standalone) { if ($this->checkGroupAccess($resource, $user)) { App::abort(403, Lang::txt('COM_RESOURCES_ALERTNOTAUTH')); return; } } if ($resource->standalone && !$resource->path) { $resource->path = DS . trim($this->config->get('uploadpath', '/site/resources'), DS) . Html::build_path($resource->created, $resource->id, '') . DS . 'media' . DS . Request::getVar('file'); } $resource->path = trim($resource->path); // Ensure we have a path // Ensure resource is published - stemedhub #472 if (empty($resource->path) && $resource->published != 1) { App::abort(404, Lang::txt('COM_RESOURCES_FILE_NOT_FOUND')); return; } // Get the configured upload path $base_path = $this->config->get('uploadpath', '/site/resources'); if ($base_path) { $base_path = DS . trim($base_path, DS); } // Does the path start with a slash? if (substr($resource->path, 0, 1) != DS) { $resource->path = DS . $resource->path; // Does the beginning of the $resource->path match the config path? if (substr($resource->path, 0, strlen($base_path)) == $base_path) { // Yes - this means the full path got saved at some point } else { // No - append it $resource->path = $base_path . $resource->path; } } // Add root path $filename = PATH_APP . $resource->path; // Ensure the file exist if (!file_exists($filename)) { App::abort(404, Lang::txt('COM_RESOURCES_FILE_NOT_FOUND') . ' ' . $filename); return; } $ext = strtolower(\Filesystem::extension($filename)); if (!in_array($ext, array('jpg', 'jpeg', 'jpe', 'gif', 'png', 'pdf', 'htm', 'html', 'txt', 'json', 'xml'))) { $d = 'attachment'; } // Initiate a new content server and serve up the file $xserver = new \Hubzero\Content\Server(); $xserver->filename($filename); $xserver->disposition($d); $xserver->acceptranges(false); // @TODO fix byte range support if (!$xserver->serve()) { // Should only get here on error throw new Exception(Lang::txt('COM_RESOURCES_SERVER_ERROR'), 500); } else { exit; } return; }
/** * Generate a Windows tool invoke URL to redirect to * * @param string $option Name of the component * @return void */ public function invoke($option) { $no_html = Request::getInt('no_html', 0); $response = new StdClass(); $response->success = false; $response->message = Lang::txt('No invoke URL found.'); // Check for an imconing token. if ($token = Request::getVar('token', '', 'get')) { $dtoken = base64_decode($token); $key = App::hash(@$_SERVER['HTTP_USER_AGENT']); $crypter = new \Hubzero\Encryption\Encrypter(new \Hubzero\Encryption\Cipher\Simple(), new \Hubzero\Encryption\Key('simple', $key, $key)); $session_id = $crypter->decrypt($dtoken); $session = \Hubzero\Session\Helper::getSession($session_id); $user = User::getInstance($session->userid); $user->set('guest', 0); $user->set('id', $session->userid); $user->set('username', $session->username); $ip = $session->ip; } else { $user = User::getInstance(); $ip = Request::ip(); } // Is the user validated? if ($user->isGuest()) { $response->message = Lang::txt('Login is required to perform this action.'); } else { $appid = Request::getVar('appid'); // Generate the URL $url = $this->generateInvokeUrl($option, $appid, $user, $ip); if ($url) { if (!$token) { $session = App::get('session'); $session_id = $session->getId(); $key = App::hash(@$_SERVER['HTTP_USER_AGENT']); $crypter = new \Hubzero\Encryption\Encrypter(new \Hubzero\Encryption\Cipher\Simple(), new \Hubzero\Encryption\Key('simple', $key, $key)); $token = base64_encode($crypter->encrypt($session_id)); } $rurl = rtrim($this->params->get('invoke_url', 'http://wapps.hubzero.org'), '/') . '/v1?'; //standaloneUrl=' . $url; $params = array(); $params[] = 'token=' . $token; if ($appid) { $params[] = 'appid=' . $appid; } $params[] = 'standaloneUrl=' . $url; $rurl .= implode('&', $params); $response->success = true; $response->message = $rurl; if (!$no_html) { $this->view('invoke', 'display')->set('url', $rurl)->set('rurl', $_SERVER['HTTP_REFERER'])->display(); exit; App::redirect($url); } } } if (!$no_html) { App::abort(404, Lang::txt('No invoke URL found.')); } $response = json_encode($response); if ($callback = Request::getVar('callback')) { $response = $callback . '(' . $response . ')'; } echo $response; exit; }