-
Notifications
You must be signed in to change notification settings - Fork 71
Expand file tree
/
Copy pathauth.py
More file actions
100 lines (87 loc) · 2.64 KB
/
auth.py
File metadata and controls
100 lines (87 loc) · 2.64 KB
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
import os
import json
import sys
import requests
from click import echo, style
from evalai.utils.config import (
AUTH_TOKEN_PATH,
API_HOST_URL,
EVALAI_ERROR_CODES,
HOST_URL_FILE_PATH,
)
from evalai.utils.urls import URLS
requests.packages.urllib3.disable_warnings()
def get_user_auth_token_by_login(username, password):
"""
Returns user auth token by login.
"""
url = "{}{}".format(get_host_url(), URLS.login.value)
try:
payload = {"username": username, "password": password}
response = requests.post(url, data=payload)
response.raise_for_status()
except requests.exceptions.HTTPError:
if response.status_code in EVALAI_ERROR_CODES:
echo(
style(
"\nUnable to log in with provided credentials.\n",
bold=True,
fg="red",
)
)
sys.exit(1)
except requests.exceptions.RequestException:
echo(
style(
"\nCould not establish a connection to EvalAI."
" Please check the Host URL.\n",
bold=True,
fg="red",
)
)
sys.exit(1)
token = response.json()
return token
def get_user_auth_token():
"""
Loads token to be used for sending requests.
"""
if os.path.exists(AUTH_TOKEN_PATH):
with open(str(AUTH_TOKEN_PATH), "r") as TokenObj:
try:
data = TokenObj.read()
except (OSError, IOError) as e:
echo(style(e, bold=True, fg="red"))
data = json.loads(data)
token = data["token"]
return token
else:
echo(
style(
"\nThe authentication token json file doesn't exists at the required path. "
"Please download the file from the Profile section of the EvalAI webapp and "
"place it at ~/.evalai/token.json or use evalai set_token <token> to add it.\n",
bold=True,
fg="red",
)
)
sys.exit(1)
def get_request_header():
"""
Returns user auth token formatted in header for sending requests.
"""
header = {"Authorization": "Token {}".format(get_user_auth_token())}
return header
def get_host_url():
"""
Returns the host url.
"""
if not os.path.exists(HOST_URL_FILE_PATH):
return API_HOST_URL
else:
with open(HOST_URL_FILE_PATH, "r") as fr:
try:
data = fr.read()
return str(data)
except (OSError, IOError) as e:
echo(style(e, bold=True, fg="red"))