Get web sudo cookies using normal http request
428226
def user_get_websudo(self):
        
        url = 'secure/admin/WebSudoAuthenticate.jspa'
        headers = self.form_token_headers
        data = {
            'webSudoPassword': self.password,
        }
        return self.post(path=url, data=data, headers=headers)
952978
function(headers) {
    var noSec = httpinvoke.forbiddenInputHeaders.indexOf('sec-*') >= 0;
    var noProxy = httpinvoke.forbiddenInputHeaders.indexOf('proxy-*') >= 0;
    for(var header in headers) {
        if(headers.hasOwnProperty(header)) {
            var headerl = header.toLowerCase();
            if(httpinvoke.forbiddenInputHeaders.indexOf(headerl) >= 0) {
                throw [14, header];
            }
            if(noProxy && headerl.substr(0, 'proxy-'.length) === 'proxy-') {
                throw [15, header];
            }
            if(noSec && headerl.substr(0, 'sec-'.length) === 'sec-') {
                throw [16, header];
            }
        }
    }
}
334524
def _get_headers(self, environ):
        
        headers = self.headers
        method = environ['REQUEST_METHOD']

        if has_empty_content(self.status_code, method) and method != HEAD:
            headers.pop('content-type', None)
            headers.pop('content-length', None)
            self._content = ()
        else:
            if not self.is_streamed():
                cl = reduce(count_len, self._content, 0)
                headers['content-length'] = str(cl)
            ct = headers.get('content-type')
            # content type encoding available
            if self.encoding:
                ct = ct or 'text/plain'
                if ';' not in ct:
                    ct = '%s; charset=%s' % (ct, self.encoding)
            if ct:
                headers['content-type'] = ct
            if method == HEAD:
                self._content = ()
        # Cookies
        if (self.status_code < 400 and self._can_store_cookies and
                self._cookies):
            for c in self.cookies.values():
                headers.add('set-cookie', c.OutputString())
        return headers.items()
279437
def extract_cookies(self, response, request):
        """"""
        _debug("extract_cookies: %s", response.info())
        self._cookies_lock.acquire()
        try:
            self._policy._now = self._now = int(time.time())

            for cookie in self.make_cookies(response, request):
                if self._policy.set_ok(cookie, request):
                    _debug(" setting cookie: %s", cookie)
                    self.set_cookie(cookie)
        finally:
            self._cookies_lock.release()
117653
def parse_cookies(self, req, name, field):
        """"""
        return core.get_value(req.COOKIES, name, field)
1242391
private Optional<String> getXsrfFromHtmlBody(HttpResponse loginResponse) throws IOException {
        Optional<Cookie> gerritAccountCookie = findGerritAccountCookie();
        if (gerritAccountCookie.isPresent()) {
            Matcher matcher = GERRIT_AUTH_PATTERN.matcher(EntityUtils.toString(loginResponse.getEntity(), Consts.UTF_8));
            if (matcher.find()) {
                return Optional.of(matcher.group(1));
            }
        }
        return Optional.absent();
    }
163382
function getProxyUri(uri) {

	if (uri.protocol === 'https:' && env.httpsProxy || uri.protocol === 'http:' && env.httpProxy) {

		if (env.noProxy) {
			var canonicalHost = uri.host.replace(/^\.*/, '.');
			var port = uri.port || (uri.protocol === 'https:' ? '443' : '80');

			var patterns = env.noProxy.split(',');
			for (var i = patterns.length - 1; i >= 0; i--) {
				var pattern = patterns[i].trim().toLowerCase();

				// don't use a proxy at all
				if (pattern === '*') {
					return null;
				}

				// Remove leading * and make sure to have exact one leading dot (.)
				pattern = pattern.replace(/^[\*]+/, '').replace(/^\.*/, '.');

				// add port if no specified
				if (pattern.indexOf(':') === -1) {
					pattern += ':' + port;
				}

				// if host ends with pattern, no proxy should be used
				if (canonicalHost.indexOf(pattern) === canonicalHost.length - pattern.length) {
					return null;
				}
			}
		}

		if (uri.protocol === 'https:' && env.httpsProxy) {
			return env.httpsProxy;
		} else if (uri.protocol === 'http:' && env.httpProxy) {
			return env.httpProxy;
		}
	}

	return null;
}
626751
def grant_sudo_privileges(request, max_age=COOKIE_AGE):
    
    user = getattr(request, 'user', None)

    # If there's not a user on the request, just noop
    if user is None:
        return

    if not user.is_authenticated():
        raise ValueError('User needs to be logged in to be elevated to sudo')

    # Token doesn't need to be unique,
    # just needs to be unpredictable and match the cookie and the session
    token = get_random_string()
    request.session[COOKIE_NAME] = token
    request._sudo = True
    request._sudo_token = token
    request._sudo_max_age = max_age
    return token
367062
def _http_headers(self):
        
        if not self.usertag:
            return {}

        creds = u'{}:{}'.format(
            self.usertag,
            self.password or ''
        )
        token = base64.b64encode(creds.encode())
        return {
            'Authorization': 'Basic {}'.format(token.decode())
        }
273387
def login(self, username, passwd_hash, webapi_key, country_code=1):
        """"""
        self.client = Client(self.webapi_url)
        self.ArrayOfLong = self.client.get_type('ns0:ArrayOfLong')  # this should be done by zeep...
        ver_key = self.client.service.doQuerySysStatus(1, 1, webapi_key)['verKey']
        return self.client.service.doLoginEnc(username, passwd_hash,
                                              country_code, webapi_key,
                                              ver_key)['sessionHandlePart']
829209
def get_private_endpoint(id: str, guid: str) -> str:
    """"""
    _username, domain = id.split("@")
    return "https://%s/receive/users/%s" % (domain, guid)
552379
def logged_user(request):
    
    dct = cookie_facade.retrive_cookie_data(request, USER_COOKIE_NAME).execute().result
    if dct is None:
        return Command()
    return NodeSearch(dct['id'])
108179
def parse_cookie_header(header):
    '''
    
    '''
    attribs = ('expires', 'path', 'domain', 'version', 'httponly', 'secure', 'comment', 'max-age')

    # Split into cookie(s); handles headers with multiple cookies defined
    morsels = []
    for item in header.split(';'):
        item = item.strip()
        if ',' in item and 'expires' not in item:
            for part in item.split(','):
                morsels.append(part)
        else:
            morsels.append(item)

    # Break down morsels into actual cookies
    cookies = []
    cookie = {}
    value_set = False
    for morsel in morsels:
        parts = morsel.split('=')
        if parts[0].lower() in attribs:
            if parts[0] in cookie:
                cookies.append(cookie)
                cookie = {}
            if len(parts) > 1:
                cookie[parts[0]] = '='.join(parts[1:])
            else:
                cookie[parts[0]] = True
        else:
            if value_set is True:
                # This is a new cookie; save the old one and clear for this one
                cookies.append(cookie)
                cookie = {}
                value_set = False
            cookie[parts[0]] = '='.join(parts[1:])
            value_set = True

    if cookie:
        # Set the last cookie that was processed
        cookies.append(cookie)

    # These arguments are required by cookielib.Cookie()
    reqd = (
        'version',
        'port',
        'port_specified',
        'domain',
        'domain_specified',
        'domain_initial_dot',
        'path',
        'path_specified',
        'secure',
        'expires',
        'discard',
        'comment',
        'comment_url',
        'rest',
    )

    ret = []
    for cookie in cookies:
        name = None
        value = None
        for item in list(cookie):
            if item in attribs:
                continue
            name = item
            value = cookie.pop(item)

        # cookielib.Cookie() requires an epoch
        if 'expires' in cookie:
            cookie['expires'] = salt.ext.six.moves.http_cookiejar.http2time(cookie['expires'])

        # Fill in missing required fields
        for req in reqd:
            if req not in cookie:
                cookie[req] = ''
        if cookie['version'] == '':
            cookie['version'] = 0
        if cookie['rest'] == '':
            cookie['rest'] = {}
        if cookie['expires'] == '':
            cookie['expires'] = 0

        if 'httponly' in cookie:
            del cookie['httponly']
        ret.append(salt.ext.six.moves.http_cookiejar.Cookie(name=name, value=value, **cookie))

    return ret
552665
function getCookies() {
  return new Promise((resolve, reject) => {
    request.get(rootUrl, function(err, res, body) {
      if (err != null && res.statusCode !== 200) {
        reject(err || new Error('Accessing UK information failed'))
        return
      }
      resolve()
    })
  })
}
56475
def get_session(username, password, locale=DEFAULT_LOCALE,
                cookie_path=COOKIE_PATH):
    """"""
    class UPSAuth(AuthBase):  # pylint: disable=too-few-public-methods
        """UPS authorization storage."""

        def __init__(self, username, password, locale, cookie_path):
            """Init."""
            self.username = username
            self.password = password
            self.locale = locale
            self.cookie_path = cookie_path

        def __call__(self, r):
            """Call is no-op."""
            return r

    session = requests.session()
    session.auth = UPSAuth(username, password, locale, cookie_path)
    if os.path.exists(cookie_path):
        session.cookies = _load_cookies(cookie_path)
    else:
        _login(session)
    return session
582493
Cookie[] getCookies(String uri){
        if( null == cookies || 0 == cookies.size()) return null;

        for(Cookie cookie: cookies){

            if("".equals(cookie.getDomain())){
                String domain = uri.replaceAll("^.*:\\/\\/([^\\/]+)[\\/]?.*$", "$1");
                cookie.setDomain(domain);
                cookie.setPath("/");
                cookie.setExpiryDate(null);
                cookie.setSecure(false);
            }
        }

        return cookies.toArray(new Cookie[cookies.size()]);
    }
255830
public Credential getSingleSignOn(HttpRequest request,
                                      HttpResponse response)
    {
        String ssoID = null;
        Cookie[] cookies = request.getCookies();
        for (int i = 0; i < cookies.length; i++)
        {
            if (cookies[i].getName().equals(SSO_COOKIE_NAME))
            {
                ssoID = cookies[i].getValue();
                break;
            }
        }
        if(log.isDebugEnabled())log.debug("get ssoID="+ssoID);
        
        Principal principal=null;
        Credential credential=null;
        synchronized(_ssoId2Principal)
        {
            principal=(Principal)_ssoId2Principal.get(ssoID);
            credential=(Credential)_ssoPrincipal2Credential.get(principal);
        }
        
        if(log.isDebugEnabled())log.debug("SSO principal="+principal);
        
        if (principal!=null && credential!=null)
        {
            if (response.getHttpContext().getRealm().reauthenticate(principal))
            {
                request.setUserPrincipal(principal);
                request.setAuthUser(principal.getName());
                return credential;
            }
            else
            {
                synchronized(_ssoId2Principal)
                {
                    _ssoId2Principal.remove(ssoID);
                    _ssoPrincipal2Credential.remove(principal);
                    _ssoUsername2Id.remove(principal.getName());
                }    
            }
        }
        return null;
    }