-
Notifications
You must be signed in to change notification settings - Fork 25
/
connector.py
191 lines (152 loc) · 6.75 KB
/
connector.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
# Copyright (C) 2014-2017 Andrey Antukh <niwi@niwi.nz>
# Copyright (C) 2014-2017 Jesús Espino <jespinog@gmail.com>
# Copyright (C) 2014-2017 David Barragán <bameda@dbarragan.com>
# Copyright (C) 2014-2017 Alejandro Alonso <alejandro.alonso@kaleidos.net>
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import requests
import json
from collections import namedtuple
from urllib.parse import urljoin
from django.conf import settings
from django.utils.translation import ugettext_lazy as _
from taiga.base.connectors.exceptions import ConnectorBaseException
from taiga.base.exceptions import AuthenticationFailed
import logging
class OpenIDApiError(ConnectorBaseException):
pass
######################################################
# Data
######################################################
CLIENT_ID = getattr(settings, "OPENID_CLIENT_ID", None)
CLIENT_SCOPE = getattr(settings, "OPENID_SCOPE", "openid info")
CLIENT_SECRET = getattr(settings, "OPENID_CLIENT_SECRET", None)
TOKEN_URL = getattr(settings, "OPENID_TOKEN_URL", None)
USER_URL = getattr(settings, "OPENID_USER_URL", None)
OPENID_FILTER = getattr(settings, "OPENID_FILTER", "")
ID_FIELD = getattr(settings, "OPENID_ID_FIELD", "sub")
USER_FIELD = getattr(settings, "OPENID_USERNAME_FIELD", "preferred_username")
NAME_FIELD = getattr(settings, "OPENID_FULLNAME_FIELD", "name")
EMAIL_FIELD = getattr(settings, "OPENID_EMAIL_FIELD", "email")
FILTER_FIELD = getattr(settings, "OPENID_FILTER_FIELD", None)
HEADERS = {"Accept": "application/json", }
AuthInfo = namedtuple("AuthInfo", ["access_token"])
User = namedtuple("User", ["id", "username", "full_name", "email"])
######################################################
# utils
######################################################
def _build_url(*args, **kwargs) -> str:
"""
Return a valid url.
"""
resource_url = API_RESOURCES_URLS
for key in args:
resource_url = resource_url[key]
if kwargs:
resource_url = resource_url.format(**kwargs)
return urljoin(API_URL, resource_url)
def _get(url: str, headers: dict) -> dict:
"""
Make a GET call.
"""
response = requests.get(url, headers=headers)
data = response.json()
if response.status_code != 200:
raise OpenIDApiError({"status_code": response.status_code,
"error": data.get("error", "")})
return data
def _post(url: str, params: dict, headers: dict) -> dict:
"""
Make a POST call.
"""
response = requests.post(url, data=params, headers=headers)
try:
data = response.json()
except:
raise OpenIDApiError({"status_code": response.status_code,
"error": 'error from data not retrievable',
"content": response.content})
else:
if response.status_code != 200 or ("error" in data):
raise OpenIDApiError({"status_code": response.status_code,
"error": data.get("error", ""),
"content": response.content})
return data
######################################################
# Simple calls
######################################################
def login(access_code: str, token: str, redirect_uri: str, client_id: str = CLIENT_ID, client_secret: str = CLIENT_SECRET, headers: dict = HEADERS):
"""
Get access_token fron an user authorized code, the client id and the client secret key.
(See http://openid.net/specs/openid-connect-core-1_0.html#TokenEndpoint).
"""
if not CLIENT_ID or not CLIENT_SECRET:
raise OpenIDApiError({"error_message": _(
"The OpenID Connect plugin isn't properly configured. Please contact your sysadmin.")})
if token == "" or token == None:
url = TOKEN_URL
params = {"grant_type": "authorization_code",
"code": access_code,
"client_id": CLIENT_ID,
"client_secret": CLIENT_SECRET,
"redirect_uri": redirect_uri,
"scope": CLIENT_SCOPE
}
data = _post(url, params=params, headers=headers)
return AuthInfo(access_token=data.get("access_token", None))
else:
return AuthInfo(access_token=token)
def get_user_profile(headers: dict = HEADERS):
"""
Get authenticated user info.
(See openid.net/specs/openid-connect-core-1_0.html#UserInfo).
"""
url = USER_URL
data = _get(url, headers=headers)
if FILTER_FIELD:
userinfo_filter_claim = data.get(FILTER_FIELD, None)
if userinfo_filter_claim is None:
raise AuthenticationFailed("OPENID_FILTER_CLAIM provided but '{0}' not found in UserInfo".format(FILTER_FIELD))
filter_allowed = set(OPENID_FILTER.split(','))
if not filter_allowed & set(userinfo_filter_claim):
raise AuthenticationFailed("User does not satisfy OPENID_FILTER")
username = None
if data.get(USER_FIELD, None) != None :
username = data.get(USER_FIELD, None)
elif data.get("preferred_username", None) != None :
username = data.get("preferred_username", None)
elif data.get("full_name", None) != None :
username = data.get("full_name", None)
elif data.get("username", None) != None :
username = data.get("username", None)
elif data.get("email", None) != None :
username = data.get("email", None)
user = User(id=data.get(ID_FIELD, None),
username=username,
full_name=data.get(NAME_FIELD, None),
email=data.get(EMAIL_FIELD, None),
)
# logging.warning([data.get(ID_FIELD, None), username, data.get(NAME_FIELD, None), data.get(EMAIL_FIELD, None)])
return user
######################################################
# Convined calls
######################################################
def me(access_code: str, token: str, redirect_uri: str) -> tuple:
"""
Connect to a openid account and get all personal info (profile and the primary email).
"""
auth_info = login(access_code, token, redirect_uri)
headers = HEADERS.copy()
headers["Authorization"] = "Bearer {}".format(auth_info.access_token)
user = get_user_profile(headers=headers)
return user