示例#1
0
    def handle_401(self, r, **kwargs):
        """Resends a request with auth headers, if needed."""

        www_authenticate = r.headers.get('www-authenticate', '').lower()

        if 'basic' in www_authenticate:
            if self.pos is not None:
                r.request.body.seek(self.pos)

            # Consume content and release the original connection
            # to allow our new request to reuse the same one.
            r.content
            r.raw.release_conn()
            prep = r.request.copy()
            if not hasattr(prep, '_cookies'):
                prep._cookies = cookies.RequestsCookieJar()
            cookies.extract_cookies_to_jar(prep._cookies, r.request, r.raw)
            prep.prepare_cookies(prep._cookies)

            self.auth = auth.HTTPBasicAuth(self.username, self.password)
            prep = self.auth(prep)
            _r = r.connection.send(prep, **kwargs)
            _r.history.append(r)
            _r.request = prep

            return _r

        if 'digest' in www_authenticate:
            self.auth = auth.HTTPDigestAuth(self.username, self.password)
            # Digest auth would resend the request by itself. We can take a
            # shortcut here.
            return self.auth.handle_401(r, **kwargs)
示例#2
0
def warn(change_id, revision_id):
    url = ('https://review.openstack.org/a/changes/%s/revisions/%s/review' %
           (change_id, revision_id))
    data = {'message': WARN_MSG}
    if CONF.dryrun:
        return
    response = requests.post(url, json=data,
                             auth=auth.HTTPDigestAuth(CONF.gerrit_user,
                                                      CONF.http_password))
示例#3
0
def abandon(change_id):
    url = ('https://review.openstack.org/a/changes/%s/abandon' %
           change_id)
    data = {'message': AB_MSG}
    if CONF.dryrun:
        return
    response = requests.post(url, json=data,
                             auth=auth.HTTPDigestAuth(CONF.gerrit_user,
                                                      CONF.http_password))
    def __init__(
        self,
        service_url,
        username=None,
        password=None,
        service_name=None,
        timeout=HTTP_TIMEOUT,
        connection=None,
    ):
        """
        :param service_url: http://user:passwd@host:port/json_rpc"
        :param service_name: method name of monero wallet RPC and monero daemon RPC
        """
        self.__service_url = service_url
        self.__service_name = service_name
        self.__timeout = timeout
        self.__url = urlparse.urlparse(service_url)
        if self.__url.port is None:
            port = 80
        else:
            port = self.__url.port

        self.__rpc_url = (
            self.__url.scheme
            + "://"
            + self.__url.hostname
            + ":"
            + str(port)
            + self.__url.path
        )

        user = username if username else self.__url.username
        passwd = password if password else self.__url.password

        # Digest Authentication
        authentication = None
        log.debug(f"{user}, {passwd}")
        if user is not None and passwd is not None:
            authentication = auth.HTTPDigestAuth(user, passwd)

        headers = {
            "Content-Type": "application/json",
            "User-Agent": USER_AGENT,
            "Host": self.__url.hostname,
        }

        if connection:
            # Callables re-use the connection of the original proxy
            self.__conn = connection
        else:
            self.__conn = Session()
            self.__conn.auth = authentication
            self.__conn.headers = headers
    def __init__(
        self,
        service_url,
        username=None,
        password=None,
        service_name=None,
        timeout=HTTP_TIMEOUT,
        connection=None,
    ):
        """
        :param service_url: Monero RPC URL, like http://user:passwd@host:port/json_rpc.
        :param service_name: Method name of Monero RPC.
        """

        self.__service_url = service_url
        self.__service_name = service_name
        self.__timeout = timeout
        self.__url = urlparse.urlparse(service_url)

        port = self.__url.port if self.__url.port else 80
        self.__rpc_url = (
            self.__url.scheme
            + "://"
            + self.__url.hostname
            + ":"
            + str(port)
            + self.__url.path
        )

        if connection:
            # Callables re-use the connection of the original proxy
            self.__conn = connection
        else:
            headers = {
                "Content-Type": "application/json",
                "User-Agent": USER_AGENT,
                "Host": self.__url.hostname,
            }

            user = username if username else self.__url.username
            passwd = password if password else self.__url.password
            # Digest Authentication
            authentication = None
            if user is not None and passwd is not None:
                authentication = auth.HTTPDigestAuth(user, passwd)

            self.__conn = Session()
            self.__conn.mount(
                f"{self.__url.scheme}://{self.__url.hostname}", self.retry_adapter
            )
            self.__conn.auth = authentication
            self.__conn.headers = headers
示例#6
0
def getData(accountID):
    # get from database
    if accountID in dataDic:
        return dataDic[accountID]
    res = requests.get(
        "http://51.104.239.212:8060/v1/documents?uri=/documents/" + accountID +
        ".json",
        auth=auth.HTTPDigestAuth("admin", "admin"))
    print(1)
    if res.status_code == 404:
        dataDic[accountID] = False
        return False
    result = json.loads(res.text)
    dataDic[accountID] = result
    return result
    def __init__(self,
                 project,
                 user=None,
                 password=None,
                 updating_review_cb=lambda x: None):
        self.base_url = 'https://review.openstack.org/'

        if not (user and password):
            config = _read_config()
            user = config['username']
            password = config['password']
            self.base_url = config['url']

        self.auth = auth.HTTPDigestAuth(user, password)

        self.project = project
        self.updating_review_cb = updating_review_cb
示例#8
0
    def parse_auth(self, auth):
        # Parse "auth" parameter
        if type(auth) is not tuple or len(auth) != 3:
            return None

        method, username, password = auth

        # Basic Authentication
        if method == 'basic':
            print 'basic authentication method being used.'
            return requestsauth.HTTPBasicAuth(username, password)

        # Digest Authentication
        if method == 'digest':
            print 'digest authentication method being used.'
            return requestsauth.HTTPDigestAuth(username, password)

        raise NotImplementedError('Unsupported authentication method: %r' %
                                  method)
    def __init__(self,
                 service_url,
                 service_name=None,
                 timeout=HTTP_TIMEOUT,
                 connection=None):
        """
        :param service_url: http://user:passwd@host:port/json_rpc"
        :param service_name: method name of monero wallet RPC and monero daemon RPC
        """
        self.__service_url = service_url
        self.__service_name = service_name
        self.__timeout = timeout
        self.__url = urlparse.urlparse(service_url)
        if self.__url.port is None:
            port = 80
        else:
            port = self.__url.port

        self.__rpc_url = (self.__url.scheme + '://' + self.__url.hostname +
                          ':' + str(port) + self.__url.path)

        (user, passwd) = (self.__url.username, self.__url.password)

        # Digest Authentication
        authentication = None
        log.debug('{0}, {1}'.format(user, passwd))
        if user is not None and passwd is not None:
            authentication = auth.HTTPDigestAuth(user, passwd)

        headers = {
            'Content-Type': 'application/json',
            'User-Agent': USER_AGENT,
            'Host': self.__url.hostname
        }

        if connection:
            # Callables re-use the connection of the original proxy
            self.__conn = connection
        else:
            self.__conn = Session()
            self.__conn.auth = authentication
            self.__conn.headers = headers
示例#10
0
文件: wtt.py 项目: jerrywang1974/wtt
    def auth_basic_digest(self):
        """
		return	data for basic/digest auth
		"""

        params = dict()
        for item in self.auth_params.split(','):
            params[item.split("=")[0]] = item.split("=")[1]

        if self.auth.lower() == "basic":
            try:
                return auth.HTTPBasicAuth(params["login"], params["password"])
            except:
                sys.exit("ERROR: Basic auth has no login and password fields")

        if self.auth.lower() == "digest":
            try:
                return auth.HTTPDigestAuth(params["login"], params["password"])
            except:
                sys.exit("ERROR: Digest auth has no login and password fields")
示例#11
0
    def __init__(self, host='localhost', port=8080, user='******', password=''):
        """ Roughly the order of requests used in the built in deluge webui that we emulate

        1. system.listMethods
        2. auth.check_session: []
        3. web.register_event_listener [PluginDisabledEvent]
        4. web.register_event_listener [PluginEnabledEvent]
        5. web.get_events []
        6. web.connected []
        7. web.update_ui [["queue","name","total_size","state","progress","num_seeds",
            "total_seeds","num_peers","total_peers","download_payload_rate","upload_payload_rate",
            "eta","ratio","distributed_copies","is_auto_managed","time_added","tracker_host",
            "save_path","total_done","total_uploaded","max_download_speed","max_upload_speed",
            "seeds_peers_ratio"],{}]
        8. web.get_plugins
        9. web.update_ui
        10. web.get_events [] (periodic?)

        If the password is not accepted _valid_password will be set to false and prevent any
        more requests from happening.

        :param host: Host of the deluge webui
        :type host: basestring
        :param port: Port of the webui (default: 8112)
        :type port: int
        :param password: Password to the webui (default: deluge)
        :type password: string
        """
        super(QBittorrentClient, self).__init__()
        self._endpoint = 'http://{}:{}/json'.format(host, port)
        self._session = requests.session()
        self._session.auth = auth.HTTPDigestAuth(user, password)
        self._headers = {
            'Content-type': 'application/json',
            'Accept': 'application/json'
        }
        self._req_id = 0
        self._valid_password = True
        self._last_request = 0
示例#12
0
    def request(self, host, handler, request_body, verbose):
        """
		Make an xmlrpc request.
		"""
        url = self._build_url(host, handler)
        try:
            resp = requests.post(url,
                                 data=request_body,
                                 timeout=30,
                                 auth=auth.HTTPDigestAuth(
                                     self._username, self._password))
        except ValueError:
            raise
        except Exception:
            raise  # something went wrong
        else:
            try:
                resp.raise_for_status()
            except requests.RequestException as e:
                raise xmlrpclib.ProtocolError(url, resp.status_code, str(e),
                                              resp.headers)
            else:
                return self.parse_response(resp, verbose)
示例#13
0
def getDataForAccount(accountID):
    with open(
            "/Users/yhw/Desktop/CS/2ndYear/SystemEngineering/webapp-testing/aux_files/finalData.json",
            'r') as data:
        a = json.load(data)
    resultDic = {}
    for key in a['Data']:
        current = []
        for item in a['Data'][key]:
            if item["AccountId"] == accountID:
                if key == "Account":
                    month = item["OpeningDate"][3:5]
                    day = item["OpeningDate"][0:2]
                    resultDic["BillingDate"] = month + '-' + day
                current.append(item)
            resultDic[key] = current
    result = json.dumps(resultDic)
    url = "http://51.104.239.212:8060/v1/documents?uri=/documents/" + accountID + ".json"
    headers = {'Content-Type': 'application/json'}
    r = requests.put(url,
                     data=json.dumps(result),
                     headers=headers,
                     auth=auth.HTTPDigestAuth("admin", "admin"))
    return
示例#14
0
    def __init__(self, configuration, credentials):
        """
        Initiate an object with configuration and credentials.

        The initialized client will then operate within the given Atlas group, and the given user.
        Other than this, it is stateless: methods are merely HTTP wrappers.

        Note: credentials passed in as a separate object to keep them from being accidentally
        dumped to logs.

        :param dict configuration: group_id (required) and api root url (optional)
        :param dict credentials: user and key (required)
        """
        self.group_id = configuration["group_id"]
        self.root = configuration.get("root", DEFAULT_ROOT_URL)
        self.root += "/" if self.root[-1] != "/" else ""
        self.private_root = configuration.get("private", PRIVATE_ROOT_URL)
        self.private_root += "/" if self.private_root[-1] != "/" else ""

        # Check and fail early if credentials missing
        assert credentials["public_key"]
        assert credentials["private_key"]
        self.auth = auth.HTTPDigestAuth(credentials["public_key"],
                                        credentials["private_key"])
示例#15
0
def create_digest_auth(config):
    return requests_auth.HTTPDigestAuth(config['username'], config['password'])
示例#16
0
 def __init__(self, username, password):
     self.digest_auth = auth.HTTPDigestAuth(username, password)
示例#17
0
from django.shortcuts import render, redirect
from django.contrib.auth.decorators import login_required
from users.forms import UserRegistrationForm, UserUpdateForm, ProfileUpdateForm
import requests
from requests import auth
import json
from django.contrib import messages

import requests, json
from requests import auth
me = auth.HTTPDigestAuth("admin", "admin")
resp = requests.get("http://51.132.8.252:8060/v1/search?format=json", auth=me)
jsonFile = json.loads(resp.text)
result = jsonFile["results"]
a = []
for key in result:
    uri = key["uri"]
    res = requests.get("http://51.132.8.252:8060/v1/documents?uri=" + uri,
                       auth=me)
    a.append(res.json())
print(a)

a = [{
    'accounts': [{
        'id':
        '8ca8a7e4-6d02-40e3-a129-0b2bf89de9f0',
        'label':
        'My Account',
        'bank_id':
        'GENODEM1GLS',
        'account_routings': [{
示例#18
0
# Purpose:     Scripts for accessing and querying the MarkLogic server
#
# Author:      Schei008
#
# Created:     13-02-2019
# Copyright:   (c) Schei008 2019
# Licence:     <your licence>
#-------------------------------------------------------------------------------

import requests
from requests import auth
import json
import pandas as pd
#import rdflib

me = auth.HTTPDigestAuth("simon", "$28*Mfrh")

url = 'http://localhost:8000/v1/graphs/sparql'

prefixes = 'PREFIX db: <http://dbpedia.org/resource/> \
            PREFIX onto: <http://dbpedia.org/ontology/> \
            PREFIX owl: <http://www.w3.org/2002/07/owl#> \
            PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#> \
            PREFIX cts: <http://marklogic.com/cts#> \
            PREFIX dc: <http://purl.org/dc/elements/1.1/>\
             '
""""Firing SPARQL queries against Mark Logic"""


#Fires a query against MarkLogic and returns a Pandas DF
def queryforDF(query):
示例#19
0
-                r.request.body.seek(self.pos)
-
-            # Consume content and release the original connection
-            # to allow our new request to reuse the same one.
-            r.content
-            r.raw.release_conn()
-            prep = r.request.copy()
-            if not hasattr(prep, '_cookies'):
-                prep._cookies = cookies.RequestsCookieJar()
-            cookies.extract_cookies_to_jar(prep._cookies, r.request, r.raw)
-            prep.prepare_cookies(prep._cookies)
-
-            self.auth = auth.HTTPBasicAuth(self.username, self.password)
-            prep = self.auth(prep)
-            _r = r.connection.send(prep, **kwargs)
-            _r.history.append(r)
-            _r.request = prep
-
-            return _r
+            return self._handle_basic_auth_401(r, kwargs)
 
         if 'digest' in www_authenticate:
-            self.auth = auth.HTTPDigestAuth(self.username, self.password)
-            # Digest auth would resend the request by itself. We can take a
-            # shortcut here.
-            return self.auth.handle_401(r, **kwargs)
+            return self._handle_digest_auth_401(r, kwargs)
 
     def __call__(self, request):
         if self.auth is not None: