Conditions | 3 |
Total Lines | 59 |
Code Lines | 45 |
Lines | 0 |
Ratio | 0 % |
Changes | 0 |
Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.
For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.
Commonly applied refactorings include:
If many parameters/temporary variables are present:
1 | import hashlib |
||
15 | def get_token( |
||
16 | issuer_uri, |
||
17 | client_id, |
||
18 | redirect_uri=None, |
||
19 | scopes=None, |
||
20 | login_hint=None, |
||
21 | domain_hint=None, |
||
22 | browser_name=None |
||
23 | ): |
||
24 | state = str(randrange(1000000000)) # "InfoOfWhereTheUserWantedToGo" |
||
25 | nonce = str(randrange(1000000000)) |
||
26 | |||
27 | # Your first step is to generate_key_pair a code verifier and challenge: |
||
28 | # Code verifier: Random URL-safe string with a minimum length of 43 characters. |
||
29 | # Code challenge: Base64 URL-encoded SHA-256 hash of the code verifier. |
||
30 | code_verifier = secrets.token_urlsafe(43) |
||
31 | m = hashlib.sha256() |
||
32 | m.update(code_verifier.encode()) |
||
33 | code_challenge = urlsafe_b64encode(m.digest()).decode().rstrip("=") |
||
34 | |||
35 | if redirect_uri is None: |
||
36 | server = AuthCodeReceiver(port=0) |
||
37 | port = server.get_port() |
||
38 | redirect_uri = f"http://localhost:{port}/" |
||
39 | else: |
||
40 | server = AuthCodeReceiver(port=int(redirect_uri.split(":")[-1])) |
||
41 | |||
42 | res = requests.get( |
||
43 | url=posixpath.join(issuer_uri, "oauth2/v2.0/authorize"), |
||
44 | params={ |
||
45 | "client_id": client_id, |
||
46 | "response_type": "code", |
||
47 | "scope": " ".join(scopes or []), |
||
48 | "redirect_uri": redirect_uri, |
||
49 | "state": state, |
||
50 | "nonce": nonce, # Optional |
||
51 | "code_challenge_method": "S256", |
||
52 | "code_challenge": code_challenge, |
||
53 | "client_info": "1", |
||
54 | "prompt": "select_account", |
||
55 | "login_hint": login_hint or "", |
||
56 | "domain_hint": domain_hint or "" |
||
57 | } |
||
58 | ) |
||
59 | |||
60 | assert res.status_code == 200 |
||
61 | |||
62 | if browser_name: |
||
63 | webbrowser.get(browser_name).open(res.request.url) |
||
64 | else: |
||
65 | webbrowser.open(res.request.url) |
||
66 | |||
67 | q = server.get_auth_response(timeout=1000, state=state) |
||
68 | return _exchange_code( |
||
69 | client_id=client_id, |
||
70 | issuer_uri=issuer_uri, |
||
71 | code_verifier=code_verifier, |
||
72 | redirect_url=redirect_uri, |
||
73 | code=q["code"] |
||
74 | ) |
||
186 |