/** * Hook for after parsing route * * @return void */ public function onAfterRoute() { // First, check for presence of subject dn, which is the minimum required field if (!isset($_SERVER['SSL_CLIENT_S_DN']) || !$_SERVER['SSL_CLIENT_S_DN']) { \App::redirect($this->params->get('failure_location', '/invalidcert.php')); return; } if (\User::isGuest()) { // If so, redirect to login Request::setVar('option', 'com_users'); Request::setVar('task', 'user.login'); Request::setVar('authenticator', 'certificate'); Request::setVar('return', base64_encode(\Request::current())); return; } // Check if user is registered and if current session is linked to cert identity $hzad = \Hubzero\Auth\Domain::getInstance('authentication', 'certificate', $_SERVER['SSL_CLIENT_I_DN_CN']); if ($link = \Hubzero\Auth\Link::getInstance($hzad->id, $_SERVER['SSL_CLIENT_S_DN_CN'])) { if ($link->user_id == \User::get('id')) { // All clear...return nothing return; } } // Otherwise, we have a cert-based user that doesn't match the current user Request::setVar('option', 'com_users'); Request::setVar('task', 'user.logout'); $this->event->stop(); }
function display($tpl = null) { $user = User::getRoot(); // If this is an auth_link account update, carry on, otherwise raise an error if (!is_object($user) || !array_key_exists('auth_link_id', $user) || !is_numeric($user->get('username')) || !$user->get('username') < 0) { App::abort('405', 'Method not allowed'); return; } // Get and add the js and extra css to the page \Hubzero\Document\Assets::addComponentStylesheet('com_users', 'link.css'); \Hubzero\Document\Assets::addComponentStylesheet('com_users', 'providers.css'); \Hubzero\Document\Assets::addComponentScript('com_users', 'link'); // Import a few things jimport('joomla.user.helper'); // Look up a few things $hzal = \Hubzero\Auth\Link::find_by_id($user->get("auth_link_id")); $hzad = \Hubzero\Auth\Domain::find_by_id($hzal->auth_domain_id); $plugins = Plugin::byType('authentication'); // Get the display name for the current plugin being used Plugin::import('authentication', $hzad->authenticator); $plugin = Plugin::byType('authentication', $hzad->authenticator); $pparams = new \Hubzero\Config\Registry($plugin->params); $refl = new ReflectionClass("plgAuthentication{$plugin->name}"); $display_name = $pparams->get('display_name', $refl->hasMethod('onGetLinkDescription') ? $refl->getMethod('onGetLinkDescription')->invoke(NULL) : ucfirst($plugin->name)); // Look for conflicts - first check in the hub accounts $profile_conflicts = \Hubzero\User\Profile\Helper::find_by_email($hzal->email); // Now check the auth_link table $link_conflicts = \Hubzero\Auth\Link::find_by_email($hzal->email, array($hzad->id)); $conflict = array(); if ($profile_conflicts) { foreach ($profile_conflicts as $p) { $user_id = JUserHelper::getUserId($p); $juser = User::getInstance($user_id); $auth_link = \Hubzero\Auth\Link::find_by_user_id($juser->id); $dname = is_object($auth_link) && $auth_link->auth_domain_name ? $auth_link->auth_domain_name : 'hubzero'; $conflict[] = array("auth_domain_name" => $dname, "name" => $juser->name, "email" => $juser->email); } } if ($link_conflicts) { foreach ($link_conflicts as $l) { $juser = User::getInstance($l['user_id']); $conflict[] = array("auth_domain_name" => $l['auth_domain_name'], "name" => $juser->name, "email" => $l['email']); } } // Make sure we don't somehow have any duplicate conflicts $conflict = array_map("unserialize", array_unique(array_map("serialize", $conflict))); // @TODO: Could also check for high probability of name matches??? // Get the site name $sitename = Config::get('sitename'); // Assign variables to the view $this->assign('hzal', $hzal); $this->assign('hzad', $hzad); $this->assign('plugins', $plugins); $this->assign('display_name', $display_name); $this->assign('conflict', $conflict); $this->assign('sitename', $sitename); $this->assignref('juser', $user); parent::display($tpl); }
/** * Method is called after user data is deleted from the database * * @param array $user holds the user data * @param boolean $success true if user was succesfully stored in the database * @param string $msg message * @return boolean True on success */ public function onAfterDeleteUser($user, $succes, $msg) { $xprofile = \Hubzero\User\Profile::getInstance($user['id']); // remove user from groups \Hubzero\User\Helper::removeUserFromGroups($user['id']); if (is_object($xprofile)) { $xprofile->delete(); } \Hubzero\Auth\Link::delete_by_user_id($user['id']); // Check if quota exists for the user require_once PATH_CORE . DS . 'components' . DS . 'com_members' . DS . 'tables' . DS . 'users_quotas.php'; $quota = new \Components\Members\Tables\UsersQuotas($this->database); $quota->load(array('user_id' => $user['id'])); if ($quota->id) { $quota->delete(); } return true; }
/** * Similar to onAuthenticate, except we already have a logged in user, we're just linking accounts * * @param array $options * @return void */ public function link($options = array()) { // Set up the config for the sdk instance $config = array('appId' => $this->params->get('app_id'), 'secret' => $this->params->get('app_secret')); // Set defaults \Facebook\FacebookSession::setDefaultApplication($config['appId'], $config['secret']); $helper = new \Facebook\FacebookRedirectLoginHelper(self::getReturnUrl($options['return'])); try { $session = $helper->getSessionFromRedirect(); } catch (\Facebook\FacebookRequestException $ex) { // When Facebook returns an error } catch (\Exception $ex) { // When validation fails or other local issues } // Make sure we have a user_id (facebook returns 0 for a non-logged in user) if (isset($user_id) && $user_id > 0 || isset($session) && $session) { try { $request = new \Facebook\FacebookRequest($session, 'GET', '/me'); $user_profile = $request->execute()->getGraphObject(\Facebook\GraphUser::className()); $id = $user_profile->getId(); $email = $user_profile->getProperty('email'); } catch (\Facebook\FacebookRequestException $e) { // Error message? $response->status = \Hubzero\Auth\Status::FAILURE; $response->error_message = Lang::txt('PLG_AUTHENTICATION_FACEBOOK_ERROR_RETRIEVING_PROFILE', $e->getMessage()); return; } $hzad = \Hubzero\Auth\Domain::getInstance('authentication', 'facebook', ''); // Create the link if (\Hubzero\Auth\Link::getInstance($hzad->id, $id)) { // This facebook account is already linked to another hub account App::redirect(Route::url('index.php?option=com_members&id=' . User::get('id') . '&active=account'), Lang::txt('PLG_AUTHENTICATION_FACEBOOK_ACCOUNT_ALREADY_LINKED'), 'error'); } else { $hzal = \Hubzero\Auth\Link::find_or_create('authentication', 'facebook', null, $id); $hzal->user_id = User::get('id'); $hzal->email = $email; $hzal->update(); } } else { // User didn't authorize our app, or, clicked cancel App::redirect(Route::url('index.php?option=com_members&id=' . User::get('id') . '&active=account'), Lang::txt('PLG_AUTHENTICATION_FACEBOOK_MUST_AUTHORIZE_TO_LINK', Config::get('sitename')), 'error'); } }
/** * Short description for 'create' * * Long description (if any) ... * * @return mixed Return description (if any) ... */ public function createTask() { if (!User::isGuest() && !User::get('tmp_user')) { App::redirect(Route::url('index.php?option=' . $this->_option . '&task=myaccount'), Lang::txt('COM_MEMBERS_REGISTER_ERROR_NONGUEST_SESSION_CREATION'), 'warning'); return; } if (!isset($this->_taskMap[$this->_task])) { $this->_task = 'create'; Request::setVar('task', 'create'); } // Set the pathway $this->_buildPathway(); // Set the page title $this->_buildTitle(); $usersConfig = Component::params('com_users'); if ($usersConfig->get('allowUserRegistration') == '0') { return App::abort(404, Lang::txt('JGLOBAL_RESOURCE_NOT_FOUND')); } $hzal = null; if (User::get('auth_link_id')) { $hzal = \Hubzero\Auth\Link::find_by_id(User::get('auth_link_id')); } // Instantiate a new registration object $xregistration = new \Components\Members\Models\Registration(); if (Request::getMethod() == 'POST') { // Check for request forgeries Request::checkToken(); // Load POSTed data $xregistration->loadPost(); // Perform field validation if ($xregistration->check('create')) { // Get required system objects $user = clone User::getRoot(); $authorize = \JFactory::getACL(); // If user registration is not allowed, show 403 not authorized. if ($usersConfig->get('allowUserRegistration') == '0') { App::abort(403, Lang::txt('Access Forbidden')); return; } // Initialize new usertype setting $newUsertype = $usersConfig->get('new_usertype'); if (!$newUsertype) { $db = App::get('db'); $query = $db->getQuery(true)->select('id')->from('#__usergroups')->where('title = "Registered"'); $db->setQuery($query); $newUsertype = $db->loadResult(); } $user->set('username', $xregistration->get('login')); $user->set('name', $xregistration->get('name')); $user->set('email', $xregistration->get('email')); /* // Bind the post array to the user object if (!$user->bind(Request::get('post'), 'usertype')) { App::abort(500, $user->getError()); } */ // Set some initial user values $user->set('id', 0); $user->set('groups', array($newUsertype)); $date = Date::of('now'); $user->set('registerDate', $date->toSql()); // Check user activation setting // 0 = automatically confirmed // 1 = require email confirmation (the norm) // 2 = require admin confirmation $useractivation = $usersConfig->get('useractivation', 1); // If requiring admin approval, set user to block if ($useractivation == 2) { $user->set('approved', 0); } // If there was an error with registration, set the message and display form if ($user->save()) { /* // Send registration confirmation mail $password = Request::getString('password', '', 'post', JREQUEST_ALLOWRAW); $password = preg_replace('/[\x00-\x1F\x7F]/', '', $password); //Disallow control chars in the email UserController::_sendMail($user, $password); // Everything went fine, set relevant message depending upon user activation state and display message if ($useractivation == 1) { $message = Lang::txt('REG_COMPLETE_ACTIVATE'); } else { $message = Lang::txt('REG_COMPLETE'); } App::redirect(Route::url('index.php'), $message); */ // Get some settings $params = Component::params('com_members'); $hubHomeDir = rtrim($params->get('homedir'), '/'); // Attempt to get the new user $xprofile = \Hubzero\User\Profile::getInstance($user->get('id')); $result = is_object($xprofile); // Did we successfully create an account? if ($result) { $xprofile->loadRegistration($xregistration); if (is_object($hzal)) { if ($xprofile->get('email') == $hzal->email) { $xprofile->set('emailConfirmed', 3); } else { $xprofile->set('emailConfirmed', -rand(1, pow(2, 31) - 1)); } } else { if ($useractivation == 0) { $xprofile->set('emailConfirmed', 1); } } $xprofile->set('public', 0); // Do we have a return URL? $regReturn = Request::getVar('return', ''); if ($regReturn) { $xprofile->setParam('return', $regReturn); } // Unset password here so that change password below can be in charge of setting it initially $xprofile->set('password', ''); $result = $xprofile->update(); } // add member interests $interests = $xregistration->get('interests'); $mt = new \Components\Members\Models\Tags($xprofile->get('uidNumber')); if (!empty($interests)) { $mt->setTags($interests, $xprofile->get('uidNumber')); } if ($result) { $result = \Hubzero\User\Password::changePassword($xprofile->get('uidNumber'), $xregistration->get('password')); // Set password back here in case anything else down the line is looking for it $xprofile->set('password', $xregistration->get('password')); } // Did we successfully create/update an account? if (!$result) { return App::abort(500, Lang::txt('COM_MEMBERS_REGISTER_ERROR_CREATING_ACCOUNT')); } if ($xprofile->get('emailConfirmed') < 0) { // Notify the user $subject = Config::get('sitename') . ' ' . Lang::txt('COM_MEMBERS_REGISTER_EMAIL_CONFIRMATION'); $eview = new \Hubzero\Mail\View(array('name' => 'emails', 'layout' => 'create')); $eview->option = $this->_option; $eview->controller = $this->_controller; $eview->sitename = Config::get('sitename'); $eview->xprofile = $xprofile; $eview->baseURL = $this->baseURL; $eview->xregistration = $xregistration; $msg = new \Hubzero\Mail\Message(); $msg->setSubject($subject)->addTo($xprofile->get('email'), $xprofile->get('name'))->addFrom(Config::get('mailfrom'), Config::get('sitename') . ' Administrator')->addHeader('X-Component', $this->_option); $message = $eview->loadTemplate(false); $message = str_replace("\n", "\r\n", $message); $msg->addPart($message, 'text/plain'); $eview->setLayout('create_html'); $message = $eview->loadTemplate(); $message = str_replace("\n", "\r\n", $message); $msg->addPart($message, 'text/html'); if (!$msg->send()) { $this->setError(Lang::txt('COM_MEMBERS_REGISTER_ERROR_EMAILING_CONFIRMATION')); // @FIXME: LOG ERROR SOMEWHERE } } // Notify administration if ($usersConfig->get('mail_to_admin', 0)) { $eview = new \Hubzero\Mail\View(array('name' => 'emails', 'layout' => 'admincreate_plain')); $eview->option = $this->_option; $eview->controller = $this->_controller; $eview->sitename = Config::get('sitename'); $eview->xprofile = $xprofile; $eview->baseUrl = $this->baseURL; $plain = $eview->loadTemplate(false); $plain = str_replace("\n", "\r\n", $plain); // HTML $eview->setLayout('admincreate_html'); $html = $eview->loadTemplate(); $html = str_replace("\n", "\r\n", $html); $hubMonitorEmail = Config::get('mailfrom'); $message = new \Hubzero\Mail\Message(); $message->setSubject(Config::get('sitename') . ' ' . Lang::txt('COM_MEMBERS_REGISTER_EMAIL_ACCOUNT_CREATION'))->addTo($hubMonitorEmail)->addFrom(Config::get('mailfrom'), Config::get('sitename') . ' Administrator')->addHeader('X-Component', $this->_option)->addHeader('X-Component-Object', 'user_creation_admin_notification')->addPart($plain, 'text/plain')->addPart($html, 'text/html'); // Send mail if (!$message->send()) { \Log::error('Members admin notification email failed: ' . Lang::txt('Failed to mail %s', $hubMonitorEmail)); } } // Instantiate a new view $this->view->setLayout('create'); $this->view->title = Lang::txt('COM_MEMBERS_REGISTER_CREATE_ACCOUNT'); $this->view->sitename = Config::get('sitename'); $this->view->xprofile = $xprofile; if ($this->getError()) { $this->view->setError($this->getError()); } $this->view->display(); if (is_object($hzal)) { $hzal->user_id = $user->get('id'); if ($hzal->user_id > 0) { $hzal->update(); } } User::set('auth_link_id', null); User::set('tmp_user', null); User::set('username', $xregistration->get('login')); User::set('email', $xregistration->get('email')); User::set('id', $user->get('id')); return; } } } if (Request::method() == 'GET') { if (User::get('tmp_user')) { $xregistration->loadAccount(User::getRoot()); $username = $xregistration->get('login'); $email = $xregistration->get('email'); if (is_object($hzal)) { $xregistration->set('login', $hzal->username); $xregistration->set('email', $hzal->email); $xregistration->set('confirmEmail', $hzal->email); } } } return $this->_show_registration_form($xregistration, 'create'); }
/** * Method to log out a user. * * @since 1.6 */ public function logout() { $app = JFactory::getApplication(); $user = User::getInstance(); $authenticator = Request::getVar('authenticator', '', 'method'); $singleSignOn = Request::getVar('sso', false); if (empty($authenticator) || $authenticator == '') { $cookie = \Hubzero\Utility\Cookie::eat('authenticator'); if (isset($cookie->authenticator)) { $authenticator = $cookie->authenticator; } else { $authenticator = null; } } // If a specific authenticator is specified try to call the logout method for that plugin if (!empty($authenticator)) { Plugin::import('authentication'); $plugins = Plugin::byType('authentication'); foreach ($plugins as $plugin) { $className = 'plg' . $plugin->type . $plugin->name; if ($plugin->name != $authenticator) { continue; } if (class_exists($className)) { if (method_exists($className, 'logout')) { $myplugin = new $className($this, (array) $plugin); // Redirect to user third party signout view // Only do this for PUCAS for the time being (it's the one that doesn't lose session info after hub logout) if ($authenticator == 'pucas') { // Get plugin params $plugin = Plugin::byType('authentication', $authenticator); $pparams = new \Hubzero\Config\Registry($plugin->params); $auto_logoff = $pparams->get('auto_logoff', false); if ($auto_logoff || $singleSignOn == 'all') { $result = $myplugin->logout(); break; } elseif ($singleSignOn === false) { App::redirect(Route::url('index.php?option=com_users&view=endsinglesignon&authenticator=' . $authenticator, false)); return; } else { break; } } else { $result = $myplugin->logout(); break; } // Normal path } // End verification of logout() method } // End plugin check } // End foreach } // End check for specified authenticator // Perform the log out $error = $app->logout(); // Check if the log out succeeded. if (!$error instanceof Exception) { // If the authenticator is empty, but they have an active third party session, // redirect to a page indicating this and offering complete signout if (isset($user->auth_link_id) && $user->auth_link_id && empty($authenticator)) { $auth_domain_name = ''; $auth_domain = \Hubzero\Auth\Link::find_by_id($user->auth_link_id); if (is_object($auth_domain)) { $auth_domain_id = $auth_domain->auth_domain_id; $auth_domain_name = \Hubzero\Auth\Domain::find_by_id($auth_domain_id)->authenticator; } // Redirect to user third party signout view // Only do this for PUCAS for the time being (it's the one that doesn't lose session info after hub logout) if ($auth_domain_name == 'pucas') { // Get plugin params $plugin = Plugin::byType('authentication', $auth_domain_name); $pparams = new \Hubzero\Config\Registry($plugin->params); $auto_logoff = $pparams->get('auto_logoff', false); if ($auto_logoff) { App::redirect(Route::url('index.php?option=com_users&task=user.logout&authenticator=' . $auth_domain_name, false)); return; } else { App::redirect(Route::url('index.php?option=com_users&view=endsinglesignon&authenticator=' . $auth_domain_name, false)); return; } } } // Get the return url from the request and validate that it is internal. $return = Request::getVar('return', '', 'method', 'base64'); $return = base64_decode($return); if (!JURI::isInternal($return)) { $return = ''; } // Redirect the user. App::redirect(Route::url($return, false)); } else { App::redirect(Route::url('index.php?option=com_users&view=login', false)); } }
/** * Remove linked account * * @return void */ private function _unlink() { // Get the id of the account to be unlinked $hzal_id = Request::getInt('hzal_id', null); // Get instance $hzal = \Hubzero\Auth\Link::find_by_id($hzal_id); // Determine what type of password change the user needs $hzup = \Hubzero\User\Password::getInstance($this->member->get('uidNumber')); if (empty($hzup->passhash) && count(\Hubzero\Auth\Link::find_by_user_id($this->member->get('uidNumber'))) <= 1) { App::redirect(Route::url($this->member->getLink() . '&active=account'), Lang::txt('PLG_MEMBERS_ACCOUNT_CANT_REMOVE_ONLY_ACCESS'), 'warning'); } // Delete the auth_link if (!$hzal->delete()) { App::abort(500, Lang::txt('PLG_MEMBERS_UNLINK_FAILED')); return; } // Set the redirect App::redirect(Route::url($this->member->getLink() . '&active=account'), Lang::txt('PLG_MEMBERS_ACCOUNT_UNLINKED'), 'passed'); }
/** * Similar to onAuthenticate, except we already have a logged in user, we're just linking accounts * * @param array $options additional options * @return void */ public function link($options = array()) { // Check for the required subject dn field if ($this->isAuthenticated()) { $domain = $_SERVER['SSL_CLIENT_I_DN_CN']; $username = $_SERVER['SSL_CLIENT_S_DN_CN']; $hzad = \Hubzero\Auth\Domain::getInstance('authentication', 'certificate', $domain); // Create the link if (\Hubzero\Auth\Link::getInstance($hzad->id, $username)) { // This certificate account is already linked to another hub account App::redirect(Route::url('index.php?option=com_members&id=' . User::get('id') . '&active=account'), Lang::txt('PLG_AUTHENTICATION_CERTIFICATE_ACCOUNT_ALREADY_LINKED'), 'error'); } else { $hzal = \Hubzero\Auth\Link::find_or_create('authentication', 'certificate', $domain, $username); $hzal->user_id = User::get('id'); $hzal->email = $_SERVER['SSL_CLIENT_S_DN_Email']; $hzal->update(); } } else { // User somehow got redirect back without being authenticated (not sure how this would happen?) App::redirect(Route::url('index.php?option=com_members&id=' . User::get('id') . '&active=account'), Lang::txt('PLG_AUTHENTICATION_CERTIFICATE_ERROR_LINKING_CERT'), 'error'); } }
/** * Similar to onAuthenticate, except we already have a logged in user, we're just linking accounts * * @param array $options * @return void */ public function link($options = array()) { // Set up the config for the ORCID api instance $oauth = new Oauth(); $oauth->setClientId($this->params->get('client_id'))->setClientSecret($this->params->get('client_secret'))->setRedirectUri(self::getRedirectUri('orcid')); // If we have a code coming back, the user has authorized our app, and we can authenticate if (!Request::getVar('code', NULL)) { // User didn't authorize our app, or, clicked cancel... App::redirect(Route::url('index.php?option=com_members&id=' . User::get('id') . '&active=account'), Lang::txt('PLG_AUTHENTICATION_ORCID_MUST_AUTHORIZE_TO_LINK', Config::get('sitename')), 'error'); } // Authenticate the user $oauth->authenticate(Request::getVar('code')); // Check for successful authentication if ($oauth->isAuthenticated()) { $orcid = new Profile($oauth); // Set username to ORCID iD $username = $orcid->id(); $hzad = \Hubzero\Auth\Domain::getInstance('authentication', 'orcid', ''); // Create the link if (\Hubzero\Auth\Link::getInstance($hzad->id, $username)) { // This orcid account is already linked to another hub account App::redirect(Route::url('index.php?option=com_members&id=' . User::get('id') . '&active=account'), Lang::txt('PLG_AUTHENTICATION_ORCID_ACCOUNT_ALREADY_LINKED'), 'error'); } else { // Create the hubzero auth link $hzal = \Hubzero\Auth\Link::find_or_create('authentication', 'orcid', null, $username); $hzal->user_id = User::get('id'); $hzal->email = $orcid->email(); $hzal->update(); } } else { // User didn't authorize our app, or, clicked cancel... App::redirect(Route::url('index.php?option=com_members&id=' . User::get('id') . '&active=account'), Lang::txt('PLG_AUTHENTICATION_ORCID_MUST_AUTHORIZE_TO_LINK', Config::get('sitename')), 'error'); } }
/** * Similar to onAuthenticate, except we already have a logged in user, we're just linking accounts * * @param array $options * @return void */ public function link($options = array()) { // Build twitter object using temp credentials saved in session $twitter = new TwitterOAuth($this->params->get('app_id'), $this->params->get('app_secret'), App::get('session')->get('twitter.oauth.token'), App::get('session')->get('twitter.oauth.token_secret')); // Request user specific (longer lasting) credentials $token_credentials = $twitter->getAccessToken(Request::getVar('oauth_verifier')); // Build new twitter object with user credentials $twitter = new TwitterOAuth($this->params->get('app_id'), $this->params->get('app_secret'), $token_credentials['oauth_token'], $token_credentials['oauth_token_secret']); // Get user account info $account = $twitter->get('account/verify_credentials'); // Make sure we have a twitter account if (!$account->errors && $account->id > 0) { // Get unique username $username = (string) $account->id; $hzad = \Hubzero\Auth\Domain::getInstance('authentication', 'twitter', ''); // Create the link if (\Hubzero\Auth\Link::getInstance($hzad->id, $username)) { // This twitter account is already linked to another hub account App::redirect(Route::url('index.php?option=com_members&id=' . User::get('id') . '&active=account'), Lang::txt('PLG_AUTHENTICATION_TWITTER_ACCOUNT_ALREADY_LINKED'), 'error'); return; } else { $hzal = \Hubzero\Auth\Link::find_or_create('authentication', 'twitter', null, $username); $hzal->user_id = User::get('id'); $hzal->update(); } } else { // User didn't authorize our app, or, clicked cancel App::redirect(Route::url('index.php?option=com_members&id=' . User::get('id') . '&active=account'), Lang::txt('PLG_AUTHENTICATION_TWITTER_MUST_AUTHORIZE_TO_LINK', Config::get('sitename')), 'error'); return; } }
/** * Similar to onAuthenticate, except we already have a logged in user, we're just linking accounts * * @param array $options * @return void */ public function link($options = array()) { $jsession = App::get('session'); // Set up linkedin configuration $linkedin_config['appKey'] = $this->params->get('api_key'); $linkedin_config['appSecret'] = $this->params->get('app_secret'); // Create Object $linkedin_client = new LinkedIn($linkedin_config); if (!Request::getVar('oauth_verifier', NULL)) { // User didn't authorize our app, or, clicked cancel App::redirect(Route::url('index.php?option=com_members&id=' . User::get('id') . '&active=account'), Lang::txt('PLG_AUTHENTICATION_LINKEDIN_MUST_AUTHORIZE_TO_LOGIN', App::get('sitename')), 'error'); } // LinkedIn has sent a response, user has granted permission, take the temp access token, // the user's secret and the verifier to request the user's real secret key $request = $jsession->get('linkedin.oauth.request'); $reply = $linkedin_client->retrieveTokenAccess($request['oauth_token'], $request['oauth_token_secret'], Request::getVar('oauth_verifier')); if ($reply['success'] === TRUE) { // The request went through without an error, gather user's 'access' tokens $jsession->set('linkedin.oauth.access', $reply['linkedin']); // Set the user as authorized for future quick reference $jsession->set('linkedin.oauth.authorized', TRUE); } else { return new Exception(Lang::txt('Access token retrieval failed'), 500); } if ($jsession->get('linkedin.oauth.authorized') == TRUE) { $linkedin_client->setTokenAccess($jsession->get('linkedin.oauth.access')); // Get the linked in profile $profile = $linkedin_client->profile('~:(id,first-name,last-name,email-address)'); $profile = $profile['linkedin']; // Parse the profile XML $profile = new SimpleXMLElement($profile); // Get the profile values $li_id = $profile->{'id'}; $username = (string) $li_id; // (make sure this is unique) $hzad = \Hubzero\Auth\Domain::getInstance('authentication', 'linkedin', ''); // Create the link if (\Hubzero\Auth\Link::getInstance($hzad->id, $username)) { // This linkedin account is already linked to another hub account App::redirect(Route::url('index.php?option=com_members&id=' . User::get('id') . '&active=account'), Lang::txt('PLG_AUTHENTICATION_LINKEDIN_ACCOUNT_ALREADY_LINKED'), 'error'); } else { $hzal = \Hubzero\Auth\Link::find_or_create('authentication', 'linkedin', null, $username); $hzal->user_id = User::get('id'); $hzal->email = (string) $profile->{'email-address'}; $hzal->update(); } } else { // User didn't authorize our app, or, clicked cancel App::redirect(Route::url('index.php?option=com_members&id=' . User::get('id') . '&active=account'), Lang::txt('PLG_AUTHENTICATION_LINKEDIN_MUST_AUTHORIZE_TO_LINK', Config::get('sitename')), 'error'); } }
/** * Similar to onAuthenticate, except we already have a logged in user, we're just linking accounts * * @param array $options * @return void */ public function link($options = array()) { // Set up the config for the google api instance $client = new Google_Client(); $client->setClientId($this->params->get('app_id')); $client->setClientSecret($this->params->get('app_secret')); $client->setRedirectUri(self::getRedirectUri('google')); // Create OAuth2 Instance $oauth2 = new Google_Service_Oauth2($client); // If we have this code, we know we have a successful return from google if ($code = Request::getVar('code', NULL)) { // Authenticate the user $client->authenticate($code); } // If we have an access token set, carry on if ($client->getAccessToken()) { // Get the user info $user_profile = $oauth2->userinfo->get(); // Make sure we use something unique and consistent here! $username = $user_profile['email']; $hzad = \Hubzero\Auth\Domain::getInstance('authentication', 'google', ''); // Create the link if (\Hubzero\Auth\Link::getInstance($hzad->id, $username)) { // This google account is already linked to another hub account App::redirect(Route::url('index.php?option=com_members&id=' . User::get('id') . '&active=account'), Lang::txt('PLG_AUTHENTICATION_GOOGLE_ACCOUNT_ALREADY_LINKED'), 'error'); } else { // Create the hubzero auth link $hzal = \Hubzero\Auth\Link::find_or_create('authentication', 'google', null, $username); $hzal->user_id = User::get('id'); $hzal->email = $user_profile['email']; $hzal->update(); } } else { // User didn't authorize our app, or, clicked cancel... App::redirect(Route::url('index.php?option=com_members&id=' . User::get('id') . '&active=account'), Lang::txt('PLG_AUTHENTICATION_GOOGLE_MUST_AUTHORIZE_TO_LINK', Config::get('sitename')), 'error'); } }
/** * Show a form for registering * * @return void */ public function createTask() { if (!User::isGuest() && !User::get('tmp_user')) { App::redirect(Route::url('index.php?option=' . $this->_option . '&task=myaccount'), Lang::txt('COM_MEMBERS_REGISTER_ERROR_NONGUEST_SESSION_CREATION'), 'warning'); } if (!isset($this->_taskMap[$this->_task])) { $this->_task = 'create'; Request::setVar('task', 'create'); } // If user registration is not allowed, show 403 not authorized. $usersConfig = Component::params('com_members'); if ($usersConfig->get('allowUserRegistration') == '0') { return App::abort(404, Lang::txt('JGLOBAL_RESOURCE_NOT_FOUND')); } $hzal = null; if (User::get('auth_link_id')) { $hzal = \Hubzero\Auth\Link::find_by_id(User::get('auth_link_id')); } // Instantiate a new registration object $xregistration = new \Components\Members\Models\Registration(); if (Request::getMethod() == 'POST') { // Check for request forgeries Request::checkToken(); // Load POSTed data $xregistration->loadPost(); // Perform field validation $result = $xregistration->check('create'); // Incoming profile edits $profile = Request::getVar('profile', array(), 'post', 'none', 2); // Compile profile data foreach ($profile as $key => $data) { if (isset($profile[$key]) && is_array($profile[$key])) { $profile[$key] = array_filter($profile[$key]); } if (isset($profile[$key . '_other']) && trim($profile[$key . '_other'])) { if (is_array($profile[$key])) { $profile[$key][] = $profile[$key . '_other']; } else { $profile[$key] = $profile[$key . '_other']; } unset($profile[$key . '_other']); } } // Validate profile data $fields = \Components\Members\Models\Profile\Field::all()->including(['options', function ($option) { $option->select('*'); }])->where('action_create', '!=', \Components\Members\Models\Profile\Field::STATE_HIDDEN)->ordered()->rows(); // Validate profile fields if ($fields->count()) { $form = new \Hubzero\Form\Form('profile', array('control' => 'profile')); $form->load(\Components\Members\Models\Profile\Field::toXml($fields, 'create', $profile)); $form->bind(new \Hubzero\Config\Registry($profile)); if (!$form->validate($profile)) { $result = false; foreach ($form->getErrors() as $key => $error) { if ($error instanceof \Hubzero\Form\Exception\MissingData) { $xregistration->_missing[$key] = $error; } $xregistration->_invalid[$key] = $error; } } } // Passed validation? if ($result) { // Get required system objects $user = clone User::getInstance(); // Initialize new usertype setting $newUsertype = $usersConfig->get('new_usertype'); if (!$newUsertype) { $db = App::get('db'); $query = $db->getQuery(true)->select('id')->from('#__usergroups')->where('title = "Registered"'); $db->setQuery($query); $newUsertype = $db->loadResult(); } $user->set('username', $xregistration->get('login', '')); $user->set('name', $xregistration->get('name', '')); $user->set('givenName', $xregistration->get('givenName', '')); $user->set('middleName', $xregistration->get('middleName', '')); $user->set('surname', $xregistration->get('surname', '')); $user->set('email', $xregistration->get('email', '')); $user->set('usageAgreement', (int) $xregistration->get('usageAgreement', 0)); $user->set('sendEmail', -1); if ($xregistration->get('sendEmail') >= 0) { $user->set('sendEmail', (int) $xregistration->get('sendEmail')); } // Set home directory $hubHomeDir = rtrim($this->config->get('homedir'), '/'); if (!$hubHomeDir) { // try to deduce a viable home directory based on sitename or live_site $sitename = strtolower(Config::get('sitename')); $sitename = preg_replace('/^http[s]{0,1}:\\/\\//', '', $sitename, 1); $sitename = trim($sitename, '/ '); $sitename_e = explode('.', $sitename, 2); if (isset($sitename_e[1])) { $sitename = $sitename_e[0]; } if (!preg_match("/^[a-zA-Z]+[\\-_0-9a-zA-Z\\.]+\$/i", $sitename)) { $sitename = ''; } if (empty($sitename)) { $sitename = strtolower(Request::base()); $sitename = preg_replace('/^http[s]{0,1}:\\/\\//', '', $sitename, 1); $sitename = trim($sitename, '/ '); $sitename_e = explode('.', $sitename, 2); if (isset($sitename_e[1])) { $sitename = $sitename_e[0]; } if (!preg_match("/^[a-zA-Z]+[\\-_0-9a-zA-Z\\.]+\$/i", $sitename)) { $sitename = ''; } } $hubHomeDir = DS . 'home'; if (!empty($sitename)) { $hubHomeDir .= DS . $sitename; } } $user->set('homeDirectory', $hubHomeDir . DS . $user->get('username')); $user->set('loginShell', '/bin/bash'); $user->set('ftpShell', '/usr/lib/sftp-server'); // Set some initial user values $user->set('id', 0); $user->set('accessgroups', array($newUsertype)); $user->set('registerDate', Date::toSql()); // Check user activation setting // 0 = automatically confirmed // 1 = require email confirmation (the norm) // 2 = require admin confirmation $useractivation = $usersConfig->get('useractivation', 1); // If requiring admin approval, set user to block if ($useractivation == 2) { $user->set('approved', 0); } $user->set('access', 5); $user->set('activation', -rand(1, pow(2, 31) - 1)); if (is_object($hzal)) { if ($user->get('email') == $hzal->email) { $user->set('activation', 3); } } else { if ($useractivation == 0) { $user->set('activation', 1); $user->set('access', (int) $this->config->get('privacy', 1)); } } $user->set('password', \Hubzero\User\Password::getPasshash($xregistration->get('password'))); // Do we have a return URL? $regReturn = Request::getVar('return', ''); if ($regReturn) { $user->setParam('return', $regReturn); } // If we managed to create a user if ($user->save()) { $access = array(); foreach ($fields as $field) { $access[$field->get('name')] = $field->get('access'); } $profile = $xregistration->_registration['_profile']; // Save profile data $member = Member::oneOrNew($user->get('id')); if (!$member->saveProfile($profile, $access)) { \Notify::error($member->getError()); // Don't stop the registration process! // At this point, the account was successfully created. // The profile info, however, may have issues. But, it's not crucial. //$result = false; } } else { \Notify::error($user->getError()); $result = false; } // If everything is OK so far... if ($result) { $result = \Hubzero\User\Password::changePassword($user->get('id'), $xregistration->get('password')); // Set password back here in case anything else down the line is looking for it $user->set('password', $xregistration->get('password')); // Did we successfully create/update an account? if (!$result) { return App::abort(500, Lang::txt('COM_MEMBERS_REGISTER_ERROR_CREATING_ACCOUNT')); } // Send confirmation email if ($user->get('activation') < 0) { \Components\Members\Helpers\Utility::sendConfirmEmail($user, $xregistration); } // Instantiate a new view $this->view->set('title', Lang::txt('COM_MEMBERS_REGISTER_CREATE_ACCOUNT'))->set('sitename', Config::get('sitename'))->set('xprofile', $user)->setErrors($this->getErrors())->setLayout('create')->display(); if (is_object($hzal)) { $hzal->user_id = $user->get('id'); if ($hzal->user_id > 0) { $hzal->update(); } } User::set('auth_link_id', null); User::set('tmp_user', null); User::set('username', $xregistration->get('login')); User::set('email', $xregistration->get('email')); User::set('id', $user->get('id')); return; } } } if (Request::method() == 'GET') { if (User::get('tmp_user')) { $xregistration->loadAccount(User::getInstance()); $username = $xregistration->get('login'); $email = $xregistration->get('email'); if (is_object($hzal)) { $xregistration->set('login', $hzal->username); $xregistration->set('email', $hzal->email); $xregistration->set('confirmEmail', $hzal->email); } } } // Set the pathway $this->_buildPathway(); // Set the page title $this->_buildTitle(); return $this->_show_registration_form($xregistration, 'create'); }
/** * Similar to onAuthenticate, except we already have a logged in user, we're just linking accounts * * @param array $options * @return void */ public function link($options = array()) { // Set up the config for the api instance $client = new Oauth(); if ($this->params->get('environment') == 'sandbox') { $client->useSandboxEnvironment(); } $client->setClientId($this->params->get('app_id'))->setClientSecret($this->params->get('app_secret'))->setRedirectUri(self::getRedirectUri('orcid')); // If we have a code coming back, the user has authorized our app, and we can authenticate if ($code = Request::getVar('code', NULL)) { // Authenticate the user $client->authenticate($code); } else { // User didn't authorize our app or clicked cancel App::redirect(Route::url('index.php?option=com_users&view=login&return=' . base64_encode('/members/myaccount')), Lang::txt('PLG_AUTHENTICATION_SCISTARTER_MUST_AUTHORIZE_TO_LOGIN', Config::get('sitename')), 'error'); } if ($client->isAuthenticated()) { $account = $client->getUserData(); } else { // User didn't authorize our app or clicked cancel App::redirect(Route::url('index.php?option=com_members&id=' . User::get('id') . '&active=account'), Lang::txt('PLG_AUTHENTICATION_SCISTARTER_MUST_AUTHORIZE_TO_LINK', Config::get('sitename')), 'error'); } // Make sure we have a scistarter account if ($account->scistarter_user_id > 0) { $username = (string) $account->email; $hzad = \Hubzero\Auth\Domain::getInstance('authentication', 'scistarter', ''); // Create the link if (\Hubzero\Auth\Link::getInstance($hzad->id, $username)) { // This scistarter account is already linked to another hub account App::redirect(Route::url('index.php?option=com_members&id=' . User::get('id') . '&active=account'), Lang::txt('PLG_AUTHENTICATION_SCISTARTER_ACCOUNT_ALREADY_LINKED'), 'error'); } else { $hzal = \Hubzero\Auth\Link::find_or_create('authentication', 'scistarter', null, $username); $hzal->user_id = User::get('id'); $hzal->update(); } } else { // User didn't authorize our app, or, clicked cancel App::redirect(Route::url('index.php?option=com_members&id=' . User::get('id') . '&active=account'), Lang::txt('PLG_AUTHENTICATION_SCISTARTER_AUTHENTICATION_FAILED', Config::get('sitename')), 'error'); } }
/** * Similar to onAuthenticate, except we already have a logged in user, we're just linking accounts * * @param array $options * @return void */ public function link($options = array()) { if (Config::get('debug')) { $debug_location = $this->params->get('debug_location', '/var/log/apache2/php/phpCAS.log'); phpCAS::setDebug($debug_location); } $this->initialize(); if (phpCAS::isAuthenticated() && $this->checkBoilerkey()) { // Get unique username $username = phpCAS::getUser(); $hzad = \Hubzero\Auth\Domain::getInstance('authentication', 'pucas', ''); // Create the link if (\Hubzero\Auth\Link::getInstance($hzad->id, $username)) { // This purdue cas account is already linked to another hub account App::redirect(Route::url('index.php?option=com_members&id=' . User::get('id') . '&active=account'), Lang::txt('PLG_AUTHENTICATION_PUCAS_ACCOUNT_ALREADY_LINKED'), 'error'); } else { $hzal = \Hubzero\Auth\Link::find_or_create('authentication', 'pucas', null, $username); $hzal->user_id = User::get('id'); $hzal->email = phpCAS::getAttribute('email'); $hzal->update(); } } else { // User somehow got redirect back without being authenticated (not sure how this would happen?) App::redirect(Route::url('index.php?option=com_members&id=' . User::get('id') . '&active=account'), Lang::txt('PLG_AUTHENTICATION_PUCAS_ERROR_LINKING'), 'error'); } }
/** * @access public * @param array - $options * @return void */ public function link($options = array()) { if ($status = $this->status()) { $this->log('link', $status); // Get unique username $username = $status['eppn']; $hzad = \Hubzero\Auth\Domain::getInstance('authentication', 'shibboleth', $status['idp']); if (\Hubzero\Auth\Link::getInstance($hzad->id, $username)) { $this->log('already linked', array('domain' => $hzad->id, 'username' => $username)); App::redirect(Route::url('index.php?option=com_members&id=' . User::get('id') . '&active=account'), 'This account appears to already be linked to a hub account', 'error'); } else { $hzal = \Hubzero\Auth\Link::find_or_create('authentication', 'shibboleth', $status['idp'], $username); $hzal->user_id = User::get('id'); $this->log('setting link', $hzal); $hzal->update(); } } else { // User somehow got redirect back without being authenticated (not sure how this would happen?) App::redirect(Route::url('index.php?option=com_members&id=' . User::get('id') . '&active=account'), 'There was an error linking your account, please try again later.', 'error'); } }
/** * Method is called after user data is deleted from the database * * @param array $user holds the user data * @param boolean $success true if user was succesfully stored in the database * @param string $msg message * @return boolean True on success */ public function onAfterDeleteUser($user, $success, $msg) { $xprofile = \Hubzero\User\Profile::getInstance($user['id']); // remove user from groups \Hubzero\User\Helper::removeUserFromGroups($user['id']); if (is_object($xprofile)) { $xprofile->delete(); } \Hubzero\Auth\Link::delete_by_user_id($user['id']); // Check if quota exists for the user require_once PATH_CORE . DS . 'components' . DS . 'com_members' . DS . 'models' . DS . 'quota.php'; $quota = Components\Members\Models\Quota::all()->whereEquals('user_id', $user['id'])->row(); if ($quota->get('id')) { $quota->destroy(); } if ($success) { Event::trigger('members.onMemberAfterDelete', array($user, $success, $msg)); } return true; }