Source

pyoauth1client / oauth1client / __init__.py

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
"""
TODO: Write some documentation here
"""
from collections import namedtuple as _namedtuple, UserDict, Mapping, MutableMapping
from abc import (ABCMeta as _ABCMeta, abstractproperty as _abstractproperty,
        abstractmethod as _abstractmethod)
from functools import partial as _partial
from urllib.parse import (quote as urlquote, urlsplit, urlunsplit, urlencode,
        parse_qs)
from time import time
from random import randint
import hmac
import hashlib
from binascii import b2a_base64
from copy import deepcopy, copy
from os import walk, makedirs
from os.path import join as joinpath, relpath, isfile, isdir, expanduser, dirname
from itertools import chain
from functools import reduce
import json
import sys
import requests
from http.server import BaseHTTPRequestHandler, HTTPServer


class Response(metaclass=_ABCMeta):
    text = _abstractproperty(doc="Content of the response, in unicode")
    status_code = _abstractproperty(doc="Integer code of the responded HTTP "
            "Status")

_Request = _namedtuple("_Request", ("method", "url", "data",
                        "headers", "cookies"))


class Request(_Request):
    def __new__(cls, method, url, data={}, headers={}, cookies={}):
        return super().__new__(cls, method, url, data, headers, cookies)


def apply_query_to_url(url, p):
    """Applies a key-value query string to URL. """
    x = urlsplit(url)
    if x.query == '':
        query = urlencode(p)
    else:
        query = '{0}&{1}'.format(x.query, urlencode(p))
    return urlunsplit((x[0], x[1], x[2], query, x[4]))


def apply_headers_to_req(req, headers):
    if isinstance(req.headers, Mapping):
        if isinstance(req.headers, MutableMapping):
            h = copy(req.headers)
        else:
            h = dict(req.headers)
    else:
        h = dict()
    h.update(headers)
    return req._replace(headers=h)


def apply_url_query_to_req(req, query):
    try:
        url = str(req.url)
    except:
        url = ""
    x = urlsplit(url)
    if x.query == '':
        q = urlencode(query)
    else:
        q = '{}&{}'.format(x.query, urlencode(query))
    return req._replace(url=urlunsplit((x[0], x[1], x[2], q, x[4])))


def apply_data_to_req(req, data):
    if isinstance(req.data, Mapping):
        if isinstance(req.data, MutableMapping):
            d = copy(req.data)
        else:
            d = dict(req.data)
    else:
        d = dict()
    d.update(data)
    return req._replace(method="POST", data=d)


def nonce(length=8):
    """Generate pseudorandom number."""
    return ''.join([str(randint(0, 9)) for i in range(length)])


def timestamp():
    """Get seconds since epoch (UTC)."""
    return int(time())


urlquote = _partial(urlquote, safe='')

""" Credentials """

class Credentials(UserDict):
    #OKAY!
    def __init__(self, dict = None, provider = None, **kwargs):
        self.provider = provider
        super().__init__(dict = dict, **kwargs)

    oauth_token = property(lambda x: x["oauth_token"])
    oauth_token_secret = property(lambda x: x["oauth_token_secret"])

    @classmethod
    def loads(self, input):
        x = json.loads(input)
        if "provider" in x:
            del x["provider"]
        return cls(dict = x)

    @classmethod
    def load(cls, file):
        if isinstance(file, str):
            file = open(file, "r")
        x = json.load(file)
        if "provider" in x:
            del x["provider"]
        return cls(dict = x)

    def dumps(self):
        x = {"oauth_token": self.oauth_token, 
                "oauth_token_secret": self.oauth_token_secret}
        if self.provider and self.provider.name:
            x["provider"] = self.provider.name
        return json.dumps(x, indent = 4)

    def dump(self, file):
        if isinstance(file, str):
            makedirs(dirname(file), exist_ok = True)
            file = open(file, "wb")
        x = {"oauth_token": self.oauth_token,
                "oauth_token_secret": self.oauth_token_secret}
        if self.provider and self.provider.name:
            x["provider"] = self.provider.name
        return json.dump(x, file, indent = 4)

    @classmethod
    def load_profile(cls, provider, profile = "default"):
        if isinstance(provider, str):
            provider_name = provider
        else:
            provider_name = provider.name
        x = cls.load(token_store_open(provider_name, profile, "r"))
        if not isinstance(provider, str):
            x.provider = provider
        return x

    def dump_profile(self, profile = "default"):
        return self.dump(token_store_open(self.provider.name, profile, "w"))

    def oauth_req(self, req):
        return self.provider.oauth(req, self)


""" Applying oauth parameters to request """
def req_apply_oauth_header(req: Request, oauth_params) -> Request:
    x = ",".join(['{0}="{1}"'.format(urlquote(str(k)), urlquote(str(v)))
            for k, v in oauth_params.items()])
    return apply_headers_to_req(req, {"Authorization": "OAuth {0}".format(x)})


def req_apply_oauth_data(req: Request, oauth_params) -> Request:
    return apply_data_to_req(req, oauth_params)


def req_apply_oauth_urlquery(req: Request, oauth_params) -> Request:
    return apply_url_query_to_req(req, oauth_params)


""" Signature Base String Functions (For Signature Methods) """


def base_string_uri(uri):
    x = urlsplit(uri)
    scheme = x.scheme.lower()  # Scheme must be lowercase
    host, _, port = x.netloc.partition(':')
    host = host.lower()  # Host must be lowercase
    if port:
        port = int(port)
    if (scheme == "http" and port == 80) or (scheme == "https" and port == 443) or not port:
        netloc = host
    else:
        netloc = "{0}:{1}".format(host, port)
    path = x.path if x.path else "/"
    return urlunsplit((scheme, netloc, path, "", ""))


def base_string_request_params(uri, oauth_params = None, data = None):
    from urllib.parse import urlsplit, parse_qs, urlencode 
    from collections import Mapping
    query = dict((k, v[0]) for k, v in parse_qs(urlsplit(uri).query).items())
    if oauth_params: 
        query.update(oauth_params)
    if data and isinstance(data, Mapping):
        query.update(data)
    if "oauth_signature" in query: 
        del query["oauth_signature"]
    #Parameter normalization
    params = [(urlquote(str(k)), urlquote(str(v))) for k, v in query.items()]
    params.sort()
    return '&'.join(['{0}={1}'.format(k, v) for k, v in params])


def signature_base_string(method, uri, oauth_params = None, data = None):
    return '{0}&{1}&{2}'.format(urlquote(method.upper()), urlquote(base_string_uri(uri)),
            urlquote(base_string_request_params(uri, oauth_params, data)))


""" Signature Methods """


class PLAINTEXTSignatureMethod:
    name = "PLAINTEXT"
    def __init__(self, client_secret: str):
        self.client_secret = client_secret
    def __call__(self, req: Request, oauth_params:dict, token_secret:str = "") -> str:
        return "{0}&{1}".format(urlquote(self.client_secret), urlquote(token_secret))

class HMACSHA1SignatureMethod:
    name = "HMAC-SHA1"
    def __init__(self, client_secret: str):
        self.client_secret = client_secret
    def __call__(self, req: Request, oauth_params:dict, token_secret:str = "") -> str:
        #digest = HMAC-SHA1(key, text)
        text = signature_base_string(req.method, req.url, oauth_params, req.data)
        key = "{0}&{1}".format(urlquote(self.client_secret), urlquote(token_secret))
        x = hmac.new(key.encode('ascii'), text.encode('ascii'), hashlib.sha1)
        return b2a_base64(x.digest())[:-1].decode('ascii')

#TODO: RSASHA1SignatureMethod: Use the RSA module?


def oauth(req: Request, client_id:str,
        signature_method, credentials = None, params = {},
        req_oauth = req_apply_oauth_header):
    """Adds oauth parameters to a Request and signs the Request, returning the
    signed Request."""
    #Applies oauth_params to the req, and signs it.
    p = {"oauth_consumer_key": client_id,
            "oauth_timestamp": timestamp(),
            "oauth_nonce": nonce(),
            "oauth_signature_method": signature_method.name,
            "oauth_version": "1.0"}
    if credentials: 
        p["oauth_token"] = credentials.oauth_token
    p.update(params)
    signature = signature_method(req, p, credentials.oauth_token_secret if credentials else "")
    p["oauth_signature"] = signature
    x = req_oauth(req, p)
    return x


""" Token Storage """
#API Rationale: These are global functions because they should not be overriden
#in order to keep compatibility between libraries.


def _token_store_path_posix(name, profile = "default"):
    return joinpath(expanduser("~/.local/share/oauth1/profiles"), profile, name)

def _token_store_path(name, profile = "default"):
    return _token_store_path_posix(name, profile)

def token_store_open(name, profile = "default", mode = "rb"):
    path = _token_store_path(name, profile)
    makedirs(dirname(path), exist_ok = True)
    return open(path, mode)


""" User Handlers """

class UserHandler:
    def redirect_uri(self, redirect_uri):
        """Return suitable redirect URI for user interaction"""
        raise NotImplementedError()

    def authorization(self, url):
        pass

    def authorization_oob(self, url):
        pass

    def authorization_nocallback(self, url):
        pass

    def __exit__(self, type, value, traceback):
        pass

    def __enter__(self):
        return self


class DefaultUserHandler(UserHandler):
    def __init__(self):
        self.pipe = None
        self.httpd_p = None
        self._redirect_uri = None

    @staticmethod
    def _run_http_server(port_pipe, pipe, port_range):
        import socket
        port = port_range[0]
        while port <= port_range[1]:
            try:
                httpd = StoppableHttpServer(('127.0.0.1', port), HttpResponseHandler)
                break
            except socket.error as e:
                if e.errno == 98 or e.errno == 13: #Address already in use or permission denied
                    httpd = None
            port += 1
        if httpd is None:
            #Could not find a port
            port_pipe.send(0)
            port_pipe.close()
            return
        port_pipe.send(port)
        port_pipe.close()
        x = httpd.serve_forever()
        pipe.send(x)
        pipe.close()

    def redirect_uri(self, redirect_uri = None, *, port_range = (10000, 10010)):
        """Starts web server if possible and returns redirect URL.
        If not, if oauth version is 1.0a or RFC, 
        return oob. If oauth version is 1.0, return None
        (which would mean no callback)"""
        from multiprocessing import Process, Pipe
        from urllib.parse import urlsplit, urlunsplit
        if redirect_uri is None:
            redirect_uri = "http://localhost"
        p = urlsplit(redirect_uri)
        #Ensure hostname is localhost or 127.0.0.1
        if p.hostname != "127.0.0.1" and p.hostname != "localhost":
            raise ValueError("url must have host of 127.0.0.1 or localhost! Got: {}".format(p.hostname))
        if p.port is not None:
            port_range = (int(p.port), int(p.port))
        parent_port_pipe, child_port_pipe = Pipe()
        parent_pipe, child_pipe = Pipe()
        httpd_p = Process(target = self._run_http_server, 
                args = (child_port_pipe, child_pipe, port_range))
        httpd_p.start()
        if parent_port_pipe.poll(3000):
            final_port = parent_port_pipe.recv()
        else:
            raise Exception("Timeout waiting for HTTP server process to start")
        if final_port == 0:
            #Could not find a port
            return "oob"
        netloc = "{0}:{1}".format(p.hostname, final_port)
        if p.path:
            path = p.path
        else:
            path = '/'
        p = p._replace(netloc = netloc, path = path)
        self.pipe = parent_pipe
        self.httpd_p = httpd_p
        self._redirect_uri = urlunsplit(p)
        return self._redirect_uri # Return redirect URL

    def _auth_tk(self, url, pipe = None, has_verification_code = True):
        from tkinter import Tk, Frame, Label, Entry, StringVar, BOTH, Button, RIGHT
        import sys
        sys.stdout.flush()
        instructions = "Visit the following URL to authorize the application:"
        response = {"x": False}
        root = Tk()
        root.title("oAuth1 Authorization Required")
        webbox = Frame(root)
        instructions = Label(webbox, text = instructions)
        instructions.pack(padx = 5, pady = 5)
        urlstr = StringVar(value = url)
        urlbox = Entry(webbox, textvariable = urlstr, state = "readonly")
        urlbox.pack(padx = 5, pady = 5)
        def open_browser():
            from subprocess import Popen
            p = Popen(["sensible-browser", url])
        browserbutton = Button(webbox, text = "Open in web browser", command = open_browser)
        browserbutton.pack(padx = 5, pady = 5)
        if pipe:
            def poll():
                if pipe.poll():
                    root.destroy()
                    #Mutability ftw... wat
                    response["x"] = True
                else:
                    root.after(300, poll)
            root.after(300, poll)
        elif has_verification_code:
            code_instructions = Label(webbox, text = ("After authorization, " 
                "the server will give you a verification code. Enter it "
                "below:"))
            code_instructions.pack(padx = 5, pady = 5)
            code = ""
            codestr = StringVar(value = code)
            codeinput = Entry(webbox, textvariable = codestr)
            codeinput.pack(padx = 5, pady = 5)
        else:
            #No verification code.
            code_instructions = Label(webbox, text = ("Once you have " 
                "authorized the application successfully, click the button "
                "below:"))
            code_instructions.pack(padx = 5, pady = 5)
            def yay_response():
                response["x"] = True
                root.destroy()
            okbutton = Button(webbox, text = "I have authorized the application",
                    command = yay_response)
            okbutton.pack(padx = 5, pady = 5)
        webbox.pack(fill = BOTH, expand = 1)
        def code_response():
            response["x"] = code
            root.destroy()
        if not pipe and has_verification_code:
            okbutton = Button(root, text = "Ok", command = code_response)
            okbutton.pack(side = RIGHT, padx = 5, pady = 5)
        cancelbutton = Button(root, text = "Cancel", command = root.destroy)
        cancelbutton.pack(side = RIGHT, padx = 5, pady = 5)
        root.mainloop()
        return response["x"]

    def authorization(self, url):
        """Prompt the user for authorization and return redirected URL"""
        x = self._auth_tk(url, self.pipe)
        if x:
            url = self.pipe.recv()
            self.pipe.close()
            self.httpd_p.join()
            self.httpd_p = None
            return url
        else:
            self.pipe.close()
        return False

    def authorization_oob(self, url):
        """Out-of-bound authorization. Return the verification code entered
        by the user as a string."""
        return self._auth_tk(url, None)

    def authorization_nocallback(self, url):
        """Authorization with no callback so do not expect to get
        a response from the user or server"""
        return self._auth_tk(url, None, None)

    def __exit__(self, type, value, traceback):
        """Shuts down HTTP Server if it is running to prevent zombie
        process"""
        import requests
        if self._redirect_uri and self.httpd_p:
            try:
                requests.get(self._redirect_uri)
                self.httpd_p.join()
            except:
                pass


""" Server """

class TempCredentials(Credentials):
    pass

class AuthResponse(UserDict):
    oauth_token = property(lambda x: x["oauth_token"], doc = ( "The temporary "
        "credential token which was authorized."))
    @property
    def oauth_verifier(self):
        "The verification code"
        return self["oauth_verifier"] if "oauth_verifier" in self else None

class TokenCredentials(Credentials):
    pass

ServerCred = _namedtuple("ServerCred", ("server", "cred"))

class OAuth1Server:
    callback = "http://localhost"
    req_oauth = staticmethod(req_apply_oauth_header)
    version = "RFC"

    def __init__(self, client_id, signature_method, *, 
            temp_cred_endpoint = None, 
            temp_cred_endpoint_method = "POST",
            token_cred_endpoint = None, 
            token_cred_endpoint_method = "POST",
            auth_endpoint = None,
            callback = "http://localhost",
            name = None):
        for x in ("client_id", "signature_method", "temp_cred_endpoint",
                "temp_cred_endpoint_method", "token_cred_endpoint",
                "token_cred_endpoint_method", "auth_endpoint",
                "callback", "name"):
            setattr(self, x, locals()[x])

    def oauth(self, req, credentials = None, params = {}):
        """Adds oauth parameters and signs a Request"""
        return oauth(req, self.client_id, self.signature_method, 
                credentials, params, self.req_oauth)

    """ Temporary Credentials Endpoint """

    def temp_cred_req(self, oauth_callback = None, **kwargs):
        """Generate Request for requesting temporary credentials"""
        if oauth_callback is None: 
            oauth_callback = self.callback
        p = dict(kwargs)
        p["oauth_callback"] = oauth_callback
        r = Request(self.temp_cred_endpoint_method, self.temp_cred_endpoint)
        return self.oauth(r, params = p)

    def temp_cred_parse_resp(self, resp):
        x = dict((k, v[0]) for k, v in parse_qs(resp.text).items())
        return TempCredentials(dict = x, provider = self)

    def temp_cred(self, oauth_callback = None, **kwargs):
        if oauth_callback is None: 
            oauth_callback = self.callback
        req = self.temp_cred_req(oauth_callback, **kwargs)
        r = requests.request(**(req._asdict()))
        r.raise_for_status()
        return self.temp_cred_parse_resp(r)

    """ Authorization Endpoint """

    def auth_userreq(self, temp_cred, **kwargs):
        kwargs.update({"oauth_token": temp_cred.oauth_token})
        return apply_query_to_url(self.auth_endpoint, kwargs)
    
    def auth_parse_userresp(self, redirect_url):
        p = dict((k, v[0]) for k, v in parse_qs(urlsplit(redirect_url).query).items())
        return AuthResponse(dict = p)

    """ Token Credentials Endpoint """

    def token_cred_req(self, temp_cred, oauth_verifier):
        r = Request(self.token_cred_endpoint_method, self.token_cred_endpoint)
        return self.oauth(r, temp_cred, params = {"oauth_verifier": oauth_verifier})

    def token_cred_parse_resp(self, resp):
        x = dict((k, v[0]) for k, v in parse_qs(resp.text).items())
        return TokenCredentials(dict = x, provider = self)

    def token_cred(self, temp_cred, oauth_verifier):
        req = self.token_cred_req(temp_cred, oauth_verifier)
        r = requests.request(**(req._asdict()))
        r.raise_for_status()
        return self.token_cred_parse_resp(r)

    def basic_flow(self, oauth_callback = None, *, handler = DefaultUserHandler):
        if oauth_callback is None:
            oauth_callback = self.callback
        with handler() as x:
            redirect_uri = x.redirect_uri()
            temp_cred = self.temp_cred(oauth_callback = redirect_uri)
            url = self.auth_userreq(temp_cred, oauth_callback = redirect_uri)
            if redirect_uri == "oob":
                code = x.authorization_oob(url)
            else:
                redirected_url = x.authorization(url)
                code = self.auth_parse_userresp(redirected_url).oauth_verifier
            return self.token_cred(temp_cred, code)

    """ Credentials Storage """

    def load_profile(self, profile = "default"):
        """Load a Token from a profile."""
        x = Credentials.load_profile(self, profile)
        return x

class LegacyOAuth1Server(OAuth1Server):
    version = "1.0"
    def auth_userreq(self, temp_cred, *, oauth_callback = None,
            **kwargs):
        if oauth_callback:
            kwargs.update({"oauth_callback": oauth_callback})
        return super().auth_userreq(temp_cred, **kwargs)

    def token_cred_req(self, temp_cred, oauth_verifier = None):
        #NOTE: oauth_verifier is ignored as oauth1 core does not support it.
        r = Request(self.token_cred_endpoint_method, self.token_cred_endpoint)
        return self.oauth(r, temp_cred)

    def basic_flow(self, oauth_callback = None, *, handler = DefaultUserHandler):
        if oauth_callback is None:
            oauth_callback = self.callback
        with handler() as x:
            redirect_uri = x.redirect_uri()
            temp_cred = self.temp_cred(oauth_callback = redirect_uri)
            if redirect_uri == "oob":
                url = self.auth_userreq(temp_cred, oauth_callback = None)
                result = x.authorization_nocallback(url)
            else:
                url = self.auth_userreq(temp_cred, oauth_callback = redirect_uri)
                result = x.authorization(url)
            if not result:
                raise Exception("User cancel")
            return self.token_cred(temp_cred, None)


def get_all_file_paths_in_path(path: str):
    """Return a list of all paths in the directory `path`"""
    def join_paths(dir_path, filenames):
        return (joinpath(path, dir_path, filename) for \
                filename in filenames)
    files_iter = (join_paths(dir_path, filenames) for \
            dir_path, _, filenames in walk(path))
    return chain.from_iterable(files_iter)


def get_all_file_paths_in_paths(paths: [str]):
    """Return a list of all paths in the list of paths"""
    """path: TypedIteratore(Path). Returns: TypedIterator(Path)"""
    def handle(x):
        if isdir(x):
            return get_all_file_paths_in_path(x)
        elif isfile(x):
            return [x]
        else:
            return None
    paths_iter = (handle(x) for x in paths)
    paths_iter2 = filter(None, paths_iter)
    return chain.from_iterable(paths_iter2)

def _config_search_paths_posix():
    return ["/usr/share/oauth1/providers.d",
            "/usr/share/oauth1/providers.json",
            "/usr/local/share/oauth1/providers.d",
            "/usr/local/share/oauth1/providers.json",
            "/etc/oauth1.json",
            expanduser("~/.local/share/oauth1/providers.d"),
            expanduser("~/.local/share/oauth1/providers.json"),
            expanduser("~/.config/oauth1.json")
            ]

config_search_paths = _config_search_paths_posix()

def merge(x, y):
    from copy import deepcopy
    for key in x:
        if key in y:
            x[key].update(y[key])
    return x

class Config(UserDict):
    def server(self, name, **kwargs):
        """Returns the server with name"""
        x = self[name].copy()
        if "signature_method" in x:
            signature_method = x["signature_method"]
        else:
            signature_method = "HMAC-SHA1"
        if signature_method == "HMAC-SHA1":
            signature_method = HMACSHA1SignatureMethod(x["client_secret"])
        elif signature_method == "PLAINTEXT":
            signature_method = PLAINTEXTSignatureMethod(x["client_secret"])
        else:
            raise ValueError("Unknown signature method {0!r}".format(signature_method))
        x["signature_method"] = signature_method
        if "version" in x:
            version = x["version"]
        else:
            version = "rfc"
        if "_pyoauth1client_class" in x:
            module, _, cls = x["_pyoauth1client_class"].rpartition(".")
            module = __import__(module, fromlist = [cls])
            cls = getattr(module, cls)
        elif version == "rfc" or version == "1.0a":
            cls = OAuth1Server
        elif version == "1.0":
            cls = LegacyOAuth1Server
        else:
            raise ValueError("Unknown oAuth version {!r}".format(version))
        x = dict((k, v) for k, v in x.items() if not (k.startswith("_") or 
            k in ["client_secret", "resources", "version"]))
        x["name"] = name
        x.update(kwargs)
        y = cls(**x)
        return y

    def url(self, url, **kwargs):
        """Returns the server which has a resource under URL"""
        def check(x, url):
            if "resources" in x:
                y = x["resources"].split("|")
                return any(url.startswith(x) for x in y)
            else:
                return False
        z = next((x for x in self if check(self[x], url)), None)
        if z:
            return self.server(z)
        else:
            raise KeyError(url)


def load_config(paths = config_search_paths):
    z = get_all_file_paths_in_paths(paths)
    def load_file(x):
        f = open(x, "r", encoding = 'utf-8')
        y = json.load(f)
        f.close()
        return y
    configs = (load_file(x) for x in z)
    return Config(reduce(lambda x, y: merge(x, y), configs))

""" User Interface Support """

class StoppableHttpServer(HTTPServer):
    """http server that reacts to self.stop flag"""
    def serve_forever(self):
        """Handle one request at a time until stopped."""
        self.stop = False
        self.response_url = None
        while not self.stop:
            self.handle_request()
        return self.response_url

class HttpResponseHandler(BaseHTTPRequestHandler):
    def do_GET(self):
        from copy import copy
        #Send a Nice response back to client
        self.send_response(200)
        self.send_header("Content-Type", "text/html; charset=utf-8")
        self.end_headers()
        self.wfile.write(self.path.encode('ascii'))
        self.server.response_url = copy(self.path)
        #Stop the server
        self.server.stop = True
    def log_request(code = '-', size = '-'):
        pass



""" Workarounds """
class ProtocolSignatureWorkaround(OAuth1Server):
    def oauth(self, req, credentials = None, params = {}):
        #NOTE: While flickr supports HTTPS in its oauth endpoints, flickr
        #thinks that the HTTPS endpoints are being accessed via HTTP, and thus
        #constructs the signature base string accordingly, which
        #will hence not match the signature base string generated by
        #pyoauth1client. We solve this by replacing HTTPS with HTTP
        #when generating the signature base string, and then revert the change
        #after the base string is generated. This way the signature
        #base string will match the one generated by flickr even though
        #we are accessing the endpoints via HTTPS for ADDED SECURITY!!!111one
        x = urlsplit(req.url)
        if x.scheme == "https":
            #Remove the HTTPS Scheme
            https = True
            x = x._replace(scheme = "http")
            req = req._replace(url = urlunsplit(x))
        else:
            https = False
        y = super().oauth(req, credentials, params)
        if https:
            #Add back the HTTPS scheme
            x = urlsplit(y.url)
            x = x._replace(scheme = "https")
            y = y._replace(url = urlunsplit(x))
        return y
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.