-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathauthentication.py
107 lines (81 loc) · 3.44 KB
/
authentication.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
"""OAuth2 authentication to access protected resources."""
import json
from pathlib import Path
from typing import Optional
def get_hosts_file() -> Path:
"""Return the path to the hosts file."""
config_dir = Path("~/.config/cookiecomposer").expanduser().resolve()
config_dir.mkdir(mode=0o755, parents=True, exist_ok=True)
return config_dir / "hosts.json"
def login_to_svc(
service: Optional[str] = None,
protocol: Optional[str] = None,
scopes: Optional[str] = None,
token: Optional[str] = None,
) -> str:
"""
Log in and cache token.
Args:
service: The name of the service to authenticate with
protocol: The protocol to use for git operations
scopes: Additional authentication scopes to request
token: A specific token to use instead of logging in
Returns:
The token for the service
"""
import questionary
hosts_file = get_hosts_file()
hosts = json.loads(hosts_file.read_text()) if hosts_file.exists() else {}
if not service: # pragma: no cover
title = "What account do you want to log into?"
options = [
"github.com",
]
service = questionary.select(title, options).ask()
protocol = protocol or hosts.get(service, {}).get("git_protocol")
if not protocol: # pragma: no cover
title = "What is your preferred protocol for Git operations?"
options = ["ssh", "https"]
protocol = questionary.select(title, options).ask()
token = token or hosts.get(service, {}).get("oauth_token")
if not token: # pragma: no cover
token = github_auth_device() if service == "github.com" else ""
hosts[service] = {"git_protocol": protocol, "oauth_token": token}
hosts_file.write_text(json.dumps(hosts))
return token
def get_cached_token(account_name: str) -> Optional[str]:
"""Return the cached token for the account."""
hosts_file = get_hosts_file()
hosts = json.loads(hosts_file.read_text()) if hosts_file.exists() else {}
return hosts.get(account_name, {}).get("oauth_token")
def add_auth_to_url(url: str) -> str:
"""
Add authentication information to a URL.
Args:
url: The URL to add authentication information to.
Returns:
The URL with authentication information added, or the original URL if no token is cached
"""
from urllib.parse import urlparse, urlunparse
parsed = urlparse(url)
token = get_cached_token(parsed.netloc)
if token:
parsed = parsed._replace(netloc=f"cookiecomposer:{token}@{parsed.netloc}")
return urlunparse(parsed)
def github_auth_device(n_polls: int = 9999) -> Optional[str]: # pragma: no cover
"""
Authenticate with GitHub, polling up to `n_polls` times to wait for completion.
"""
from ghapi.auth import GhDeviceAuth
auth = GhDeviceAuth(client_id="de4e3ca9028661a80b50")
print(f"First copy your one-time code: \x1b[33m{auth.user_code}\x1b[m") # noqa: T201
print(f"Then visit {auth.verification_uri} in your browser, and paste the code when prompted.") # noqa: T201
input("Press Enter to open github.com in your browser...")
auth.open_browser()
print("Waiting for authorization...", end="") # noqa: T201
token = auth.wait(lambda: print(".", end=""), n_polls=n_polls) # noqa: T201
if not token:
print("Authentication not complete!") # noqa: T201
return None
print("Authenticated to GitHub") # noqa: T201
return token