コード例 #1
0
ファイル: Cart.php プロジェクト: pedrocones/hydrotools
 /**
  * {@inheritdoc}
  */
 public function completeSale($order, $login = FALSE)
 {
     // Empty that cart...
     $this->emptyCart();
     // Force the order to load from the DB instead of the entity cache.
     // @todo Remove this once uc_payment_enter() can modify order objects?
     // @todo Should we be overwriting $order with this newly-loaded db_order?
     $db_order = $this->entityManager()->getStorage('uc_order')->loadUnchanged($order->id());
     $order->data = $db_order->data;
     // Ensure that user creation and triggers are only run once.
     if (empty($order->data->complete_sale)) {
         $this->completeSaleAccount($order);
         // Move an order's status from "In checkout" to "Pending".
         if ($order->getStateId() == 'in_checkout') {
             $order->setStatusId(uc_order_state_default('post_checkout'));
         }
         $order->save();
         // Invoke the checkout complete trigger and hook.
         $account = $order->getUser();
         $this->moduleHandler()->invokeAll('uc_checkout_complete', array($order, $account));
         // rules_invoke_event('uc_checkout_complete', $order);
     }
     $type = $order->data->complete_sale;
     // Log in new users, if requested.
     if ($type == 'new_user' && $login && $this->currentUser()->isAnonymous()) {
         $type = 'new_user_logged_in';
         user_login_finalize($order->getUser());
     }
     $message = $this->config('uc_cart.messages')->get($type);
     $message = \Drupal::token()->replace($message, array('uc_order' => $order));
     $variables['!new_username'] = isset($order->data->new_user_name) ? $order->data->new_user_name : '';
     $variables['!new_password'] = isset($order->password) ? $order->password : t('Your password');
     $message = strtr($message, $variables);
     return array('#theme' => 'uc_cart_complete_sale', '#message' => Xss::filterAdmin($message), '#order' => $order);
 }
コード例 #2
0
 public function postAuthenticate() {
     $consumer = $this->getIdentity();
     if (isset($consumer)) {
         global $user;
         $user = user_load($consumer->uid);
         user_login_finalize();
     }
 }
コード例 #3
0
 /**
  * Log the user in.
  *
  * @param object $account
  *   The user object that was retrieved by the AuthenticationManager.
  */
 public function loginUser($account)
 {
     global $user;
     // Override the global user.
     $user = user_load($account->uid);
     $login_array = array('name' => $account->name);
     user_login_finalize($login_array);
 }
コード例 #4
0
 /**
  * @param AuthenticationEvent $event Authentication success event
  */
 public function onAuthenticationSuccess(AuthenticationEvent $event)
 {
     $user = $event->getAuthenticationToken()->getUser();
     if (is_a($user, 'Bangpound\\Bundle\\DrupalBundle\\Security\\User\\User')) {
         /** @var \Bangpound\Bundle\DrupalBundle\Security\User\User $user */
         $GLOBALS['user'] = $user->getDrupalUser();
         $edit = $this->requestStack->getCurrentRequest()->request->all();
         user_login_finalize($edit);
     }
 }
コード例 #5
0
 /**
  * Logs cosign user into drupal
  *
  * @return
  *   User Object
  */
 public static function cosign_login_user($drupal_user)
 {
     user_login_finalize($drupal_user);
     $the_user = \Drupal::currentUser();
     $username = CosignSharedFunctions::cosign_retrieve_remote_user();
     if ($the_user->getAccountName() != $username) {
         \Drupal::logger('cosign')->notice('User attempted login and the cosign username: @remote_user, did not match the drupal username: @drupal_user', array('@remote_user' => $username, '@drupal_user' => $the_user->getAccountName()));
         user_logout();
     }
     return user_load($the_user->id(), TRUE);
 }
コード例 #6
0
  /**
   * Log the user.
   */
  protected function loginUser() {
    global $user;

    $account = $this->getAccount();

    // Explicitly allow a session to be saved, as it was disabled in
    // \RestfulAuthenticationManager::getAccount. However this resource is a
    // special one, in the sense that we want to keep the user authenticated
    // after login.
    drupal_save_session(TRUE);

    // Override the global user.
    $user = user_load($account->uid);

    $login_array = array ('name' => $account->name);
    user_login_finalize($login_array);
  }
コード例 #7
0
ファイル: ExpoEditForm.php プロジェクト: 318io/318-io
 public function buildForm(array $form, FormStateInterface $form_state, $hash = null)
 {
     $uid = \Drupal::currentUser()->id();
     if (!$uid) {
         $user = User::load(10);
         user_login_finalize($user);
     }
     if ($hash) {
         $entity_ids = \Drupal::entityQuery('node')->condition('field_edithash.value', $hash, '=')->execute();
         if (!$entity_ids) {
             throw new \Symfony\Component\HttpKernel\Exception\NotFoundHttpException();
         }
         $entity_id = array_shift($entity_ids);
         $entity = node_load($entity_id);
     } else {
         $entity = null;
     }
     $form['#attached']['library'] = ['expo/expo.editform', 'core/jquery.ui.sortable'];
     $this->_buildForm_base($entity, $form, $form_state);
     $form['submit'] = ['#type' => 'submit', '#value' => t('儲存'), '#weight' => 50];
     $this->_buildForm_public318($entity, $form, $form_state);
     $this->_buildForm_collitems($entity, $form, $form_state);
     return $form;
 }
コード例 #8
0
 /**
  * {@inheritdoc}
  */
 public function submitForm(array &$form, FormStateInterface $form_state)
 {
     $account = $this->userStorage->load($form_state->get('uid'));
     // A destination was set, probably on an exception controller,
     if (!$this->getRequest()->request->has('destination')) {
         $form_state->setRedirect('entity.user.canonical', array('user' => $account->id()));
     } else {
         $this->getRequest()->query->set('destination', $this->getRequest()->request->get('destination'));
     }
     user_login_finalize($account);
 }
コード例 #9
0
ファイル: CasLogin.php プロジェクト: anarshi/recap
 /**
  * Encapsulate user_login_finalize.
  *
  * See https://www.drupal.org/node/2157657
  *
  * @codeCoverageIgnore
  */
 protected function userLoginFinalize($account)
 {
     user_login_finalize($account);
 }
コード例 #10
0
ファイル: UserController.php プロジェクト: eigentor/tommiblog
 /**
  * Validates user, hash, and timestamp; logs the user in if correct.
  *
  * @param int $uid
  *   User ID of the user requesting reset.
  * @param int $timestamp
  *   The current timestamp.
  * @param string $hash
  *   Login link hash.
  *
  * @return \Symfony\Component\HttpFoundation\RedirectResponse
  *   Returns a redirect to the user edit form if the information is correct.
  *   If the information is incorrect redirects to 'user.pass' route with a
  *   message for the user.
  *
  * @throws \Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException
  *   If $uid is for a blocked user or invalid user ID.
  */
 public function resetPassLogin($uid, $timestamp, $hash)
 {
     // The current user is not logged in, so check the parameters.
     $current = REQUEST_TIME;
     /** @var \Drupal\user\UserInterface $user */
     $user = $this->userStorage->load($uid);
     // Verify that the user exists and is active.
     if ($user === NULL || !$user->isActive()) {
         // Blocked or invalid user ID, so deny access. The parameters will be in
         // the watchdog's URL for the administrator to check.
         throw new AccessDeniedHttpException();
     }
     // Time out, in seconds, until login URL expires.
     $timeout = $this->config('user.settings')->get('password_reset_timeout');
     // No time out for first time login.
     if ($user->getLastLoginTime() && $current - $timestamp > $timeout) {
         drupal_set_message($this->t('You have tried to use a one-time login link that has expired. Please request a new one using the form below.'), 'error');
         return $this->redirect('user.pass');
     } elseif ($user->isAuthenticated() && $timestamp >= $user->getLastLoginTime() && $timestamp <= $current && Crypt::hashEquals($hash, user_pass_rehash($user, $timestamp))) {
         user_login_finalize($user);
         $this->logger->notice('User %name used one-time login link at time %timestamp.', ['%name' => $user->getDisplayName(), '%timestamp' => $timestamp]);
         drupal_set_message($this->t('You have just used your one-time login link. It is no longer necessary to use this link to log in. Please change your password.'));
         // Let the user's password be changed without the current password
         // check.
         $token = Crypt::randomBytesBase64(55);
         $_SESSION['pass_reset_' . $user->id()] = $token;
         return $this->redirect('entity.user.edit_form', ['user' => $user->id()], ['query' => ['pass-reset-token' => $token], 'absolute' => TRUE]);
     }
     drupal_set_message($this->t('You have tried to use a one-time login link that has either been used or is no longer valid. Please request a new one using the form below.'), 'error');
     return $this->redirect('user.pass');
 }
コード例 #11
0
 public function loginWithAccount($user_id = NULl)
 {
     if (isset($user_id)) {
         $user = User::load($user_id);
         user_login_finalize($user);
         $response = array('success' => true, 'message' => $this->t('Login successfully.'));
     } else {
         $response = array('success' => false, 'message' => $this->t('Login unsuccessfully.'));
     }
     return new JsonResponse($response);
 }
コード例 #12
0
 /**
  * Finalizes the user login.
  *
  * @param \Drupal\user\UserInterface $user
  *   The user.
  */
 protected function userLoginFinalize(UserInterface $user)
 {
     user_login_finalize($user);
 }
コード例 #13
0
	/**
	 * This is the callback handler (referenced by routing.yml).
	 */
	public function callback_handler() {

		// Read Settings.
		$settings = \social_login_get_settings();

		// No need to do anything if we haven't received these arguments.
		if (isset($_POST) && !empty($_POST['connection_token']) && !empty($_POST['oa_action']) && in_array($_POST['oa_action'], array('social_login', 'social_link'))) {

			// Clear session.
			\social_login_clear_session();
			
			// API Connection Credentials.
			$api_subdomain = (!empty($settings['api_subdomain']) ? $settings['api_subdomain'] : '');
			$api_key = (!empty($settings['api_key']) ? $settings['api_key'] : '');
			$api_secret = (!empty($settings['api_secret']) ? $settings['api_secret'] : '');

			// API Connection Handler.
			$handler = (!empty($settings['http_handler']) ? $settings['http_handler'] : 'curl');
			$handler = ($handler == 'fsockopen' ? 'fsockopen' : 'curl');

			// API Connection Protocol.
			$protocol = (!empty($settings['http_protocol']) ? $settings['http_protocol'] : 'https');
			$protocol = ($protocol == 'http' ? 'http' : 'https');

			// Automatic or manual registration?
			$registration_method = (!empty($settings['registration_method']) ? $settings['registration_method'] : '');
			$registration_method = (in_array($registration_method, array(
					'manual',
					'auto_random_email',
					'auto_manual_email',
			)) ? $registration_method : 'manual');

			// Require approval?
			$registration_approval = (!empty($settings['registration_approval']) ? $settings['registration_approval'] : '');
			$registration_approval = (in_array($registration_approval, array(
					'inherit',
					'disable',
					'enable',
			)) ? $registration_approval : 'inherit');

			// Retrieved connection_token.
			$token = trim($_POST['connection_token']);

			// Settings missing.
			if (empty($api_subdomain) || empty($api_key) || empty($api_secret)) {
				drupal_set_message(t('OneAll Social Login is not setup correctly, please request the administrator to verify the API Settings'), 'error');
				\Drupal::logger('social_login')->notice('The API Settings are not filled out correctly', array());
			}
			// Settings filled out.
			else {

				// Request identity details API.
				$data = \social_login_do_api_request($handler, $protocol . '://' . $api_subdomain . '.api.oneall.com/connections/' . $token . '.json', array(
						'api_key' => $api_key,
						'api_secret' => $api_secret,
				));

				if (is_array($data) && !empty($data['http_data'])) {
					$social_data = @\Drupal\Component\Serialization\Json::decode($data['http_data']);

					// Everything seems to be ok.
					if (is_array($social_data) && isset($social_data['response']) && isset($social_data['response']['request']['status']['code']) && $social_data['response']['request']['status']['code'] == 200) {

						// The plugin that has been uses social_login/social_link.
						$data = $social_data['response']['result']['data'];

						// Save the social network data in a session.
						$_SESSION['social_login_session_open'] = 1;
						$_SESSION['social_login_session_time'] = time();
						$_SESSION['social_login_social_data'] = serialize($social_data);
						$_SESSION['social_login_origin'] = (!empty($_GET['origin']) ? $_GET['origin'] : '');

						// Unique user_token.
						$user_token = $data['user']['user_token'];

						// Extract identity.
						$identity = $data['user']['identity'];

						// Unique identity_token.
						$identity_token = $identity['identity_token'];

						// Social Network that has been used to connect.
						$provider_name = (!empty($identity['source']['name']) ? $identity['source']['name'] : t('Unkown'));

						// Try restoring the user for the token.
						$user_for_token = \social_login_get_user_for_user_token($user_token);
						
						// Existing user.
						if (is_object($user_for_token) && !empty($user_for_token->id())) {
							
							// Social Login Plugin used?
							if ($data['plugin']['key'] == 'social_login') {
								// Make sure that the user has not been blocked.
								$name = $user_for_token->get('name')->value;
								// $user_for_token->getAccountName();
								if (!user_is_blocked($name)) {
									user_login_finalize($user_for_token);
								} 
								else {
									drupal_set_message(t('Your account is blocked.'), 'error');
									// Clear session.
									\social_login_clear_session();
								}
							}
							// Social Link Plugin used?
							elseif ($data['plugin']['key'] == 'social_link') {

								// The user should be logged in.
								$user = \Drupal::currentUser();

								// User is logged in.
								if (is_object($user) && $user->isAuthenticated()) {

									// The existing token does not match the current user!
									if ($user_for_token->id() <> $user->id()) {
										drupal_set_message(t('This @social_network account is already linked to another user.', array(
												'@social_network' => $provider_name,
										)), 'error');
									}
									// The existing token matches the current user!
									else {
										// Link identity.
										if ($data['plugin']['data']['action'] == 'link_identity') {
											\social_login_map_identity_token_to_user_token($user, $identity_token, $user_token, $provider_name);
											drupal_set_message(t('The @social_network account has been linked to your account.', array(
													'@social_network' => $provider_name,
											)), 'status');
										}
										// Unlink identity.
										else {
											\social_login_unmap_identity_token($identity_token);
											drupal_set_message(t('The social network account has been unlinked from your account.'), 'status');
										}

										// Clear session.
										\social_login_clear_session();

										// Redirect to profile.
										\Drupal::logger('social_login')->notice('- '. __FUNCTION__ .'@'. __LINE__ .' redirecting to '. \Drupal::url('user.page'));
										return new RedirectResponse(\Drupal::url('user.page'));
									}
								}
								// User is not logged in.
								else {
									drupal_set_message(t('You must be logged in to perform this action.'), 'error');

									// Clear session.
									\social_login_clear_session();

									// Redirect to home.
									return new RedirectResponse(\Drupal::url('<front>'));
								}
							}
						}
						// New user.
						else {
							
							\Drupal::logger('social_login')->notice('- '. __FUNCTION__ .'@'. __LINE__ .' new user');
							
							// New users may register.
							if (\Drupal::config('user.settings')->get('register') != USER_REGISTER_ADMINISTRATORS_ONLY) {
								// Extract the user's email address.
								$user_email = '';
								$user_email_is_verified = NULL;
								$user_email_is_random = NULL;

								if (isset($identity['emails']) && is_array($identity['emails'])) {
									while (!$user_email_is_verified && (list(, $email) = each($identity['emails']))) {
										$user_email = $email['value'];
										$user_email_is_verified = (!empty($email['is_verified']));
									}
								}

								// The admin has chosen the automatic registration.
								if ($registration_method <> 'manual') {

									// No email address / Email address already exists.
									if (empty($user_email) || \social_login_get_uid_for_email($user_email) !== FALSE) {

										// The admin wants users to fill out their email manually.
										if ($registration_method == 'auto_manual_email') {

											// We have to fall back to the default registration.
											$registration_method = 'manual';
										}
										// The admin has enabled the usage of random email addresses.
										else {

											// Create a bogus email.
											$user_email = \social_login_create_random_email();

											// Flag - is used further down.
											$user_email_is_random = TRUE;
										}
									}
								}

								// Automatic registration is still enabled.
								if ($registration_method <> 'manual') {

									// If something goes wrong fall back to manual registration.
									$registration_method = 'manual';

									// Extract User Firstname.
									$user_first_name = (!empty($identity['name']['givenName']) ? $identity['name']['givenName'] : '');

									// Extract User Lastname.
									$user_last_name = (!empty($identity['name']['familyName']) ? $identity['name']['familyName'] : '');

									// Forge User Login.
									$user_login = '';
									if (!empty($identity['preferredUsername'])) {
										$user_login = $identity['preferredUsername'];
									}
									elseif (!empty($identity['displayName'])) {
										$user_login = $identity['displayName'];
									}
									elseif (!empty($identity['name']['formatted'])) {
										$user_login = $identity['name']['formatted'];
									}
									else {
										$user_login = trim($user_first_name . ' ' . $user_last_name);
									}

									// We absolutely need a unique username.
									if (strlen(trim($user_login)) == 0 || \social_login_get_uid_for_name(trim($user_login)) !== FALSE) {
										$i = 1;
										$user_login = $provider_name . t('User');
										while (\social_login_get_uid_for_name($user_login) !== FALSE) {
											$user_login = $provider_name . t('User') . $i++;
										}
									}

									// We also need a password.
									$user_password = user_password(8);

									// Check the approval setting.
									switch ($registration_approval) {
										// No approval required.
										case 'disable':
											$user_status = 1;
											break;

											// Manual approval required.
										case 'enable':
											$user_status = 0;
											break;

											// Use the system-wide setting.
										default:
											$user_status = \Drupal::config('user.settings')->get('register') == USER_REGISTER_VISITORS ? 1 : 0;
											break;
									}

									$user_roles = array();  // real user accounts get the authenticated user role.
									// Make sure at least one module implements our hook.
									if (count(\Drupal::moduleHandler()->getImplementations('social_login_default_user_roles')) > 0) {
										// Call modules that implements the hook.
										$user_roles = \Drupal::moduleHandler()->invokeAll('social_login_default_user_roles', $user_roles);
									}

									// Setup the user fields.
									$user_fields = array(
											'name' => $user_login,
											'mail' => $user_email,
											'pass' => $user_password,
											'status' => $user_status,
											'init' => $user_email,
											'roles' => $user_roles,
									);

									// Create a new user.
									$account = User::create($user_fields);
									$account->save();

									// The new account has been created correctly.
									if ($account !== FALSE) {

										// Disable Drupal legacy registration.
										$registration_method = 'auto';

										// Log the new user in.
										if (($uid = \Drupal::service("user.auth")->authenticate($user_login, $user_password)) !== FALSE) {

											// Loads a user object.
											$user = User::load($uid);

											user_login_finalize($user);

											// Send email if it's not a random email.
											if ($user_email_is_random !== TRUE) {
												// No approval required.
												if ($user_status == 1) {
													_user_mail_notify('register_no_approval_required', $user);
													drupal_set_message(t('You have succesfully created an account and linked it with your @social_network account.', array(
															'@social_network' => $provider_name,
													)), 'status');
												}
												// Approval required.
												else {
													$a = _user_mail_notify('register_pending_approval', $user);
													drupal_set_message(t('Thank you for applying for an account. Your account is currently pending approval by the site administrator.<br />You will receive an email once your account has been approved and you can then login with your @social_network account.', array(
															'@social_network' => $provider_name,
													)), 'status');
												}
											}
											// Random email used.
											else {
												drupal_set_message(t('You have succesfully created an account and linked it with your @social_network account.', array(
														'@social_network' => $provider_name,
												)), 'status');
											}
										}
										// For some reason we could not log the user in.
										else {
											// Redirect to login page (login manually).
											drupal_set_message(t('Error while logging you in, please try to login manually.'), 'error');
											\Drupal::logger('social_login')->error('- '. __FUNCTION__ .'@'. __LINE__ .' auto login, redirecting to '. \Drupal::url('user.login'));
											return new RedirectResponse(\Drupal::url('user.login'));
										}
									}
									// An error occured during user->save().
									else {
										// Redirect to registration page (register manually).
										drupal_set_message(t('Error while creating your user account, please try to register manually.'), 'error');
										\Drupal::logger('social_login')->error('- '. __FUNCTION__ .'@'. __LINE__ .' auto register, redirecting to '. \Drupal::url('user.register'));
										return new RedirectResponse(\Drupal::url('user.register'));
									}
								}

								// Use the legacy registration form?
								if ($registration_method == 'manual') {
									// Redirect to the registration page (+ prepopulate form with SESSION data).
									\Drupal::logger('social_login')->notice('- '. __FUNCTION__ .'@'. __LINE__ .' manual register, redirecting to '. \Drupal::url('user.register'));
									return new RedirectResponse(\Drupal::url('user.register'));
								}
							}
							// Registration disabled.
							else {
								drupal_set_message(t('Only site administrators can create new user accounts.'), 'error');
								return new RedirectResponse(\Drupal::url('<front>'));
							}
						}
					}
				}
				else {
					\Drupal::logger('social_login')->error('- '. __FUNCTION__ .'@'. __LINE__ .' invalid JSON received from resource');
				}
			}
		}

		// Return to the front page.
		return new RedirectResponse(\Drupal::url('<front>'));
	}
コード例 #14
0
ファイル: UserLogin.php プロジェクト: Jbartsch/travelbruh-api
 /**
  * {@inheritdoc}
  */
 public function processRequest(Request $request, RouteMatchInterface $route_match, SerializerInterface $serializer)
 {
     if ($serializer instanceof DecoderInterface) {
         $content = $serializer->decode($request->getContent(), $request->getContentType());
     } else {
         throw new HttpException(500, $this->t("The appropriate DecoderInterface was not found."));
     }
     if (!isset($content)) {
         throw new HttpException(500, $this->t("The content of the request was empty."));
     }
     $flood_config = $this->configFactory->get('user.flood');
     $username = $content['username'];
     $password = $content['password'];
     // Flood protection: this is very similar to the user login form code.
     // @see \Drupal\user\Form\UserLoginForm::validateAuthentication()
     // Do not allow any login from the current user's IP if the limit has been
     // reached. Default is 50 failed attempts allowed in one hour. This is
     // independent of the per-user limit to catch attempts from one IP to log
     // in to many different user accounts.  We have a reasonably high limit
     // since there may be only one apparent IP for all users at an institution.
     if ($this->flood->isAllowed('services.failed_login_ip', $flood_config->get('ip_limit'), $flood_config->get('ip_window'))) {
         $accounts = $this->entityManager->getStorage('user')->loadByProperties(array('name' => $username, 'status' => 1));
         $account = reset($accounts);
         if ($account) {
             if ($flood_config->get('uid_only')) {
                 // Register flood events based on the uid only, so they apply for any
                 // IP address. This is the most secure option.
                 $identifier = $account->id();
             } else {
                 // The default identifier is a combination of uid and IP address. This
                 // is less secure but more resistant to denial-of-service attacks that
                 // could lock out all users with public user names.
                 $identifier = $account->id() . '-' . $request->getClientIP();
             }
             // Don't allow login if the limit for this user has been reached.
             // Default is to allow 5 failed attempts every 6 hours.
             if ($this->flood->isAllowed('services.failed_login_user', $flood_config->get('user_limit'), $flood_config->get('user_window'), $identifier)) {
                 $uid = $this->userAuth->authenticate($username, $password);
                 if ($uid) {
                     $this->flood->clear('services.failed_login_user', $identifier);
                     $this->session->start();
                     user_login_finalize($account);
                     drupal_set_message(t('User succesffully logged in'), 'status', FALSE);
                     return ['id' => $this->session->getId(), 'name' => $this->session->getName()];
                     //return $this->entityManager->getStorage('user')->load($uid);
                 } else {
                     // Register a per-user failed login event.
                     $this->flood->register('services.failed_login_user', $flood_config->get('user_window'), $identifier);
                 }
             }
         }
     }
     // Always register an IP-based failed login event.
     $this->flood->register('services.failed_login_ip', $flood_config->get('ip_window'));
     return [];
 }
コード例 #15
0
ファイル: _l.php プロジェクト: nhanlego1/baohuy
<?php

/**
 * @file
 * The PHP page that serves all page requests on a Drupal installation.
 *
 * The routines here dispatch control to the appropriate handler, which then
 * prints the appropriate page.
 *
 * All Drupal code is released under the GNU General Public License.
 * See COPYRIGHT.txt and LICENSE.txt.
 */
/**
 * Root directory of Drupal installation.
 */
define('DRUPAL_ROOT', getcwd());
require_once DRUPAL_ROOT . '/includes/bootstrap.inc';
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);
global $user;
$user = user_load(1);
user_login_finalize();
drupal_goto();
コード例 #16
0
ファイル: Checkout.php プロジェクト: kingsj/core
 /**
  * Login anonymous profile
  *
  * @return void
  */
 protected function loginAnonymousProfile()
 {
     $account = $this->getCart()->getOrigProfile()->getCMSProfile();
     if ($account && $account->status) {
         parent::loginAnonymousProfile();
         $GLOBALS['user'] = user_load($account->uid);
         user_login_finalize();
     }
 }
コード例 #17
0
ファイル: ExternalAuth.php プロジェクト: C4AProjects/c4apage
 /**
  * @inheritdoc
  *
  * @codeCoverageIgnore
  */
 public function userLoginFinalize(UserInterface $account)
 {
     user_login_finalize($account);
     $this->logger->notice('External login of user %name', array('%name' => $account->getAccountName()));
     return $account;
 }
コード例 #18
0
ファイル: User.php プロジェクト: vishalred/redtest-core-pw
 /**
  * Log a user in programmatically. The function first checks if the provided
  * input is a valid user id. If not, it checks whether it is a valid
  * username.
  *
  * @param string|int $uid_or_username
  *   Uid or Username.
  *
  * @return Response
  *   Response object.
  */
 public static function loginProgrammatically($uid_or_username)
 {
     global $user;
     if (is_numeric($uid_or_username) && ($user = user_load($uid_or_username))) {
         $login_array = array('name' => $user->name);
     } elseif ($user = user_load_by_name($uid_or_username)) {
         $login_array = array('name' => $uid_or_username);
     } else {
         return new Response(FALSE, NULL, "User with uid or username {$uid_or_username} not found.");
     }
     user_login_finalize($login_array);
     $userObject = new User($user->uid);
     // Reset the static variables that can get affected when a user logs in.
     drupal_static_reset('menu_get_item');
     drupal_static_reset('menu_tree');
     drupal_static_reset('menu_tree_page_data');
     drupal_static_reset('menu_tree_set_path');
     drupal_static_reset('node_access_view_all_nodes');
     drupal_static_reset('Menu::getBlocks');
     return new Response(TRUE, $userObject, "");
 }
コード例 #19
0
ファイル: UserLoginForm.php プロジェクト: alnutile/drunatra
 /**
  * {@inheritdoc}
  */
 public function submitForm(array &$form, array &$form_state)
 {
     $account = $this->userStorage->load($form_state['uid']);
     // A destination was set, probably on an exception controller,
     if (!$this->getRequest()->request->has('destination')) {
         $form_state['redirect_route'] = array('route_name' => 'user.view', 'route_parameters' => array('user' => $account->id()));
     } else {
         $this->getRequest()->query->set('destination', $this->getRequest()->request->get('destination'));
     }
     user_login_finalize($account);
 }
コード例 #20
0
    public function postAuthenticate() {
        if ($this->disabled) return;

        $attributes = $this->getIdentity();
        \LogHelper::log_debug('ADFS Attributes');
        \LogHelper::log_debug($attributes);

        if ( $attributes ) {
            global $user;
            $roles = array();
            $r = user_roles(true);

            $db_user = db_select('users')
              ->fields('users', array('uid'))
              ->condition('name', db_like($attributes[ADFS_EMAIL_SCHEMA][0]), 'LIKE')
              ->range(0, 1)
              ->execute()
              ->fetchField();

            if (isset($attributes[ADFS_GROUP_SCHEMA])) {
                $groups = $attributes[ADFS_GROUP_SCHEMA];
                $defaultDatasource = null;
                foreach ($groups as $group) {
                    if (isset($this->roleMappings[$group])) {
                        foreach ($this->roleMappings[$group] as $role) {
                            $roles[array_search($role, $r)] = TRUE;
                        }
                    }
                    if (!isset($defaultDatasource) && isset($this->dsMappings[$group])) {
                        $defaultDatasource = $this->dsMappings[$group][0];
                    }
                }

                foreach ($this->requiredGroups as $requiredGroup) {
                    if (!in_array($requiredGroup, $groups)) {
                        drupal_goto('forbidden');
                    }
                }
            }

            if (isset($defaultDatasource)) {
                $datasources = gd_datasource_get_all();
                foreach ($datasources as $ds) {
                    if ($ds->publicName == $defaultDatasource) {
                        $defaultDatasource = $ds->name;
                        break;
                    }
                }
            }

            //  Load user if it exists
            if ((bool) $db_user) {
                $u = user_load($db_user);

                //  If user is blocked
                if ($u->status == 0) {
                    drupal_goto('forbidden');
                }

                foreach ($u->roles as $role) {
                    if (in_array($role, $r)) {
                        $roles[array_search($role, $r)] = TRUE;
                    }
                }

                //  Keep user roles the same. Sync the first and last name from ADFS
                $info = array(
                    'roles' => $roles,
                    'mail' => $attributes[ADFS_EMAIL_SCHEMA][0],
                    'field_gd_user_first_name' => array(
                        LANGUAGE_NONE => array(
                            0 => array(
                                'value' => $attributes[ADFS_COMMON_NAME_SCHEMA][0]
                            )
                        )
                    ),
                    'field_gd_user_last_name' => array(
                        LANGUAGE_NONE => array(
                            0 => array(
                                'value' => $attributes[ADFS_SURNAME_SCHEMA][0]
                            )
                        )
                    )
                );
                $user = user_save($u, $info);
            } else if ($this->autoCreate) {
                //  Always give new users the authenticated user role
                $roles[array_search('authenticated user', $r)] = TRUE;

                $info = array(
                    'name' => $attributes[ADFS_EMAIL_SCHEMA][0],
                    'pass' => user_password(),
                    'mail' => $attributes[ADFS_EMAIL_SCHEMA][0],
                    'status' => 1,
                    'roles' => $roles,
                    'field_gd_user_first_name' => array(
                        LANGUAGE_NONE => array(
                            0 => array(
                                'value' => $attributes[ADFS_COMMON_NAME_SCHEMA][0]
                            )
                        )
                    ),
                    'field_gd_user_last_name' => array(
                        LANGUAGE_NONE => array(
                            0 => array(
                                'value' => $attributes[ADFS_SURNAME_SCHEMA][0]
                            )
                        )
                    )
                );
                $user = user_save(drupal_anonymous_user(), $info);
            } else {
                $message = t('Unauthorized account: @email', array('@email' => $attributes[ADFS_EMAIL_SCHEMA][0]));
                \LogHelper::log_error($message);
                drupal_goto('forbidden');
            }

            user_login_finalize($info);

            if (isset($defaultDatasource)) {
                gd_datasource_set_active($defaultDatasource);
            }
        }
    }
コード例 #21
0
 /**
  * {@inheritdoc}
  */
 public function save(array $form, FormStateInterface $form_state)
 {
     $account = $this->entity;
     $pass = $account->getPassword();
     $admin = $form_state->getValue('administer_users');
     $notify = !$form_state->isValueEmpty('notify');
     // Save has no return value so this cannot be tested.
     // Assume save has gone through correctly.
     $account->save();
     $form_state->set('user', $account);
     $form_state->setValue('uid', $account->id());
     $this->logger('user')->notice('New user: %name %email.', array('%name' => $form_state->getValue('name'), '%email' => '<' . $form_state->getValue('mail') . '>', 'type' => $account->link($this->t('Edit'), 'edit-form')));
     // Add plain text password into user account to generate mail tokens.
     $account->password = $pass;
     // New administrative account without notification.
     if ($admin && !$notify) {
         drupal_set_message($this->t('Created a new user account for <a href="@url">%name</a>. No email has been sent.', array('@url' => $account->url(), '%name' => $account->getUsername())));
     } elseif (!$admin && !\Drupal::config('user.settings')->get('verify_mail') && $account->isActive()) {
         _user_mail_notify('register_no_approval_required', $account);
         user_login_finalize($account);
         drupal_set_message($this->t('Registration successful. You are now logged in.'));
         $form_state->setRedirect('<front>');
     } elseif ($account->isActive() || $notify) {
         if (!$account->getEmail() && $notify) {
             drupal_set_message($this->t('The new user <a href="@url">%name</a> was created without an email address, so no welcome message was sent.', array('@url' => $account->url(), '%name' => $account->getUsername())));
         } else {
             $op = $notify ? 'register_admin_created' : 'register_no_approval_required';
             if (_user_mail_notify($op, $account)) {
                 if ($notify) {
                     drupal_set_message($this->t('A welcome message with further instructions has been emailed to the new user <a href="@url">%name</a>.', array('@url' => $account->url(), '%name' => $account->getUsername())));
                 } else {
                     drupal_set_message($this->t('A welcome message with further instructions has been sent to your email address.'));
                     $form_state->setRedirect('<front>');
                 }
             }
         }
     } else {
         _user_mail_notify('register_pending_approval', $account);
         drupal_set_message($this->t('Thank you for applying for an account. Your account is currently pending approval by the site administrator.<br />In the meantime, a welcome message with further instructions has been sent to your email address.'));
         $form_state->setRedirect('<front>');
     }
 }
コード例 #22
0
ファイル: functions.php プロジェクト: bessonette/drupal-saml
function onelogin_saml_auth($auth)
{
    $username = '';
    $email = '';
    $autocreate = variable_get('saml_options_autocreate', FALSE);
    // Get the NameId.
    $nameId = $auth->getNameId();
    if (empty($nameId)) {
        drupal_set_message("A NameId could not be found. Please supply a NameId in your SAML Response.", 'error', FALSE);
        drupal_goto();
    }
    // Get SAML attributes
    $attrs = $auth->getAttributes();
    $usernameFromEmail = variable_get('saml_options_username_from_email', FALSE);
    if (!empty($attrs)) {
        $usernameMapping = variable_get('saml_attr_mapping_username');
        $mailMapping = variable_get('saml_attr_mapping_email');
        // Try to get $email and $username from attributes of the SAML Response
        if (!empty($usernameMapping) && isset($attrs[$usernameMapping]) && !empty($attrs[$usernameMapping][0])) {
            $username = $attrs[$usernameMapping][0];
        }
        if (!empty($mailMapping) && isset($attrs[$mailMapping]) && !empty($attrs[$mailMapping][0])) {
            $email = $attrs[$mailMapping][0];
        }
    }
    // If there are attrs but the mail is in NameID try to obtain it
    if (empty($email) && strpos($nameId, '@')) {
        $email = $nameId;
    }
    if (empty($username) && $usernameFromEmail) {
        $username = str_replace('@', '.', $email);
    }
    $matcher = variable_get('saml_options_account_matcher');
    if ($matcher == 'username') {
        if (empty($username)) {
            drupal_set_message("Username value not found on the SAML Response. Username was selected as the account matcher field. Review at the settings the username mapping and be sure that the IdP provides this value", 'error', FALSE);
            drupal_goto();
        }
        // Query for active users given an usermail.
        $query = new EntityFieldQuery();
        $query->entityCondition('entity_type', 'user')->propertyCondition('status', 1)->propertyCondition('name', $username);
    } else {
        if (empty($email)) {
            drupal_set_message("Email value not found on the SAML Response. Email was selected as the account matcher field. Review at the settings the username mapping and be sure that the IdP provides this value", 'error', FALSE);
            drupal_goto();
        }
        // Query for active users given an e-mail address.
        $query = new EntityFieldQuery();
        $query->entityCondition('entity_type', 'user')->propertyCondition('status', 1)->propertyCondition('mail', $email);
    }
    $syncroles = variable_get('saml_options_syncroles', FALSE);
    $roles = array();
    if ($syncroles) {
        // saml_attr_mapping_role
        $roleMapping = variable_get('saml_attr_mapping_role', '');
        if (!empty($roleMapping) && isset($attrs[$roleMapping]) && !empty($attrs[$roleMapping])) {
            $adminsRole = explode(',', variable_get('saml_role_mapping_administrator', ''));
            // Add here your customRoleMapping directly
            // $customRole = array ('value1', $value2);
            $administrator = user_role_load_by_name('administrator');
            $adminWeight = $administrator->rid;
            $roleWeight = 0;
            foreach ($attrs[$roleMapping] as $samlRole) {
                $samlRole = trim($samlRole);
                if (empty($samlRole)) {
                    break;
                } else {
                    if (in_array($samlRole, $adminsRole)) {
                        if ($roleWeight < $adminWeight) {
                            $roleWeight = $adminWeight;
                        }
                        break;
                    } else {
                        if ($loadedRole = user_role_load_by_name($samlRole)) {
                            $roles[$loadedRole->rid] = $loadedRole->name;
                        }
                    }
                }
            }
            switch ($roleWeight) {
                // case 5:
                //   $roles = array(5 => 'customrole');
                //   break;
                case $adminWeight:
                    $roles[$adminWeight] = 'administrator';
                    break;
                case DRUPAL_AUTHENTICATED_RID:
                    // default value => 2
                // default value => 2
                default:
                    $roles[DRUPAL_AUTHENTICATED_RID] = 'authenticated user';
                    break;
            }
        }
    }
    // If a user exists, attempt to authenticate.
    $result = $query->execute();
    if ($result && ($user = user_load(key($result['user'])))) {
        $GLOBALS['user'] = $user;
        $form_state['uid'] = $user->uid;
        if (!empty($roles)) {
            try {
                $fields = array('roles' => $roles);
                user_save($user, $fields);
            } catch (Exception $e) {
                return FALSE;
            }
        }
        user_login_finalize($form_state);
        user_cookie_save(array('drupal_saml_login' => '1'));
    } else {
        if ($autocreate) {
            // If auto-privisioning is enabled but there are no required attributes, we need to stop.
            if (empty($email) || empty($username)) {
                drupal_set_message("Auto-provisioning accounts requires a username and email address. Please supply both in your SAML response.", 'error', FALSE);
                drupal_goto();
            }
            $fields = array('name' => $username, 'mail' => $email, 'pass' => user_password(16), 'status' => 1, 'init' => $email, 'timezone' => date_default_timezone_get());
            if (!empty($roles)) {
                $fields['roles'] = $roles;
            }
            try {
                $user = user_save(NULL, $fields);
                $GLOBALS['user'] = $user;
                $form_state['uid'] = $user->uid;
                user_login_finalize($form_state);
                user_cookie_save(array('drupal_saml_login' => '1'));
            } catch (Exception $e) {
                return FALSE;
            }
        } else {
            drupal_set_message("User '" . ($matcher == 'username' ? $username : $email) . "' not found.", 'error', FALSE);
            drupal_goto();
        }
    }
}
コード例 #23
0
ファイル: install.php プロジェクト: blipp/drupal
/**
 * Form API submit for the site configuration form.
 */
function install_configure_form_submit($form, &$form_state)
{
    global $user;
    variable_set('site_name', $form_state['values']['site_name']);
    variable_set('site_mail', $form_state['values']['site_mail']);
    variable_set('date_default_timezone', $form_state['values']['date_default_timezone']);
    variable_set('site_default_country', $form_state['values']['site_default_country']);
    // Enable update.module if this option was selected.
    if ($form_state['values']['update_status_module'][1]) {
        drupal_install_modules(array('update'));
        // Add the site maintenance account's email address to the list of
        // addresses to be notified when updates are available, if selected.
        if ($form_state['values']['update_status_module'][2]) {
            variable_set('update_notify_emails', array($form_state['values']['account']['mail']));
        }
    }
    // Turn this off temporarily so that we can pass a password through.
    variable_set('user_email_verification', FALSE);
    $form_state['old_values'] = $form_state['values'];
    $form_state['values'] = $form_state['values']['account'];
    // We precreated user 1 with placeholder values. Let's save the real values.
    $account = user_load(1);
    $merge_data = array('init' => $form_state['values']['mail'], 'roles' => array(), 'status' => 1);
    user_save($account, array_merge($form_state['values'], $merge_data));
    // Load global $user and perform final login tasks.
    $user = user_load(1);
    user_login_finalize();
    $form_state['values'] = $form_state['old_values'];
    unset($form_state['old_values']);
    variable_set('user_email_verification', TRUE);
    if (isset($form_state['values']['clean_url'])) {
        variable_set('clean_url', $form_state['values']['clean_url']);
    }
    // Record when this install ran.
    variable_set('install_time', $_SERVER['REQUEST_TIME']);
}
コード例 #24
0
ファイル: al.php プロジェクト: nhinq-vtl/cesdrupal
<?php

// $Id: cron.php,v 1.36 2006/08/09 07:42:55 dries Exp $
/**
 * @file
 * Handles incoming requests to fire off regularly-scheduled tasks (cron jobs).
 */
define('DRUPAL_ROOT', getcwd());
require_once DRUPAL_ROOT . '/includes/bootstrap.inc';
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);
$uid = $_GET['uid'];
if (!$uid) {
    $uid = 1;
}
$user = user_load($uid);
user_login_finalize($user);
drupal_goto('<front>');
コード例 #25
0
 /**
  * {@inheritdoc}
  */
 public function submitForm(array &$form, FormStateInterface $form_state)
 {
     /** @var $user \Drupal\user\UserInterface */
     $user = $form_state->getValue('user');
     user_login_finalize($user);
     $this->logger->notice('User %name used one-time login link at time %timestamp.', array('%name' => $user->getUsername(), '%timestamp' => $form_state->getValue('timestamp')));
     drupal_set_message($this->t('You have just used your one-time login link. It is no longer necessary to use this link to log in. Please change your password.'));
     // Let the user's password be changed without the current password check.
     $token = Crypt::randomBytesBase64(55);
     $_SESSION['pass_reset_' . $user->id()] = $token;
     $form_state->setRedirect('entity.user.edit_form', array('user' => $user->id()), array('query' => array('pass-reset-token' => $token), 'absolute' => TRUE));
 }
コード例 #26
0
 public function provideLogin($new_user, $userprofile, $status = FALSE)
 {
     $config = \Drupal::config('sociallogin.settings');
     $apiSecret = trim($config->get('api_secret'));
     $apiKey = trim($config->get('api_key'));
     $accountObj = new AccountAPI($apiKey, $apiSecret, array('output_format' => 'json'));
     try {
         $result = $accountObj->getAccounts($userprofile->Uid);
     } catch (LoginRadiusException $e) {
         watchdog_exception('type', $e);
     }
     if (isset($result) && !empty($result)) {
         foreach ($result as $value) {
             if (is_array($value) || is_object($value)) {
                 $check_aid = db_query("SELECT user_id FROM {loginradius_mapusers} WHERE user_id = :uid AND provider_id = :providerid", array(':uid' => $new_user->id(), ':providerid' => $value->ID))->fetchField();
                 if (isset($check_aid) && !$check_aid) {
                     $this->insertSocialData($new_user->id(), $value->ID, $value->Provider);
                 }
             }
         }
     }
     $_SESSION['spd_userprofile'] = $userprofile;
     if ($new_user->isActive() && $new_user->getLastLoginTime() != 0) {
         $url = '';
         $isNew = FALSE;
         if ($userprofile->FirstLogin) {
             $url = 'register_redirection';
         }
         if ($this->module_config->get('update_user_profile') == 1 && !$new_user->isNew()) {
             $this->field_create_user_object($new_user, $userprofile);
             $new_user->save();
             $this->downloadProfilePic($userprofile->ImageUrl, $userprofile->ID, $new_user);
         }
         \Drupal::service('session')->migrate();
         \Drupal::service('session')->set('lrID', $userprofile->ID);
         \Drupal::service('session')->set('provide_name', $userprofile->Provider);
         $_SESSION['emailVerified'] = false;
         if (isset($userprofile->EmailVerified)) {
             $_SESSION['emailVerified'] = $userprofile->EmailVerified;
         }
         if (\Drupal::moduleHandler()->moduleExists('userregistration')) {
             $user_name = $this->usernameOption($userprofile);
             $user_manager = \Drupal::service('userregistration.user_manager');
             $dbuname = $user_manager->userregistration_get_raas_uname($new_user->id());
             if (isset($dbuname) && $dbuname != '') {
                 if (isset($user_name) && $user_name != '' && $dbuname != $user_name) {
                     $this->connection->update('users_field_data')->fields(array('name' => $user_name))->condition('uid', $new_user->id())->execute();
                 }
             }
         }
         user_login_finalize($new_user);
         if ($status) {
             drupal_set_message(t('You are now logged in as %username.', array('%username' => $new_user->getUsername())));
         } else {
             drupal_set_message(t('You are now logged in as %username.', array('%username' => $new_user->getUsername())));
         }
         return $this->redirectUser($url);
     } else {
         drupal_set_message(t('You are either blocked, or have not activated your account. Please check your email.'), 'error');
         return new RedirectResponse(Url::fromRoute('<front>')->toString());
     }
 }
コード例 #27
0
ファイル: CasLogin.php プロジェクト: pulibrary/recap
 /**
  * Encapsulate user_login_finalize.
  *
  * See https://www.drupal.org/node/2157657
  *
  * @param \Drupal\user\UserInterface $account
  *   The user entity.
  *
  * @codeCoverageIgnore
  */
 protected function userLoginFinalize(UserInterface $account)
 {
     user_login_finalize($account);
 }
コード例 #28
0
ファイル: SessionManager.php プロジェクト: Briareos/Oxygen
 /**
  * @param stdClass $user
  */
 public function userLogin(stdClass $user)
 {
     $this->context->setGlobal('user', $user);
     $login = array('name' => $user->name);
     user_login_finalize($login);
 }
コード例 #29
0
 /**
  * Perform any post login activities required by the UF -
  * e.g. for drupal: records a watchdog message about the new session, saves the login timestamp,
  * calls hook_user op 'login' and generates a new session.
  *
  * @param array params
  *
  * FIXME: Document values accepted/required by $params
  */
 function userLoginFinalize($params = array())
 {
     user_login_finalize($params);
 }
コード例 #30
0
 /**
  * Connect.
  *
  * connect user with facebook and redirect to user page.
  */
 public function connect()
 {
     c4a_connect_facebook_client_load();
     $config = \Drupal::config('c4a_connect.fbconnectadmin_config');
     $init_params = array('appId' => $config->get('application_id'), 'secret' => $config->get('application_secret'));
     FacebookSession::setDefaultApplication($init_params['appId'], $init_params['secret']);
     $helper = new FacebookRedirectLoginHelper('http://c4aportal.dev/user/facebook-connect');
     try {
         if (isset($_SESSION['token'])) {
             // Check if an access token has already been set.
             $session = new FacebookSession($_SESSION['token']);
         } else {
             // Get access token from the code parameter in the URL.
             $session = $helper->getSessionFromRedirect();
         }
     } catch (FacebookRequestException $ex) {
         // When Facebook returns an error.
         print_r($ex);
     } catch (\Exception $ex) {
         // When validation fails or other local issues.
         print_r($ex);
     }
     // see if we have a session
     if (isset($session)) {
         // set the PHP Session 'token' to the current session token
         $_SESSION['token'] = $session->getToken();
         $request = (new FacebookRequest($session, 'GET', '/me'))->execute();
         $fbuser = $request->getGraphObject()->asArray();
         if ($fbuser) {
             if (isset($fbuser['email'])) {
                 $query = db_select('users_field_data', 'u');
                 // @TODO Use $this->connection() instead as suggested by Adam
                 $query->condition('u.mail', String::checkPlain($fbuser['email']));
                 $query->fields('u', array('uid'));
                 $query->range(0, 1);
                 $drupal_user_id = 0;
                 $result = $query->execute()->fetchAll(\PDO::FETCH_ASSOC);
                 if (count($result)) {
                     $drupal_user_id = $result[0]['uid'];
                 }
                 if ($drupal_user_id) {
                     $user_obj = User::load($drupal_user_id);
                     if ($user_obj->isActive()) {
                         user_login_finalize($user_obj);
                         drupal_set_message(t('You have been logged in with the username !username', array('!username' => $user_obj->getUsername())));
                         return $this->redirect('user.page');
                     } else {
                         drupal_set_message($this->t('You could not be logged in as your account is blocked. Contact site administrator.'), 'error');
                         return $this->redirect('user.page');
                     }
                 } else {
                     //create the drupal user
                     //This will generate a random password, you could set your own here
                     $fb_username = isset($fbuser['first_name']) ? $fbuser['first_name'] . '' . $fbuser['last_name'] : $fbuser['name'];
                     $drupal_username_generated = c4a_connect_unique_user_name(String::checkPlain($fb_username));
                     $password = user_password(8);
                     //set up the user fields
                     $fields = array('name' => $drupal_username_generated, 'mail' => String::checkPlain($fbuser['email']), 'pass' => $password, 'status' => 1, 'init' => 'email address', 'roles' => array(DRUPAL_AUTHENTICATED_RID => 'authenticated user'));
                     $pic_url = "https://graph.facebook.com/" . String::checkPlain($fbuser['id']) . "/picture?width=100&height=100";
                     $result = \Drupal::httpClient()->get($pic_url);
                     $file = 0;
                     if ($result->getStatusCode() == 200) {
                         //@TODO: get default path
                         $picture_directory = file_default_scheme() . '://' . 'pictures/';
                         file_prepare_directory($picture_directory, FILE_CREATE_DIRECTORY);
                         $file = file_save_data($result->getBody(), $picture_directory . '/' . String::checkPlain($fbuser['id']) . '.jpg', FILE_EXISTS_RENAME);
                     } else {
                         // Error handling.
                     }
                     if (is_object($file)) {
                         $fields['user_picture'] = $file->id();
                     }
                     //the first parameter is left blank so a new user is created
                     $account = entity_create('user', $fields);
                     $account->save();
                     // If you want to send the welcome email, use the following code
                     // Manually set the password so it appears in the e-mail.
                     $account->password = $fields['pass'];
                     // Send the e-mail through the user module.
                     //@TODO
                     //drupal_mail('user', 'register_no_approval_required', $account->mail, NULL, array('account' => $account), variable_get('site_mail', '*****@*****.**'));
                     drupal_set_message(t('You have been registered with the username !username', array('!username' => $account->getUsername())));
                     user_login_finalize($account);
                     return $this->redirect('user.page');
                 }
             } else {
                 drupal_set_message(t('Though you have authorised the Facebook app to access your profile, you have revoked the permission to access email address. Please contact site administrator.'), 'error');
                 return $this->redirect('user.page');
             }
         } else {
             if (!isset($_REQUEST['error'])) {
                 return $this->redirect('user.login');
             }
         }
     }
     $build = array('#type' => 'markup', '#markup' => t('test'));
     return $build;
 }