Exemple #1
0
    def auth_as_app(self) -> str:
        logger.info("Getting access token for app")
        self.request_time = datetime.datetime.now()
        data = {'grant_type': 'client_credentials'}

        pw_manager = urllib.HTTPPasswordMgrWithDefaultRealm()
        pw_manager.add_password(None, constants.OAUTH_URL, self.app_id,
                                self.app_secret)
        urllib.install_opener(
            urllib.build_opener(urllib.HTTPBasicAuthHandler(pw_manager)))

        request = urllib.Request(constants.OAUTH_URL,
                                 data=data,
                                 headers=constants.OAUTH_REQUEST_HEADERS)

        try:
            with urllib.request.urlopen(request) as response:
                self.full_response = json.loads(response.read())
                self.jwt = self.full_response["access_token"]
                self.expires_in_secs = datetime.timedelta(
                    seconds=self.full_response["expires_in"])
                self.expiry_time = self.request_time + self.expires_in_secs - constants.JWT_TOKEN_REFRESH_BUFFER
                logger.log(
                    5,
                    "refreshed auth token at %s - token will expire in %s, with a buffer next refresh will be at %s",
                    self.request_time, self.expires_in_secs, self.expiry_time)
                return self.full_response
        except urllib.error.HTTPError as err:
            logger.critical(
                "Tried to authenticate an app, got error code %s with reason %s",
                err.code, err.reason)
            raise UnauthorizedRequestError()
Exemple #2
0
    def post_data(self, data, username, password):
        utc_datetime = datetime.datetime.utcnow()
        url_parameters = {
            'cluster': self.elasticMonitoringCluster,
            'index': self.elasticIndex,
            'index_period': utc_datetime.strftime("%Y.%m.%d"),
        }
        url = "%(cluster)s/%(index)s-%(index_period)s/hrbdata" % url_parameters
        headers = {'content-type': 'application/json'}
        try:
            req = Request(url)
            req.add_header('Content-Type', 'application/json; charset=utf-8')
            jsondata = json.dumps(data)
            jsondataasbytes = jsondata.encode('utf-8')

            req.add_header('Content-Length', len(jsondataasbytes))
            data = urllib.parse.urlencode(data).encode("utf-8")
            # req = urllib.request.urlopen(url, headers=headers, data=json.dumps(data))
            if self.write_es_security_enable:
                password_mgr = urllib.HTTPPasswordMgrWithDefaultRealm()
                password_mgr.add_password(None, url, username, password)
                handler = urllib.HTTPBasicAuthHandler(password_mgr)
                opener = urllib.build_opener(handler)
                urllib.install_opener(opener)
                response = urllib.request.urlopen(req, jsondataasbytes)
            else:
                response = urllib.request.urlopen(req, jsondataasbytes)
        except Exception as e:
            print("Error:  {}".format(str(e)))
Exemple #3
0
 def handle_urlopen(self, urlData, username, password):
     if self.read_es_security_enable:
         password_mgr = urllib.HTTPPasswordMgrWithDefaultRealm()
         password_mgr.add_password(None, urlData, username, password)
         handler = urllib.HTTPBasicAuthHandler(password_mgr)
         opener = urllib.build_opener(handler)
         urllib.install_opener(opener)
         response = urllib.request.urlopen(urlData)
     else:
         response = urllib.request.urlopen(urlData)
     return response.read().decode('utf-8')
Exemple #4
0
    def __init__(self, ip_address, port, username="******", password="******"):
        PowerDevice.__init__(self, ip_address, username, password)
        self._ip_address = ip_address
        self.port = port

        # create a password manager
        password_mgr = _urllib.HTTPPasswordMgrWithDefaultRealm()
        password_mgr.add_password(None, 'http://' + ip_address, username, password)
        handler = _urllib.HTTPBasicAuthHandler(password_mgr)
        opener = _urllib.build_opener(handler)
        # Now all calls to _urllib.urlopen use our opener.
        _urllib.install_opener(opener)
Exemple #5
0
        def get_with_username_password(username, password):
            # create a password manager
            password_mgr = _urllib.HTTPPasswordMgrWithDefaultRealm()
            password_mgr.add_password(None, 'http://' + ip_address, username, password)
            handler = _urllib.HTTPBasicAuthHandler(password_mgr)
            opener = _urllib.build_opener(handler)
            opener.open('http://' + ip_address)
            _urllib.install_opener(opener)

            request = _urllib.Request('http://' + ip_address)
            response = opener.open(request)
            data = response.read()
            return data
Exemple #6
0
def http_auth_request(url, host, user, passwd, user_agent=USER_AGENT):
    """Call an HTTP server with authorization credentials using urllib.
    """
    if DEBUG: http.client.HTTPConnection.debuglevel = 1

    # Hook up handler/opener to urllib
    password_manager = urllib.HTTPPasswordMgrWithDefaultRealm()
    password_manager.add_password(None, host, user, passwd)
    auth_handler = urllib.HTTPBasicAuthHandler(password_manager)
    opener = urllib.build_opener(auth_handler)
    urllib.install_opener(opener)

    return http_request(url, user_agent)
Exemple #7
0
    def _check_url(cls, url):
        """
        Functon will check given url and try to verify if it's a valid
        link. Sometimes it may happened that mercurial will issue basic
        auth request that can cause whole API to hang when used from python
        or other external calls.

        On failures it'll raise urllib2.HTTPError
        """
        from mercurial.util import url as Url

        # those authnadlers are patched for python 2.6.5 bug an
        # infinit looping when given invalid resources
        from mercurial.url import httpbasicauthhandler, httpdigestauthhandler

        # check first if it's not an local url
        if os.path.isdir(url) or url.startswith('file:'):
            return True

        if('+' in url[:url.find('://')]):
            url = url[url.find('+') + 1:]

        handlers = []
        test_uri, authinfo = Url(url).authinfo()
        if not test_uri.endswith('info/refs'):
            test_uri = test_uri.rstrip('/') + '/info/refs'
        if authinfo:
            #create a password manager
            passmgr = urllib.HTTPPasswordMgrWithDefaultRealm()
            passmgr.add_password(*authinfo)

            handlers.extend((httpbasicauthhandler(passmgr),
                             httpdigestauthhandler(passmgr)))

        o = urllib2.build_opener(*handlers)
        o.addheaders = [('User-Agent', 'git/1.7.8.0')]  # fake some git

        q = {"service": 'git-upload-pack'}
        qs = '?%s' % urllib.urlencode(q)
        cu = "%s%s" % (test_uri, qs)
        req = urllib2.Request(cu, None, {})

        try:
            resp = o.open(req)
            return resp.code == 200
        except Exception as e:
            # means it cannot be cloned
            raise urllib2.URLError("[%s] %s" % (url, e))
Exemple #8
0
def httpConnection(url, proxy):
    #TODO: habilitar autenticacion ntlm
    if (proxy.auth == "ntlm"):
        passman = urllib.HTTPPasswordMgrWithDefaultRealm()
        passman.add_password(None, proxy.url, proxy.user, proxy.password)
        auth = HTTPNtlmAuthHandler.HTTPNtlmAuthHandler(passman)
    else:
        passman = urllib.request.HTTPPasswordMgr()
        passman.add_password(None, proxy.url, proxy.user, proxy.password)
        auth = urllib.request.HTTPBasicAuthHandler(passman)

    if (proxy.url):
        proxy = urllib.ProxyHandler({'http': proxy.url})
        opener = urllib.build_opener(proxy.url, auth, urllib2.HTTPHandler)
        urllib.install_opener(opener)

    return urllib.request.urlopen(url)
Exemple #9
0
import urllib
import ntlm_auth 
# import HTTPNtlmAuthHandler
from sharepoint import SharePointSite
username = '******'
password = '******'
url = 'http://cyg249:8080/tfs/DefaultCollection/_apis/wit/workitems/1'
passman = urllib.HTTPPasswordMgrWithDefaultRealm()
passman.add_password(None, url, username, password)
auth_NTLM = urllib.HTTPNtlmAuthHandler.HTTPNtlmAuthHandler(passman)
opener = urllib.build_opener(auth_NTLM)
site = SharePointSite(url, opener)

for sp_list in site.lists:
    print (sp_list.id, sp_list.meta['Title'])