pypomes-iam 0.5.2__py3-none-any.whl → 0.6.2__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.

Potentially problematic release.


This version of pypomes-iam might be problematic. Click here for more details.

@@ -3,17 +3,102 @@ from flask import Request, Response, request, jsonify
3
3
  from logging import Logger
4
4
  from typing import Any
5
5
 
6
- from .iam_common import IamServer, _iam_lock, _iam_server_from_endpoint
7
- from .iam_pomes import (
8
- user_login, user_logout,
9
- user_token, token_exchange, login_callback
6
+ from .iam_common import (
7
+ IamServer, IamParam, _iam_lock,
8
+ _get_iam_registry, _get_public_key,
9
+ _iam_server_from_endpoint, _iam_server_from_issuer
10
10
  )
11
+ from .iam_actions import (
12
+ action_login, action_logout,
13
+ action_token, action_exchange, action_callback
14
+ )
15
+ from .token_pomes import token_get_claims, token_validate
11
16
 
12
17
  # the logger for IAM service operations
13
18
  # (used exclusively at the HTTP endpoints - all other functions receive the logger as parameter)
14
19
  __IAM_LOGGER: Logger | None = None
15
20
 
16
21
 
22
+ def jwt_required(func: callable) -> callable:
23
+ """
24
+ Create a decorator to authenticate service endpoints with JWT tokens.
25
+
26
+ :param func: the function being decorated
27
+ """
28
+ # ruff: noqa: ANN003 - Missing type annotation for *{name}
29
+ def wrapper(*args, **kwargs) -> Response:
30
+ response: Response = __request_validate(request=request)
31
+ return response if response else func(*args, **kwargs)
32
+
33
+ # prevent a rogue error ("View function mapping is overwriting an existing endpoint function")
34
+ wrapper.__name__ = func.__name__
35
+
36
+ return wrapper
37
+
38
+
39
+ def __request_validate(request: Request) -> Response:
40
+ """
41
+ Verify whether the HTTP *request* has the proper authorization, as per the JWT standard.
42
+
43
+ This implementation assumes that HTTP requests are handled with the *Flask* framework.
44
+ Because this code has a high usage frequency, only authentication failures are logged.
45
+
46
+ :param request: the *request* to be verified
47
+ :return: *None* if the *request* is valid, otherwise a *Response* reporting the error
48
+ """
49
+ # initialize the return variable
50
+ result: Response | None = None
51
+
52
+ # retrieve the authorization from the request header
53
+ auth_header: str = request.headers.get("Authorization")
54
+
55
+ # validate the authorization token
56
+ bad_token: bool = True
57
+ if auth_header and auth_header.startswith("Bearer "):
58
+ # extract and validate the JWT access token
59
+ token: str = auth_header.split(" ")[1]
60
+ claims: dict[str, Any] = token_get_claims(token=token)
61
+ if claims:
62
+ issuer: str = claims["payload"].get("iss")
63
+ recipient_attr: str | None = None
64
+ recipient_id: str = request.values.get("user-id") or request.values.get("login")
65
+ with _iam_lock:
66
+ iam_server: IamServer = _iam_server_from_issuer(issuer=issuer,
67
+ errors=None,
68
+ logger=__IAM_LOGGER)
69
+ if iam_server:
70
+ # validate the token's recipient only if a user identification is provided
71
+ if recipient_id:
72
+ registry: dict[str, Any] = _get_iam_registry(iam_server=iam_server,
73
+ errors=None,
74
+ logger=__IAM_LOGGER)
75
+ if registry:
76
+ recipient_attr = registry[IamParam.RECIPIENT_ATTR]
77
+ public_key: str = _get_public_key(iam_server=iam_server,
78
+ errors=None,
79
+ logger=__IAM_LOGGER)
80
+ # validate the token (log errors, only)
81
+ errors: list[str] = []
82
+ if public_key and token_validate(token=token,
83
+ issuer=issuer,
84
+ recipient_id=recipient_id,
85
+ recipient_attr=recipient_attr,
86
+ public_key=public_key,
87
+ errors=errors):
88
+ # token is valid
89
+ bad_token = False
90
+ elif __IAM_LOGGER:
91
+ __IAM_LOGGER.error("; ".join(errors))
92
+ if bad_token and __IAM_LOGGER:
93
+ __IAM_LOGGER.error(f"Authorization refused for token {token}")
94
+
95
+ # deny the authorization
96
+ if bad_token:
97
+ result = Response(response="Authorization failed",
98
+ status=401)
99
+ return result
100
+
101
+
17
102
  def logger_register(logger: Logger) -> None:
18
103
  """
19
104
  Register the logger for HTTP services.
@@ -60,10 +145,10 @@ def service_login() -> Response:
60
145
  logger=__IAM_LOGGER)
61
146
  if iam_server:
62
147
  # obtain the login URL
63
- login_url: str = user_login(iam_server=iam_server,
64
- args=request.args,
65
- errors=errors,
66
- logger=__IAM_LOGGER)
148
+ login_url: str = action_login(iam_server=iam_server,
149
+ args=request.args,
150
+ errors=errors,
151
+ logger=__IAM_LOGGER)
67
152
  if login_url:
68
153
  result = jsonify({"login-url": login_url})
69
154
  if errors:
@@ -106,10 +191,10 @@ def service_logout() -> Response:
106
191
  logger=__IAM_LOGGER)
107
192
  if iam_server:
108
193
  # logout the user
109
- user_logout(iam_server=iam_server,
110
- args=request.args,
111
- errors=errors,
112
- logger=__IAM_LOGGER)
194
+ action_logout(iam_server=iam_server,
195
+ args=request.args,
196
+ errors=errors,
197
+ logger=__IAM_LOGGER)
113
198
  if errors:
114
199
  result = Response(response="; ".join(errors),
115
200
  status=400)
@@ -160,10 +245,10 @@ def service_callback() -> Response:
160
245
  logger=__IAM_LOGGER)
161
246
  if iam_server:
162
247
  # process the callback operation
163
- token_data = login_callback(iam_server=iam_server,
164
- args=request.args,
165
- errors=errors,
166
- logger=__IAM_LOGGER)
248
+ token_data = action_callback(iam_server=iam_server,
249
+ args=request.args,
250
+ errors=errors,
251
+ logger=__IAM_LOGGER)
167
252
  result: Response
168
253
  if errors:
169
254
  result = jsonify({"errors": "; ".join(errors)})
@@ -171,9 +256,9 @@ def service_callback() -> Response:
171
256
  else:
172
257
  result = jsonify({"user-id": token_data[0],
173
258
  "access-token": token_data[1]})
174
- # log the response
175
259
  if __IAM_LOGGER:
176
- __IAM_LOGGER.debug(msg=f"Response {result}, {result.get_data(as_text=True)}")
260
+ # log the response (the returned data is not logged, as it contains the token)
261
+ __IAM_LOGGER.debug(msg=f"Response {result}")
177
262
 
178
263
  return result
179
264
 
@@ -215,10 +300,10 @@ def service_token() -> Response:
215
300
  if iam_server:
216
301
  # retrieve the token
217
302
  errors: list[str] = []
218
- token: str = user_token(iam_server=iam_server,
219
- args=args,
220
- errors=errors,
221
- logger=__IAM_LOGGER)
303
+ token: str = action_token(iam_server=iam_server,
304
+ args=args,
305
+ errors=errors,
306
+ logger=__IAM_LOGGER)
222
307
  else:
223
308
  msg: str = "User identification not provided"
224
309
  errors.append(msg)
@@ -232,9 +317,9 @@ def service_token() -> Response:
232
317
  else:
233
318
  result = jsonify({"user-id": user_id,
234
319
  "access-token": token})
235
- # log the response
236
320
  if __IAM_LOGGER:
237
- __IAM_LOGGER.debug(msg=f"Response {result}, {result.get_data(as_text=True)}")
321
+ # log the response (the returned data is not logged, as it contains the token)
322
+ __IAM_LOGGER.debug(msg=f"Response {result}")
238
323
 
239
324
  return result
240
325
 
@@ -278,10 +363,10 @@ def service_exchange() -> Response:
278
363
  token_data: dict[str, Any] | None = None
279
364
  if iam_server:
280
365
  errors: list[str] = []
281
- token_data = token_exchange(iam_server=iam_server,
282
- args=request.args,
283
- errors=errors,
284
- logger=__IAM_LOGGER)
366
+ token_data = action_exchange(iam_server=iam_server,
367
+ args=request.args,
368
+ errors=errors,
369
+ logger=__IAM_LOGGER)
285
370
  result: Response
286
371
  if errors:
287
372
  result = Response(response="; ".join(errors),
@@ -3,29 +3,49 @@ import requests
3
3
  import sys
4
4
  from base64 import b64encode
5
5
  from datetime import datetime
6
+ from enum import StrEnum
6
7
  from logging import Logger
7
8
  from pypomes_core import TZ_LOCAL, exc_format
8
- from threading import RLock
9
+ from threading import Lock
9
10
  from typing import Any, Final
10
11
 
12
+
13
+ class ProviderParam(StrEnum):
14
+ """
15
+ Parameters for configuring a *JWT* token provider.
16
+ """
17
+ URL = "url"
18
+ USER = "user"
19
+ PWD = "pwd"
20
+ CUSTOM_AUTH = "custom-auth"
21
+ HEADER_DATA = "headers-data"
22
+ BODY_DATA = "body-data"
23
+ ACCESS_TOKEN = "access-token"
24
+ ACCESS_EXPIRATION = "access-expiration"
25
+ REFRESH_TOKEN = "refresh-token"
26
+ REFRESH_EXPIRATION = "refresh-expiration"
27
+
28
+
11
29
  # structure:
12
30
  # {
13
31
  # <provider-id>: {
14
32
  # "url": <strl>,
15
33
  # "user": <str>,
16
34
  # "pwd": <str>,
17
- # "basic-auth": <bool>,
35
+ # "custom-auth": <bool>,
18
36
  # "headers-data": <dict[str, str]>,
19
37
  # "body-data": <dict[str, str],
20
38
  # "access-token": <str>,
21
- # "access-expiration": <timestamp>
39
+ # "access-expiration": <timestamp>,
40
+ # "refresh-token": <str>,
41
+ # "refresh-expiration": <timestamp>
22
42
  # }
23
43
  # }
24
44
  _provider_registry: Final[dict[str, dict[str, Any]]] = {}
25
45
 
26
46
  # the lock protecting the data in '_provider_registry'
27
47
  # (because it is 'Final' and set at declaration time, it can be accessed through simple imports)
28
- _provider_lock: Final[RLock] = RLock()
48
+ _provider_lock: Final[Lock] = Lock()
29
49
 
30
50
 
31
51
  def provider_register(provider_id: str,
@@ -58,16 +78,16 @@ def provider_register(provider_id: str,
58
78
 
59
79
  with _provider_lock:
60
80
  _provider_registry[provider_id] = {
61
- "url": auth_url,
62
- "user": auth_user,
63
- "pwd": auth_pwd,
64
- "custom-auth": custom_auth,
65
- "headers-data": headers_data,
66
- "body-data": body_data,
67
- "access-token": None,
68
- "access-expiration": 0,
69
- "refresh-token": None,
70
- "refresh-expiration": 0
81
+ ProviderParam.URL: auth_url,
82
+ ProviderParam.USER: auth_user,
83
+ ProviderParam.PWD: auth_pwd,
84
+ ProviderParam.CUSTOM_AUTH: custom_auth,
85
+ ProviderParam.HEADER_DATA: headers_data,
86
+ ProviderParam.BODY_DATA: body_data,
87
+ ProviderParam.ACCESS_TOKEN: None,
88
+ ProviderParam.ACCESS_EXPIRATION: 0,
89
+ ProviderParam.REFRESH_TOKEN: None,
90
+ ProviderParam.REFRESH_EXPIRATION: 0
71
91
  }
72
92
 
73
93
 
@@ -86,76 +106,137 @@ def provider_get_token(provider_id: str,
86
106
  # initialize the return variable
87
107
  result: str | None = None
88
108
 
89
- err_msg: str | None = None
90
109
  with _provider_lock:
91
110
  provider: dict[str, Any] = _provider_registry.get(provider_id)
92
111
  if provider:
93
- now: float = datetime.now(tz=TZ_LOCAL).timestamp()
94
- if now > provider.get("access-expiration"):
95
- user: str = provider.get("user")
96
- pwd: str = provider.get("pwd")
97
- headers_data: dict[str, str] = provider.get("headers-data") or {}
98
- body_data: dict[str, str] = provider.get("body-data") or {}
99
- custom_auth: tuple[str, str] = provider.get("custom-auth")
100
- if custom_auth:
101
- body_data[custom_auth[0]] = user
102
- body_data[custom_auth[1]] = pwd
103
- else:
104
- enc_bytes: bytes = b64encode(f"{user}:{pwd}".encode())
105
- headers_data["Authorization"] = f"Basic {enc_bytes.decode()}"
106
- url: str = provider.get("url")
107
- if logger:
108
- logger.debug(msg=f"POST {url}, {json.dumps(obj=body_data,
109
- ensure_ascii=False)}")
110
- try:
111
- # typical return on a token request:
112
- # {
113
- # "token_type": "Bearer",
114
- # "access_token": <str>,
115
- # "expires_in": <number-of-seconds>,
116
- # optional data:
117
- # "refresh_token": <str>,
118
- # "refresh_expires_in": <number-of-seconds>
119
- # }
120
- response: requests.Response = requests.post(url=url,
121
- data=body_data,
122
- headers=headers_data,
123
- timeout=None)
124
- if response.status_code < 200 or response.status_code >= 300:
125
- # request resulted in error, report the problem
126
- err_msg = (f"POST failure, "
127
- f"status {response.status_code}, reason {response.reason}")
112
+ now: int = int(datetime.now(tz=TZ_LOCAL).timestamp())
113
+ if now < provider.get(ProviderParam.ACCESS_EXPIRATION):
114
+ # retrieve the stored access token
115
+ result = provider.get(ProviderParam.ACCESS_TOKEN)
116
+ else:
117
+ # access token has expired
118
+ header_data: dict[str, str] | None = None
119
+ body_data: dict[str, str] | None = None
120
+ url: str = provider.get(ProviderParam.URL)
121
+ refresh_token: str = provider.get(ProviderParam.REFRESH_TOKEN)
122
+ if refresh_token:
123
+ # refresh token exists
124
+ refresh_expiration: int = provider.get(ProviderParam.REFRESH_EXPIRATION)
125
+ if now < refresh_expiration:
126
+ # refresh token has not expired
127
+ header_data: dict[str, str] = {
128
+ "Content-Type": "application/json"
129
+ }
130
+ body_data: dict[str, str] = {
131
+ "grant_type": "refresh_token",
132
+ "refresh_token": refresh_token
133
+ }
134
+ if not body_data:
135
+ # refresh token does not exist or has expired
136
+ user: str = provider.get(ProviderParam.USER)
137
+ pwd: str = provider.get(ProviderParam.PWD)
138
+ headers_data: dict[str, str] = provider.get(ProviderParam.HEADER_DATA) or {}
139
+ body_data: dict[str, str] = provider.get(ProviderParam.BODY_DATA) or {}
140
+ custom_auth: tuple[str, str] = provider.get(ProviderParam.CUSTOM_AUTH)
141
+ if custom_auth:
142
+ body_data[custom_auth[0]] = user
143
+ body_data[custom_auth[1]] = pwd
128
144
  else:
129
- # request succeeded
130
- if logger:
131
- logger.debug(msg=f"POST success, status {response.status_code}")
132
- reply: dict[str, Any] = response.json()
133
- provider["access-token"] = reply.get("access_token")
134
- provider["access-expiration"] = now + int(reply.get("expires_in"))
135
- if reply.get("refresh_token"):
136
- provider["refresh-token"] = reply["refesh_token"]
137
- if reply.get("refresh_expires_in"):
138
- provider["refresh-expiration"] = now + int(reply.get("refresh_expires_in"))
139
- else:
140
- provider["refresh-expiration"] = sys.maxsize
141
- if logger:
142
- logger.debug(msg=f"POST {url}: status {response.status_code}")
143
- except Exception as e:
144
- # the operation raised an exception
145
- err_msg = exc_format(exc=e,
146
- exc_info=sys.exc_info())
147
- err_msg = f"POST error, '{err_msg}'"
148
- else:
149
- err_msg: str = f"Provider '{provider_id}' not registered"
150
-
151
- if err_msg:
152
- if isinstance(errors, list):
153
- errors.append(err_msg)
154
- if logger:
155
- logger.error(msg=err_msg)
156
- else:
157
- result = provider.get("access-token")
145
+ enc_bytes: bytes = b64encode(f"{user}:{pwd}".encode())
146
+ headers_data["Authorization"] = f"Basic {enc_bytes.decode()}"
147
+
148
+ # obtain the token
149
+ token_data: dict[str, Any] = __post_for_token(url=url,
150
+ header_data=header_data,
151
+ body_data=body_data,
152
+ errors=errors,
153
+ logger=logger)
154
+ if token_data:
155
+ result = token_data.get("access_token")
156
+ provider[ProviderParam.ACCESS_TOKEN] = result
157
+ provider[ProviderParam.ACCESS_EXPIRATION] = now + token_data.get("expires_in")
158
+ refresh_token = token_data.get("refresh_token")
159
+ if refresh_token:
160
+ provider[ProviderParam.REFRESH_TOKEN] = refresh_token
161
+ refresh_exp: int = token_data.get("refresh_expires_in")
162
+ provider[ProviderParam.REFRESH_EXPIRATION] = (now + refresh_exp) \
163
+ if refresh_exp else sys.maxsize
164
+
165
+ elif logger or isinstance(errors, list):
166
+ msg: str = f"Unknown provider '{provider_id}'"
167
+ if logger:
168
+ logger.error(msg=msg)
169
+ if isinstance(errors, list):
170
+ errors.append(msg)
158
171
 
159
172
  return result
160
173
 
161
174
 
175
+ def __post_for_token(url: str,
176
+ header_data: dict[str, str],
177
+ body_data: dict[str, Any],
178
+ errors: list[str] | None,
179
+ logger: Logger | None) -> dict[str, Any] | None:
180
+ """
181
+ Send a *POST* request to *url* and return the token data obtained.
182
+
183
+ Token acquisition and token refresh are the two types of requests contemplated herein.
184
+ For the former, *header_data* and *body_data* will have contents customized to the specific provider,
185
+ whereas the latter's *body_data* will contain these two attributes:
186
+ - "grant_type": "refresh_token"
187
+ - "refresh_token": <current-refresh-token>
188
+
189
+ The typical data set returned contains the following attributes:
190
+ {
191
+ "token_type": "Bearer",
192
+ "access_token": <str>,
193
+ "expires_in": <number-of-seconds>,
194
+ "refresh_token": <str>,
195
+ "refesh_expires_in": <number-of-seconds>
196
+ }
197
+
198
+ :param url: the target URL
199
+ :param header_data: the data to send in the header of the request
200
+ :param body_data: the data to send in the body of the request
201
+ :param errors: incidental errors
202
+ :param logger: optional logger
203
+ :return: the token data, or *None* if error
204
+ """
205
+ # initialize the return variable
206
+ result: dict[str, Any] | None = None
207
+
208
+ # log the POST
209
+ if logger:
210
+ logger.debug(msg=f"POST {url}, {json.dumps(obj=body_data,
211
+ ensure_ascii=False)}")
212
+ try:
213
+ response: requests.Response = requests.post(url=url,
214
+ data=body_data,
215
+ headers=header_data,
216
+ timeout=None)
217
+ if response.status_code == 200:
218
+ # request succeeded
219
+ result = response.json()
220
+ if logger:
221
+ logger.debug(msg=f"POST success, status {response.status_code}")
222
+ else:
223
+ # request failed, report the problem
224
+ msg: str = (f"POST failure, "
225
+ f"status {response.status_code}, reason {response.reason}")
226
+ if hasattr(response, "content") and response.content:
227
+ msg += f", content '{response.content}'"
228
+ if logger:
229
+ logger.error(msg=msg)
230
+ if isinstance(errors, list):
231
+ errors.append(msg)
232
+ except Exception as e:
233
+ # the operation raised an exception
234
+ err_msg = exc_format(exc=e,
235
+ exc_info=sys.exc_info())
236
+ msg: str = f"POST error, {err_msg}"
237
+ if logger:
238
+ logger.debug(msg=msg)
239
+ if isinstance(errors, list):
240
+ errors.append(msg)
241
+
242
+ return result
@@ -117,8 +117,6 @@ def token_validate(token: str,
117
117
  "verify_nbf": False,
118
118
  "verify_signature": token_alg in ["RS256", "RS512"] and public_key is not None
119
119
  }
120
- if issuer:
121
- options["require"].append("iss")
122
120
  try:
123
121
  # raises:
124
122
  # InvalidTokenError: token is invalid
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: pypomes_iam
3
- Version: 0.5.2
3
+ Version: 0.6.2
4
4
  Summary: A collection of Python pomes, penyeach (IAM modules)
5
5
  Project-URL: Homepage, https://github.com/TheWiseCoder/PyPomes-IAM
6
6
  Project-URL: Bug Tracker, https://github.com/TheWiseCoder/PyPomes-IAM/issues
@@ -10,7 +10,6 @@ Classifier: License :: OSI Approved :: MIT License
10
10
  Classifier: Operating System :: OS Independent
11
11
  Classifier: Programming Language :: Python :: 3
12
12
  Requires-Python: >=3.12
13
- Requires-Dist: cachetools>=6.2.1
14
13
  Requires-Dist: flask>=3.1.2
15
14
  Requires-Dist: pyjwt>=2.10.1
16
15
  Requires-Dist: pypomes-core>=2.8.1
@@ -0,0 +1,11 @@
1
+ pypomes_iam/__init__.py,sha256=_6tSFfjuU-5p6TAMqNLHSL6IQmaJMSYuEW-TG3ybhTI,1044
2
+ pypomes_iam/iam_actions.py,sha256=DhDZcY6j3uSWnm5Q5SrA5jriTUCatLqJKd9K7IjA2i8,39283
3
+ pypomes_iam/iam_common.py,sha256=ki_-m6fqJqUbGjgTD41r9zaE-FOXgA_c_tLisIYYTfU,15457
4
+ pypomes_iam/iam_pomes.py,sha256=XkxpwwGivUR3Y1TKR6McrqLUnpFJhRvIrsEn9T_Ut9A,7351
5
+ pypomes_iam/iam_services.py,sha256=IkCjrKDX1Ix7BiHh-BL3VKz5xogcNC8prXkHyJzQoZ8,15862
6
+ pypomes_iam/provider_pomes.py,sha256=3mMj5LQs53YEINUEOfFBAxOwOP3aOR_szlE4daEBLK0,10523
7
+ pypomes_iam/token_pomes.py,sha256=K4nSAotKUoHIE2s3ltc_nVimlNeKS9tnD-IlslkAvkk,6626
8
+ pypomes_iam-0.6.2.dist-info/METADATA,sha256=XeUm7yxjoWFURVvoHDSoYkF5iROCC696PPuHydJ1UIs,661
9
+ pypomes_iam-0.6.2.dist-info/WHEEL,sha256=qtCwoSJWgHk21S1Kb4ihdzI2rlJ1ZKaIurTj_ngOhyQ,87
10
+ pypomes_iam-0.6.2.dist-info/licenses/LICENSE,sha256=YvUELgV8qvXlaYsy9hXG5EW3Bmsrkw-OJmmILZnonAc,1086
11
+ pypomes_iam-0.6.2.dist-info/RECORD,,
@@ -1,125 +0,0 @@
1
- from cachetools import Cache, FIFOCache
2
- from flask import Flask
3
- from logging import Logger
4
- from pypomes_core import (
5
- APP_PREFIX, env_get_int, env_get_str
6
- )
7
- from typing import Any, Final
8
-
9
- from .iam_common import _IAM_SERVERS, IamServer, _iam_lock
10
- from .iam_pomes import user_token
11
-
12
- JUSBR_CLIENT_ID: Final[str] = env_get_str(key=f"{APP_PREFIX}_JUSBR_CLIENT_ID")
13
- JUSBR_CLIENT_SECRET: Final[str] = env_get_str(key=f"{APP_PREFIX}_JUSBR_CLIENT_SECRET")
14
- JUSBR_CLIENT_TIMEOUT: Final[int] = env_get_int(key=f"{APP_PREFIX}_JUSBR_CLIENT_TIMEOUT")
15
-
16
- JUSBR_ENDPOINT_CALLBACK: Final[str] = env_get_str(key=f"{APP_PREFIX}_JUSBR_ENDPOINT_CALLBACK",
17
- def_value="/iam/jusbr:callback")
18
- JUSBR_ENDPOINT_LOGIN: Final[str] = env_get_str(key=f"{APP_PREFIX}_JUSBR_ENDPOINT_LOGIN",
19
- def_value="/iam/jusbr:login")
20
- JUSBR_ENDPOINT_LOGOUT: Final[str] = env_get_str(key=f"{APP_PREFIX}_JUSBR_ENDPOINT_LOGOUT",
21
- def_value="/iam/jusbr:logout")
22
- JUSBR_ENDPOINT_TOKEN: Final[str] = env_get_str(key=f"{APP_PREFIX}_JUSBR_ENDPOINT_TOKEN",
23
- def_value="/iam/jusbr:get-token")
24
-
25
- JUSBR_PUBLIC_KEY_LIFETIME: Final[int] = env_get_int(key=f"{APP_PREFIX}_JUSBR_PUBLIC_KEY_LIFETIME",
26
- def_value=86400) # 24 hours
27
- JUSBR_REALM: Final[str] = env_get_str(key=f"{APP_PREFIX}_JUSBR_REALM")
28
- JUSBR_RECIPIENT_ATTR: Final[str] = env_get_str(key=f"{APP_PREFIX}_JUSBR_RECIPIENT_ATTR",
29
- def_value="preferred_username")
30
- JUSBR_URL_AUTH_BASE: Final[str] = env_get_str(key=f"{APP_PREFIX}_JUSBR_URL_AUTH_BASE")
31
-
32
-
33
- def jusbr_setup(flask_app: Flask,
34
- base_url: str = JUSBR_URL_AUTH_BASE,
35
- realm: str = JUSBR_REALM,
36
- client_id: str = JUSBR_CLIENT_ID,
37
- client_secret: str = JUSBR_CLIENT_SECRET,
38
- client_timeout: int = JUSBR_CLIENT_TIMEOUT,
39
- public_key_lifetime: int | None = JUSBR_PUBLIC_KEY_LIFETIME,
40
- recipient_attribute: str | None = JUSBR_RECIPIENT_ATTR,
41
- callback_endpoint: str | None = JUSBR_ENDPOINT_CALLBACK,
42
- login_endpoint: str | None = JUSBR_ENDPOINT_LOGIN,
43
- logout_endpoint: str | None = JUSBR_ENDPOINT_LOGOUT,
44
- token_endpoint: str | None = JUSBR_ENDPOINT_TOKEN) -> None:
45
- """
46
- Configure the JusBR IAM.
47
-
48
- This should be invoked only once, before the first access to a JusBR service.
49
-
50
- :param flask_app: the Flask application
51
- :param base_url: base URL to request JusBR services
52
- :param realm: the JusBR realm
53
- :param client_id: the client's identification with JusBR
54
- :param client_secret: the client's password with JusBR
55
- :param client_timeout: timeout for login authentication (in seconds,defaults to no timeout)
56
- :param public_key_lifetime: how long to use JusBR's public key, before refreshing it (in seconds)
57
- :param recipient_attribute: attribute in the token's payload holding the token's subject
58
- :param callback_endpoint: endpoint for the callback from JusBR
59
- :param login_endpoint: endpoint for redirecting user to JusBR's login page
60
- :param logout_endpoint: endpoint for terminating user access to JusBR
61
- :param token_endpoint: endpoint for retrieving JusBR's authentication token
62
- """
63
- from .iam_services import service_login, service_logout, service_callback, service_token
64
-
65
- # configure the JusBR registry
66
- cache: Cache = FIFOCache(maxsize=1048576)
67
- cache["users"] = {}
68
- with _iam_lock:
69
- _IAM_SERVERS[IamServer.IAM_JUSRBR] = {
70
- "base-url": f"{base_url}/realms/{realm}",
71
- "client-id": client_id,
72
- "client-secret": client_secret,
73
- "client-timeout": client_timeout,
74
- "public-key": None,
75
- "pk-lifetime": public_key_lifetime,
76
- "pk-expiration": 0,
77
- "recipient-attr": recipient_attribute,
78
- "cache": cache
79
- }
80
-
81
- # establish the endpoints
82
- if callback_endpoint:
83
- flask_app.add_url_rule(rule=callback_endpoint,
84
- endpoint="jusbr-callback",
85
- view_func=service_callback,
86
- methods=["GET"])
87
- if login_endpoint:
88
- flask_app.add_url_rule(rule=login_endpoint,
89
- endpoint="jusbr-login",
90
- view_func=service_login,
91
- methods=["GET"])
92
- if logout_endpoint:
93
- flask_app.add_url_rule(rule=logout_endpoint,
94
- endpoint="jusbr-logout",
95
- view_func=service_logout,
96
- methods=["GET"])
97
- if token_endpoint:
98
- flask_app.add_url_rule(rule=token_endpoint,
99
- endpoint="jusbr-token",
100
- view_func=service_token,
101
- methods=["GET"])
102
-
103
-
104
- def jusbr_get_token(user_id: str,
105
- errors: list[str] = None,
106
- logger: Logger = None) -> str:
107
- """
108
- Retrieve a JusBR authentication token for *user_id*.
109
-
110
- :param user_id: the user's identification
111
- :param errors: incidental errors
112
- :param logger: optional logger
113
- :return: the uthentication tokem
114
- """
115
- # declare the return variable
116
- result: str
117
-
118
- # retrieve the token
119
- args: dict[str, Any] = {"user-id": user_id}
120
- with _iam_lock:
121
- result = user_token(iam_server=IamServer.IAM_JUSRBR,
122
- args=args,
123
- errors=errors,
124
- logger=logger)
125
- return result