$scope = get_input('scope');
if ($scope) {
    $uid = (int) $ha_session->isAuthenticated($provider);
    if (empty($_SESSION["HA:{$provider_name}:last_scope:{$uid}"])) {
        $_SESSION["HA:{$provider_name}:last_scope:{$uid}"] = 'default';
    }
    if ($_SESSION["HA:{$provider_name}:last_scope:{$uid}"] != $scope) {
        // Check if scope has been explicitly required
        // Logout the user, and reauthenticate with the requested scope
        $config = $ha_session->getConfig();
        if (!empty($config['providers'][$provider_name])) {
            $config['providers'][$provider_name]['scope'] = urldecode($scope);
        }
        $ha_session->setConfig($config);
        $ha_session->getAdapter($provider)->logout();
        $ha_session->save();
        $_SESSION["HA:{$provider_name}:last_scope:{$uid}"] = $scope;
    } else {
        $_SESSION["HA:{$provider_name}:last_scope:{$uid}"] = 'default';
    }
}
$save_auth = $user ? true : false;
$profile = $ha_session->authenticate($provider, $save_auth);
if (!$profile) {
    echo elgg_view('resources/hybridauth/error', array('provider' => $provider->getName(), 'error' => get_input('error')));
    return;
}
$elgg_forward_url = get_input('elgg_forward_url', $_SESSION['last_forward_from']);
if ($elgg_forward_url) {
    $forward_url = urldecode($elgg_forward_url);
} else {