-
Notifications
You must be signed in to change notification settings - Fork 25
/
Copy pathauthentication.py
70 lines (50 loc) · 1.98 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
from __future__ import annotations
from urllib.parse import urlencode
import requests
from requests import Session
from todoist_api_python.endpoints import (
AUTHORIZE_ENDPOINT,
REVOKE_TOKEN_ENDPOINT,
TOKEN_ENDPOINT,
get_auth_url,
get_sync_url,
)
from todoist_api_python.http_requests import post
from todoist_api_python.models import AuthResult
from todoist_api_python.utils import run_async
def get_auth_token(
client_id: str, client_secret: str, code: str, session: Session | None = None
) -> AuthResult:
endpoint = get_auth_url(TOKEN_ENDPOINT)
session = session or requests.Session()
payload = {"client_id": client_id, "client_secret": client_secret, "code": code}
response = post(session=session, url=endpoint, data=payload)
return AuthResult.from_dict(response)
async def get_auth_token_async(
client_id: str, client_secret: str, code: str
) -> AuthResult:
return await run_async(lambda: get_auth_token(client_id, client_secret, code))
def revoke_auth_token(
client_id: str, client_secret: str, token: str, session: Session | None = None
) -> bool:
endpoint = get_sync_url(REVOKE_TOKEN_ENDPOINT)
session = session or requests.Session()
payload = {
"client_id": client_id,
"client_secret": client_secret,
"access_token": token,
}
response = post(session=session, url=endpoint, data=payload)
return response
async def revoke_auth_token_async(
client_id: str, client_secret: str, token: str
) -> bool:
return await run_async(lambda: revoke_auth_token(client_id, client_secret, token))
class ArgumentError(Exception):
pass
def get_authentication_url(client_id: str, scopes: list[str], state: str) -> str:
if len(scopes) == 0:
raise ArgumentError("At least one authorization scope should be requested.")
query = {"client_id": client_id, "scope": ",".join(scopes), "state": state}
auth_url = get_auth_url(AUTHORIZE_ENDPOINT)
return f"{auth_url}?{urlencode(query)}"