/*
Login with OAuth requires the priming of "pending credentials" on the server to receive a secret
496919
private void sendOAuthHTTPRequest(String serviceName, String accessToken, String credentialToken, Response.Listener listener) {
        RequestQueue queue = Volley.newRequestQueue(mContext);
        String url = "http://" + getServerHostname() + ":" + getServerPort() + "/_oauth/" + serviceName + "/";
        //as far as I know, Facebook is the only one that only returns a long-lived token on mobile login
        String params;
        if (accessTokenServices.contains(serviceName)) {
            params = "?accessToken=" + accessToken + "&state=" + generateState(credentialToken);
        } else {
            params = "?code=" + accessToken + "&state=" + generateState(credentialToken);
        }

        StringRequest request = new StringRequest(Request.Method.GET, url + params,
                listener, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                error.printStackTrace();
                if (BuildConfig.DEBUG) {
                    log.debug("If you're getting a weird error, " +
                            "this could be because you haven't configured " +
                            "your server for ddp loginWithOAuth yet. " +
                            "For Facebook login, remove accounts-facebook " +
                            "and add jasperlu:accounts-facebook-ddp instead.");
                }
            }
        });

        queue.add(request);
    }
1061839
function getAuth() {
    if (!auth.key || auth.key.indexOf("goes-here") !== -1) {
        var err = new Error("API key missing");
        out.error(err.message);
        throw err;
    }
    if (!auth.secret || auth.secret.indexOf("goes-here") !== -1) {
        var err = new Error("API secret missing");
        out.error(err.message);
        throw err;
    }
    return auth;
}
72601
async function runExample() {
	try {

		// Test http://example.com/
		const result = await pa11y('http://example.com/', {

			// Run some actions before the tests
			actions: [
				'set field #username to exampleUser',
				'set field #password to password1234',
				'click element #submit',
				'wait for url to be http://example.com/myaccount'
			],

			// Log what's happening to the console
			log: {
				debug: console.log,
				error: console.error,
				info: console.log
			}

		});

		// Output the raw result object
		console.log(result);

	} catch (error) {

		// Output an error if it occurred
		console.error(error.message);

	}
}
638361
function __process_authorization_header_for_user(request_params) {
    return new Promise(async (resolve, reject) => {
        try {
            const user_account_id = await user_info_endpoint
                .user_account_registrar_module
                .get_user_account_id_for_credentials(request_params.authorization_credentials.username, request_params.authorization_credentials.password);
            return resolve(request_params);
        } catch (err) {
            return reject(err);
        }
    });
}
1257403
def _login(self, username, password, client_id, client_secret):
        """"""
        url = self.api_url + self.auth_token_url
        auth_string = '%s:%s' % (client_id, client_secret)
        authorization = base64.b64encode(auth_string.encode()).decode()
        headers = {
            'Authorization': "Basic " + authorization,
            'Content-Type': "application/x-www-form-urlencoded"
        }
        params = {
            'username': str(username),
            'password': str(password),
            # 'client_id': client_id,
            'grant_type': 'password',
            'response_type': 'token'
        }
        return self.session.post(url, params=params, headers=headers)
834246
function authenticateClient (req, res, next) {
  Client.authenticate(req, function (err, client) {
    if (err) { return next(err) }
    req.client = client
    next()
  })
}
1184392
@Override
	public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response)
			throws IOException {
		final String requestURI = request.getRequestURI();
		UserAuthentication userAuth = null;
		User user = null;

		if (requestURI.endsWith(OPENID_ACTION)) {
			Authentication oidAuth = super.attemptAuthentication(request, response);

			if (oidAuth == null) {
				// hang on... redirecting to openid provider
				return null;
			} else {
				//success!
				AuthenticatedUserDetails userDetails = (AuthenticatedUserDetails) oidAuth.getPrincipal();
				userAuth = new UserAuthentication(userDetails);
				user = userDetails.getUser();
			}
		}

		return SecurityUtils.checkIfActive(userAuth, user, true);
	}
1289130
def login_with_oauth
      result = @server.post @oauth[:login_url], '', {}

      case result
      when Net::HTTPSuccess
        doc = REXML::Document.new result.body
        @session_id = doc.elements['*/sessionId'].text
        server_url  = doc.elements['*/serverUrl'].text
        init_server server_url

        return {:sessionId => @sessionId, :serverUrl => server_url}
      when Net::HTTPUnauthorized
        raise 'Invalid OAuth tokens'
      else
        raise 'Unexpected error: #{response.inspect}'
      end
    end
563361
function login(req, res, test) {
  var protocol = "https://";
  if(test === true || req.test) protocol = "http://";  //for testing

  var loginServer = req.query.login_server || "login.salesforce.com";
  var url = protocol + loginServer + "/services/oauth2/authorize";
  
  var state = JSON.stringify({
    loginServer: loginServer,
    appUrl: req.query.app_url || process.env.SALESFORCE_FINAL_URL || "/login/whoami",
    profile: req.query.profile
  });

  var options = {
    response_type: "code",
    client_id: process.env.SALESFORCE_CLIENT_ID,
    redirect_uri: process.env.SALESFORCE_REDIRECT_URL,
    state: state
  }
  
  return res.redirect(url + "?" + querystring.stringify(options) );
}
271325
function (scopes, tokenUrl, OAuthSchemeKey) {
        var params = {
            'client_id': clientId,
            'client_secret': clientSecret,
            'scope': scopes.join(' '),
            'grant_type': 'client_credentials'
        };
        $.ajax({
            url : tokenUrl,
            type: 'POST',
            data: params,
            success: function (data)
            {
                onOAuthComplete(data, OAuthSchemeKey);
            },
            error: function ()
            {
                onOAuthComplete('');
            }
        });
    }
910122
def whoami(ctx, opts):
    """"""
    click.echo("Retrieving your authentication status from the API ... ", nl=False)

    context_msg = "Failed to retrieve your authentication status!"
    with handle_api_exceptions(ctx, opts=opts, context_msg=context_msg):
        with maybe_spinner(opts):
            is_auth, username, email, name = get_user_brief()

    click.secho("OK", fg="green")
    click.echo("You are authenticated as:")
    if not is_auth:
        click.secho("Nobody (i.e. anonymous user)", fg="yellow")
    else:
        click.secho(
            "%(name)s (slug: %(username)s, email: %(email)s)"
            % {
                "name": click.style(name, fg="cyan"),
                "username": click.style(username, fg="magenta"),
                "email": click.style(email, fg="green"),
            }
        )
404315
function AuthenticationOAuth(options) {
    AuthenticationAbstract.call(this, options);
    options = options || {};
    this._token = {
        access: options.accessToken || null
    };
}
1238861
function signRequest(method, url, params, secret){
    //
    // normalize request method
    method = method.toUpperCase();
    if(!(method === 'POST' || method === 'GET')){
        throw new Error('Request method should either Post or Get and you passed "' + method + '"');
    }
    params = params || {};
    //
    // form the parameters string
    var paramStr = '';
    var keys = [];
    for(v in params){
        keys.push(v);
    }
    keys.sort();
    for(var i = 0; i < keys.length; i++){
        paramStr += keys[i] + '=' + params[keys[i]];
    }
    var basicString = method + url + paramStr + secret;
    //console.log('basic string: ' + basicString);
    var encoded = URLEncode(basicString);

    var md5 = crypto.createHash('md5');
    md5.update(encoded);
    var sign = md5.digest('hex');
    var body = '';
    for(v in params){
        body += URLEncode(v) + '=' + URLEncode(params[v]) + '&';
    }
    body += 'sign=' + sign; //append the signature
    return body;
}
145423
function post_login(urlStr, username, password, token, next) {

    assert(_.isFunction(next));

    var p = url.parse(urlStr);


    var http_protocol;
    if (p.protocol === "https:") {
        http_protocol = https;
    } else {
        http_protocol = http;
    }

    var options = {
        host: p.hostname,
        path: url.resolve(p.pathname, "login"),
        method: "POST",
        user_agent: "Mozilla/5.0"

    };

    var req = http_protocol.request(options, function (res) {
        // console.log('STATUS: ' + res.statusCode);
        // console.log('HEADERS: ' + JSON.stringify(res.headers,null," "));

        res.setEncoding('utf8');

        res.on('data', function (chunk) {
            //xx data += chunk
        });
        res.on('end', function () {


            var selected_elements = res.headers["set-cookie"].filter(function (str) {
                //  1234567890123456
                return str.substr(0, 16) === "_redmine_session";
            });

            assert(selected_elements.length === 1);
            var _cookie_session = selected_elements[0] + "; domain=" + p.hostname;
            next(null, _cookie_session);
        });
    });

    req.on('error', function (err) {
        console.log('problem with request: '.red + err.message);
        next(err);
    });

    // write data to request body
    req.write("username=" + username + "&password=" + password + "&authenticity_token=" + token + "\n");
    req.end();

}
1317366
private OAuthRequest constructXAuthPost(String email, String password) {
        OAuthRequest request = new OAuthRequest(Verb.POST, xauthEndpoint);
        request.addBodyParameter("x_auth_username", email);
        request.addBodyParameter("x_auth_password", password);
        request.addBodyParameter("x_auth_mode", "client_auth");
        return request;
    }
72125
function logon() {
    var dfrd = Q.defer();
    var token = cache.get('token');

    function extractToken(xml) {
      var r = _parse(xml, dfrd);
      if (r) {
        return r.response.token[0];
      }
    }

    if (token) {
      dfrd.resolve({
        token: token,
        cached: true
      });
    }

    request(format(URLs.logon, PROTOCOL, conf.host, conf.username,
        conf.password),
      function(err, res, body) {
        var newToken;
        if (err) {
          dfrd.reject(err);
        } else {
          newToken = extractToken(body);
          if (!newToken) {
            dfrd.reject(MODULE_ERRORS.unknown);
          } else {
            cache.put('token', newToken);
            dfrd.resolve({
              token: newToken,
              cached: false
            });
          }
        }
      });
    return dfrd.promise;
  }
661211
function tokenCredentials (authorization, secret, done) {
  var strategy = this
  var provider = strategy.provider
  var endpoint = strategy.endpoints.token
  var client = strategy.client
  var method = endpoint.method && endpoint.method.toLowerCase()
  var url = endpoint.url
  var header = endpoint.header || 'Authorization'
  var scheme = endpoint.scheme || 'OAuth'
  var accept = endpoint.accept || 'application/x-www-form-urlencoded'
  var key = client.oauth_consumer_key
  var signer = provider.oauth_signature_method || 'PLAINTEXT'
  var verifier = authorization.oauth_verifier || null
  var token = authorization.oauth_token
  var params = {}

  // Initialize request
  var req = request[method || 'post'](url)

  // Build request parameters
  params.oauth_consumer_key = key
  params.oauth_signature_method = signer
  params.oauth_timestamp = timestamp()
  params.oauth_nonce = nonce(32)
  params.oauth_token = token
  params.oauth_verifier = verifier
  params.oauth_version = '1.0'

  var input = signatureBaseString(method, url, normalizeParameters(params))
  params.oauth_signature = sign(signer, input, secret)

  // Set Authorization header
  req.set(header, scheme + ' ' + authorizationHeaderParams(params))

  // Set other headers
  req.set('Accept', accept)
  req.set('User-Agent', agent)

  // Execute request
  return req.end(function (err, res) {
    if (err) { return done(err) }
    var response = qs.parse(res.text)

    if (res.statusCode !== 200) {
      return done(new Error("Couldn't obtain token credentials"))
    }

    done(null, response)
  })
}