dserver-token-generator-plugin-oauth2 0.1.0__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.
- dserver_token_generator_plugin_oauth2/__init__.py +36 -0
- dserver_token_generator_plugin_oauth2/blueprint.py +493 -0
- dserver_token_generator_plugin_oauth2/cli.py +228 -0
- dserver_token_generator_plugin_oauth2/config.py +274 -0
- dserver_token_generator_plugin_oauth2/device_flow.py +279 -0
- dserver_token_generator_plugin_oauth2/jwt_utils.py +189 -0
- dserver_token_generator_plugin_oauth2/plugin.py +131 -0
- dserver_token_generator_plugin_oauth2/sql_models.py +37 -0
- dserver_token_generator_plugin_oauth2/user_provisioning.py +97 -0
- dserver_token_generator_plugin_oauth2/version.py +24 -0
- dserver_token_generator_plugin_oauth2-0.1.0.dist-info/METADATA +351 -0
- dserver_token_generator_plugin_oauth2-0.1.0.dist-info/RECORD +14 -0
- dserver_token_generator_plugin_oauth2-0.1.0.dist-info/WHEEL +4 -0
- dserver_token_generator_plugin_oauth2-0.1.0.dist-info/entry_points.txt +6 -0
|
@@ -0,0 +1,228 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Flask CLI commands for OAuth2 plugin management.
|
|
3
|
+
|
|
4
|
+
These commands help with setup, debugging, and maintenance of the
|
|
5
|
+
OAuth2 integration.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
import click
|
|
9
|
+
from flask import current_app
|
|
10
|
+
from flask.cli import with_appcontext
|
|
11
|
+
|
|
12
|
+
from .config import PluginConfig, PROVIDER_PRESETS
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
@click.group("oauth2")
|
|
16
|
+
def oauth2_cli():
|
|
17
|
+
"""OAuth2 token generator management commands."""
|
|
18
|
+
pass
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
@oauth2_cli.command("show-config")
|
|
22
|
+
@with_appcontext
|
|
23
|
+
def show_config():
|
|
24
|
+
"""Display current OAuth2 configuration."""
|
|
25
|
+
config = PluginConfig.from_env()
|
|
26
|
+
|
|
27
|
+
click.echo("=== OAuth2 Provider Configuration ===")
|
|
28
|
+
click.echo(f"Provider Name: {config.oauth2.name}")
|
|
29
|
+
click.echo(f"Authorization URL: {config.oauth2.authorization_url or 'Not configured'}")
|
|
30
|
+
click.echo(f"Token URL: {config.oauth2.token_url or 'Not configured'}")
|
|
31
|
+
click.echo(f"Userinfo URL: {config.oauth2.userinfo_url or 'Not configured'}")
|
|
32
|
+
click.echo(f"Redirect URI: {config.oauth2.redirect_uri}")
|
|
33
|
+
click.echo(f"Scope: {config.oauth2.scope}")
|
|
34
|
+
click.echo(f"Client ID: {config.oauth2.client_id[:8] + '...' if config.oauth2.client_id else 'Not configured'}")
|
|
35
|
+
click.echo(f"Client Secret: {'Configured' if config.oauth2.client_secret else 'Not configured'}")
|
|
36
|
+
|
|
37
|
+
click.echo("\n=== Attribute Mapping ===")
|
|
38
|
+
for provider_field, internal_field in config.oauth2.attribute_map.items():
|
|
39
|
+
click.echo(f" {provider_field} -> {internal_field}")
|
|
40
|
+
click.echo(f"Username field: {config.oauth2.username_field}")
|
|
41
|
+
|
|
42
|
+
click.echo("\n=== JWT Configuration ===")
|
|
43
|
+
click.echo(f"Private Key File: {config.jwt.private_key_file}")
|
|
44
|
+
click.echo(f"Public Key File: {config.jwt.public_key_file}")
|
|
45
|
+
click.echo(f"Algorithm: {config.jwt.algorithm}")
|
|
46
|
+
click.echo(f"Issuer: {config.jwt.issuer}")
|
|
47
|
+
click.echo(f"Token Expiry: {config.jwt.token_expiry_hours} hours")
|
|
48
|
+
|
|
49
|
+
click.echo("\n=== User Provisioning ===")
|
|
50
|
+
click.echo(f"Auto Provision: {config.auto_provision_users}")
|
|
51
|
+
click.echo(f"Default Permissions: {config.default_user_permissions}")
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
@oauth2_cli.command("list-presets")
|
|
55
|
+
def list_presets():
|
|
56
|
+
"""List available provider presets."""
|
|
57
|
+
click.echo("=== Available Provider Presets ===\n")
|
|
58
|
+
|
|
59
|
+
for name, preset in PROVIDER_PRESETS.items():
|
|
60
|
+
click.echo(f"{name}:")
|
|
61
|
+
click.echo(f" Authorization URL: {preset['authorization_url']}")
|
|
62
|
+
click.echo(f" Token URL: {preset['token_url']}")
|
|
63
|
+
click.echo(f" Userinfo URL: {preset.get('userinfo_url') or 'N/A'}")
|
|
64
|
+
click.echo(f" Scope: {preset['scope']}")
|
|
65
|
+
click.echo()
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
@oauth2_cli.command("show-preset")
|
|
69
|
+
@click.argument("name")
|
|
70
|
+
def show_preset(name):
|
|
71
|
+
"""Show environment variables for a provider preset."""
|
|
72
|
+
preset = PROVIDER_PRESETS.get(name.lower())
|
|
73
|
+
|
|
74
|
+
if not preset:
|
|
75
|
+
click.echo(f"Unknown preset: {name}", err=True)
|
|
76
|
+
click.echo(f"Available presets: {', '.join(PROVIDER_PRESETS.keys())}")
|
|
77
|
+
return
|
|
78
|
+
|
|
79
|
+
click.echo(f"=== Environment Variables for {name} ===\n")
|
|
80
|
+
click.echo("# Copy these to your docker-compose.yml or .env file\n")
|
|
81
|
+
|
|
82
|
+
click.echo(f'OAUTH2_PROVIDER_NAME: "{preset["name"]}"')
|
|
83
|
+
click.echo(f'OAUTH2_AUTHORIZATION_URL: "{preset["authorization_url"]}"')
|
|
84
|
+
click.echo(f'OAUTH2_TOKEN_URL: "{preset["token_url"]}"')
|
|
85
|
+
if preset.get("userinfo_url"):
|
|
86
|
+
click.echo(f'OAUTH2_USERINFO_URL: "{preset["userinfo_url"]}"')
|
|
87
|
+
click.echo(f'OAUTH2_SCOPE: "{preset["scope"]}"')
|
|
88
|
+
|
|
89
|
+
# Format attribute map
|
|
90
|
+
attr_map = ",".join(f"{k}:{v}" for k, v in preset["attribute_map"].items())
|
|
91
|
+
click.echo(f'OAUTH2_ATTRIBUTE_MAP: "{attr_map}"')
|
|
92
|
+
click.echo(f'OAUTH2_USERNAME_FIELD: "{preset["username_field"]}"')
|
|
93
|
+
|
|
94
|
+
click.echo("\n# You must also set:")
|
|
95
|
+
click.echo("OAUTH2_CLIENT_ID: <your-client-id>")
|
|
96
|
+
click.echo("OAUTH2_CLIENT_SECRET: <your-client-secret>")
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
@oauth2_cli.command("test-jwt")
|
|
100
|
+
@click.option("--username", default="test@example.com", help="Test username")
|
|
101
|
+
@with_appcontext
|
|
102
|
+
def test_jwt(username):
|
|
103
|
+
"""Generate a test JWT token."""
|
|
104
|
+
from .jwt_utils import JwtTokenGenerator
|
|
105
|
+
from .config import JwtConfig
|
|
106
|
+
|
|
107
|
+
try:
|
|
108
|
+
jwt_config = JwtConfig.from_env()
|
|
109
|
+
generator = JwtTokenGenerator(jwt_config)
|
|
110
|
+
|
|
111
|
+
token = generator.generate_token(
|
|
112
|
+
username=username,
|
|
113
|
+
email=f"{username}",
|
|
114
|
+
display_name="Test User",
|
|
115
|
+
permissions=["search", "retrieve"],
|
|
116
|
+
)
|
|
117
|
+
|
|
118
|
+
click.echo("=== Generated JWT Token ===")
|
|
119
|
+
click.echo(token)
|
|
120
|
+
click.echo("\n=== Token Verification ===")
|
|
121
|
+
|
|
122
|
+
claims = generator.verify_token(token)
|
|
123
|
+
if claims:
|
|
124
|
+
click.echo("Token is valid!")
|
|
125
|
+
for key, value in claims.items():
|
|
126
|
+
click.echo(f" {key}: {value}")
|
|
127
|
+
else:
|
|
128
|
+
click.echo("Token verification failed!", err=True)
|
|
129
|
+
|
|
130
|
+
except FileNotFoundError as e:
|
|
131
|
+
click.echo(f"Error: {e}", err=True)
|
|
132
|
+
click.echo("Make sure JWT key files are configured correctly.")
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
@oauth2_cli.command("validate-config")
|
|
136
|
+
@with_appcontext
|
|
137
|
+
def validate_config():
|
|
138
|
+
"""Validate the current configuration."""
|
|
139
|
+
from pathlib import Path
|
|
140
|
+
|
|
141
|
+
config = PluginConfig.from_env()
|
|
142
|
+
errors = []
|
|
143
|
+
warnings = []
|
|
144
|
+
|
|
145
|
+
# Check JWT files
|
|
146
|
+
if not Path(config.jwt.private_key_file).exists():
|
|
147
|
+
errors.append(f"JWT private key not found: {config.jwt.private_key_file}")
|
|
148
|
+
if not Path(config.jwt.public_key_file).exists():
|
|
149
|
+
errors.append(f"JWT public key not found: {config.jwt.public_key_file}")
|
|
150
|
+
|
|
151
|
+
# Check OAuth2 configuration
|
|
152
|
+
if not config.oauth2.authorization_url:
|
|
153
|
+
errors.append("OAUTH2_AUTHORIZATION_URL not configured")
|
|
154
|
+
if not config.oauth2.token_url:
|
|
155
|
+
errors.append("OAUTH2_TOKEN_URL not configured")
|
|
156
|
+
if not config.oauth2.client_id:
|
|
157
|
+
errors.append("OAUTH2_CLIENT_ID not configured")
|
|
158
|
+
if not config.oauth2.client_secret:
|
|
159
|
+
errors.append("OAUTH2_CLIENT_SECRET not configured")
|
|
160
|
+
|
|
161
|
+
if not config.oauth2.userinfo_url:
|
|
162
|
+
warnings.append("OAUTH2_USERINFO_URL not configured (may be OK for some providers)")
|
|
163
|
+
|
|
164
|
+
# Output results
|
|
165
|
+
if warnings:
|
|
166
|
+
click.echo("=== Warnings ===")
|
|
167
|
+
for warning in warnings:
|
|
168
|
+
click.echo(f" ! {warning}")
|
|
169
|
+
|
|
170
|
+
if errors:
|
|
171
|
+
click.echo("\n=== Errors ===")
|
|
172
|
+
for error in errors:
|
|
173
|
+
click.echo(f" x {error}")
|
|
174
|
+
click.echo(f"\nConfiguration validation failed with {len(errors)} error(s)")
|
|
175
|
+
return
|
|
176
|
+
|
|
177
|
+
click.echo("\n[OK] Configuration is valid!")
|
|
178
|
+
|
|
179
|
+
|
|
180
|
+
@oauth2_cli.command("test-connection")
|
|
181
|
+
@with_appcontext
|
|
182
|
+
def test_connection():
|
|
183
|
+
"""Test connectivity to the OAuth2 provider."""
|
|
184
|
+
import httpx
|
|
185
|
+
|
|
186
|
+
config = PluginConfig.from_env()
|
|
187
|
+
|
|
188
|
+
click.echo("=== Testing OAuth2 Provider Connectivity ===\n")
|
|
189
|
+
|
|
190
|
+
# Test authorization URL
|
|
191
|
+
if config.oauth2.authorization_url:
|
|
192
|
+
try:
|
|
193
|
+
with httpx.Client() as client:
|
|
194
|
+
resp = client.head(config.oauth2.authorization_url, follow_redirects=True, timeout=10)
|
|
195
|
+
click.echo(f"[OK] Authorization URL reachable: {config.oauth2.authorization_url}")
|
|
196
|
+
except Exception as e:
|
|
197
|
+
click.echo(f"[FAIL] Authorization URL: {e}")
|
|
198
|
+
else:
|
|
199
|
+
click.echo("[SKIP] Authorization URL not configured")
|
|
200
|
+
|
|
201
|
+
# Test token URL
|
|
202
|
+
if config.oauth2.token_url:
|
|
203
|
+
try:
|
|
204
|
+
with httpx.Client() as client:
|
|
205
|
+
# Just check if the endpoint exists (will return error without credentials)
|
|
206
|
+
resp = client.post(config.oauth2.token_url, timeout=10)
|
|
207
|
+
click.echo(f"[OK] Token URL reachable: {config.oauth2.token_url}")
|
|
208
|
+
except httpx.HTTPStatusError:
|
|
209
|
+
# Expected - we're not sending valid credentials
|
|
210
|
+
click.echo(f"[OK] Token URL reachable: {config.oauth2.token_url}")
|
|
211
|
+
except Exception as e:
|
|
212
|
+
click.echo(f"[FAIL] Token URL: {e}")
|
|
213
|
+
else:
|
|
214
|
+
click.echo("[SKIP] Token URL not configured")
|
|
215
|
+
|
|
216
|
+
# Test userinfo URL
|
|
217
|
+
if config.oauth2.userinfo_url:
|
|
218
|
+
try:
|
|
219
|
+
with httpx.Client() as client:
|
|
220
|
+
resp = client.get(config.oauth2.userinfo_url, timeout=10)
|
|
221
|
+
click.echo(f"[OK] Userinfo URL reachable: {config.oauth2.userinfo_url}")
|
|
222
|
+
except httpx.HTTPStatusError:
|
|
223
|
+
# Expected - we're not sending valid token
|
|
224
|
+
click.echo(f"[OK] Userinfo URL reachable: {config.oauth2.userinfo_url}")
|
|
225
|
+
except Exception as e:
|
|
226
|
+
click.echo(f"[FAIL] Userinfo URL: {e}")
|
|
227
|
+
else:
|
|
228
|
+
click.echo("[SKIP] Userinfo URL not configured")
|
|
@@ -0,0 +1,274 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Configuration management for OAuth2 integration.
|
|
3
|
+
|
|
4
|
+
This module handles loading and validating OAuth2 configuration
|
|
5
|
+
for integration with various identity providers.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
import os
|
|
9
|
+
from dataclasses import dataclass, field
|
|
10
|
+
from typing import Optional
|
|
11
|
+
from pathlib import Path
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def claim_from_env(key, dserver_key):
|
|
15
|
+
"""Return the value of a token claim (issuer, audience).
|
|
16
|
+
|
|
17
|
+
The plugin's own setting (key) if set, else the value dserver requires
|
|
18
|
+
(dserver_key, JWT_DECODE_ISSUER / JWT_DECODE_AUDIENCE), else "dserver",
|
|
19
|
+
dserver's default. Tokens therefore match what dserver checks unless the
|
|
20
|
+
plugin is configured otherwise.
|
|
21
|
+
"""
|
|
22
|
+
return (os.environ.get(key, "").strip()
|
|
23
|
+
or os.environ.get(dserver_key, "").strip()
|
|
24
|
+
or "dserver")
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
@dataclass
|
|
28
|
+
class OAuth2ProviderConfig:
|
|
29
|
+
"""OAuth2 Identity Provider configuration."""
|
|
30
|
+
|
|
31
|
+
# Provider identification
|
|
32
|
+
name: str = "oauth2"
|
|
33
|
+
|
|
34
|
+
# OAuth2 endpoints
|
|
35
|
+
authorization_url: str = ""
|
|
36
|
+
token_url: str = ""
|
|
37
|
+
userinfo_url: str = "" # Optional, for OIDC providers
|
|
38
|
+
|
|
39
|
+
# Client credentials
|
|
40
|
+
client_id: str = ""
|
|
41
|
+
client_secret: str = ""
|
|
42
|
+
|
|
43
|
+
# OAuth2 settings
|
|
44
|
+
scope: str = "openid"
|
|
45
|
+
response_type: str = "code"
|
|
46
|
+
|
|
47
|
+
# Callback URL (constructed from base URL)
|
|
48
|
+
redirect_uri: str = ""
|
|
49
|
+
|
|
50
|
+
# User attribute mapping (provider field -> internal field)
|
|
51
|
+
# These map the OAuth2/OIDC userinfo response to internal user fields
|
|
52
|
+
attribute_map: dict = field(default_factory=lambda: {
|
|
53
|
+
"sub": "user_id",
|
|
54
|
+
"email": "email",
|
|
55
|
+
"name": "display_name",
|
|
56
|
+
"given_name": "given_name",
|
|
57
|
+
"family_name": "surname",
|
|
58
|
+
})
|
|
59
|
+
|
|
60
|
+
# Field to use as username (from attribute_map values)
|
|
61
|
+
username_field: str = "user_id"
|
|
62
|
+
|
|
63
|
+
@classmethod
|
|
64
|
+
def from_env(cls) -> "OAuth2ProviderConfig":
|
|
65
|
+
"""Create configuration from environment variables."""
|
|
66
|
+
base_url = os.environ.get("OAUTH2_BASE_URL", "http://localhost:5000")
|
|
67
|
+
|
|
68
|
+
# Parse attribute map from env if provided
|
|
69
|
+
# Format: "sub:user_id,email:email,name:display_name"
|
|
70
|
+
attribute_map_str = os.environ.get("OAUTH2_ATTRIBUTE_MAP", "")
|
|
71
|
+
if attribute_map_str:
|
|
72
|
+
attribute_map = {}
|
|
73
|
+
for mapping in attribute_map_str.split(","):
|
|
74
|
+
if ":" in mapping:
|
|
75
|
+
key, value = mapping.split(":", 1)
|
|
76
|
+
attribute_map[key.strip()] = value.strip()
|
|
77
|
+
else:
|
|
78
|
+
# Default attribute map
|
|
79
|
+
attribute_map = {
|
|
80
|
+
"sub": "user_id",
|
|
81
|
+
"email": "email",
|
|
82
|
+
"name": "display_name",
|
|
83
|
+
"given_name": "given_name",
|
|
84
|
+
"family_name": "surname",
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
return cls(
|
|
88
|
+
name=os.environ.get("OAUTH2_PROVIDER_NAME", "oauth2"),
|
|
89
|
+
authorization_url=os.environ.get("OAUTH2_AUTHORIZATION_URL", ""),
|
|
90
|
+
token_url=os.environ.get("OAUTH2_TOKEN_URL", ""),
|
|
91
|
+
userinfo_url=os.environ.get("OAUTH2_USERINFO_URL", ""),
|
|
92
|
+
client_id=os.environ.get("OAUTH2_CLIENT_ID", ""),
|
|
93
|
+
client_secret=os.environ.get("OAUTH2_CLIENT_SECRET", ""),
|
|
94
|
+
scope=os.environ.get("OAUTH2_SCOPE", "openid"),
|
|
95
|
+
response_type=os.environ.get("OAUTH2_RESPONSE_TYPE", "code"),
|
|
96
|
+
redirect_uri=os.environ.get(
|
|
97
|
+
"OAUTH2_REDIRECT_URI",
|
|
98
|
+
f"{base_url}/auth/oauth2/callback"
|
|
99
|
+
),
|
|
100
|
+
attribute_map=attribute_map,
|
|
101
|
+
username_field=os.environ.get("OAUTH2_USERNAME_FIELD", "user_id"),
|
|
102
|
+
)
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
@dataclass
|
|
106
|
+
class JwtConfig:
|
|
107
|
+
"""JWT token configuration."""
|
|
108
|
+
|
|
109
|
+
private_key_file: str = "/app/jwt/jwt_key"
|
|
110
|
+
public_key_file: str = "/app/jwt/jwt_key.pub"
|
|
111
|
+
algorithm: str = "RS256"
|
|
112
|
+
issuer: str = "dserver"
|
|
113
|
+
audience: str = "dserver"
|
|
114
|
+
token_expiry_hours: int = 24
|
|
115
|
+
# Maximum age of a session: tokens can be refreshed until this long
|
|
116
|
+
# after the original login, after which the user must log in again.
|
|
117
|
+
max_session_hours: int = 168
|
|
118
|
+
|
|
119
|
+
@classmethod
|
|
120
|
+
def from_env(cls) -> "JwtConfig":
|
|
121
|
+
"""Create configuration from environment variables."""
|
|
122
|
+
return cls(
|
|
123
|
+
private_key_file=os.environ.get(
|
|
124
|
+
"JWT_PRIVATE_KEY_FILE", "/app/jwt/jwt_key"
|
|
125
|
+
),
|
|
126
|
+
public_key_file=os.environ.get(
|
|
127
|
+
"JWT_PUBLIC_KEY_FILE", "/app/jwt/jwt_key.pub"
|
|
128
|
+
),
|
|
129
|
+
algorithm=os.environ.get("JWT_ALGORITHM", "RS256"),
|
|
130
|
+
issuer=claim_from_env("JWT_ISSUER", "JWT_DECODE_ISSUER"),
|
|
131
|
+
audience=claim_from_env("JWT_AUDIENCE", "JWT_DECODE_AUDIENCE"),
|
|
132
|
+
token_expiry_hours=int(os.environ.get("JWT_TOKEN_EXPIRY_HOURS", "24")),
|
|
133
|
+
max_session_hours=int(
|
|
134
|
+
os.environ.get("JWT_MAX_SESSION_HOURS", "168")),
|
|
135
|
+
)
|
|
136
|
+
|
|
137
|
+
|
|
138
|
+
@dataclass
|
|
139
|
+
class PluginConfig:
|
|
140
|
+
"""Overall plugin configuration."""
|
|
141
|
+
|
|
142
|
+
oauth2: OAuth2ProviderConfig = field(default_factory=OAuth2ProviderConfig.from_env)
|
|
143
|
+
jwt: JwtConfig = field(default_factory=JwtConfig.from_env)
|
|
144
|
+
|
|
145
|
+
# Base URL for constructing callback URLs
|
|
146
|
+
base_url: str = "http://localhost:5000"
|
|
147
|
+
|
|
148
|
+
# User provisioning settings
|
|
149
|
+
auto_provision_users: bool = True
|
|
150
|
+
default_user_permissions: list = field(default_factory=lambda: ["search", "retrieve"])
|
|
151
|
+
|
|
152
|
+
# Frontend redirect settings
|
|
153
|
+
frontend_url: str = "/"
|
|
154
|
+
login_success_redirect: str = "/"
|
|
155
|
+
login_error_redirect: str = "/login?error=auth_failed"
|
|
156
|
+
|
|
157
|
+
# Token delivery after login. When True, the JWT is appended to the
|
|
158
|
+
# post-login redirect as a URL fragment (#token=...), which is never
|
|
159
|
+
# sent to servers and enables webapps served from a different origin
|
|
160
|
+
# than this endpoint. When False, the token is delivered via the
|
|
161
|
+
# HttpOnly cookie only and never appears in the URL at all; this
|
|
162
|
+
# requires the webapp to share the origin of this endpoint (e.g.
|
|
163
|
+
# behind a common reverse proxy) and to obtain the token via
|
|
164
|
+
# GET /auth/token using the session cookie.
|
|
165
|
+
deliver_token_in_fragment: bool = True
|
|
166
|
+
|
|
167
|
+
# Device authorization flow (RFC 8628) for command-line clients. The
|
|
168
|
+
# user approves the request at the verification URL, by default the
|
|
169
|
+
# webapp (frontend URL if absolute, otherwise the base URL).
|
|
170
|
+
device_verification_url: str = ""
|
|
171
|
+
device_code_lifetime_seconds: int = 600
|
|
172
|
+
device_poll_interval: int = 5
|
|
173
|
+
|
|
174
|
+
@classmethod
|
|
175
|
+
def from_env(cls) -> "PluginConfig":
|
|
176
|
+
"""Create configuration from environment variables."""
|
|
177
|
+
return cls(
|
|
178
|
+
oauth2=OAuth2ProviderConfig.from_env(),
|
|
179
|
+
jwt=JwtConfig.from_env(),
|
|
180
|
+
base_url=os.environ.get("OAUTH2_BASE_URL", "http://localhost:5000"),
|
|
181
|
+
auto_provision_users=os.environ.get(
|
|
182
|
+
"OAUTH2_AUTO_PROVISION_USERS", "true"
|
|
183
|
+
).lower() == "true",
|
|
184
|
+
default_user_permissions=os.environ.get(
|
|
185
|
+
"OAUTH2_DEFAULT_USER_PERMISSIONS", "search,retrieve"
|
|
186
|
+
).split(","),
|
|
187
|
+
frontend_url=os.environ.get("OAUTH2_FRONTEND_URL", "/"),
|
|
188
|
+
login_success_redirect=os.environ.get(
|
|
189
|
+
"OAUTH2_LOGIN_SUCCESS_REDIRECT", "/"
|
|
190
|
+
),
|
|
191
|
+
login_error_redirect=os.environ.get(
|
|
192
|
+
"OAUTH2_LOGIN_ERROR_REDIRECT", "/login?error=auth_failed"
|
|
193
|
+
),
|
|
194
|
+
deliver_token_in_fragment=os.environ.get(
|
|
195
|
+
"OAUTH2_DELIVER_TOKEN_IN_FRAGMENT", "true"
|
|
196
|
+
).lower() == "true",
|
|
197
|
+
device_verification_url=os.environ.get(
|
|
198
|
+
"OAUTH2_DEVICE_VERIFICATION_URL", ""),
|
|
199
|
+
device_code_lifetime_seconds=int(os.environ.get(
|
|
200
|
+
"OAUTH2_DEVICE_CODE_LIFETIME_SECONDS", "600")),
|
|
201
|
+
device_poll_interval=int(os.environ.get(
|
|
202
|
+
"OAUTH2_DEVICE_POLL_INTERVAL", "5")),
|
|
203
|
+
)
|
|
204
|
+
|
|
205
|
+
def get_device_verification_url(self) -> str:
|
|
206
|
+
"""Return the absolute URL at which users approve device logins."""
|
|
207
|
+
if self.device_verification_url:
|
|
208
|
+
return self.device_verification_url
|
|
209
|
+
if self.frontend_url.startswith(("http://", "https://")):
|
|
210
|
+
return self.frontend_url
|
|
211
|
+
return self.base_url.rstrip("/") + "/" + self.frontend_url.lstrip("/")
|
|
212
|
+
|
|
213
|
+
|
|
214
|
+
# Pre-configured provider templates
|
|
215
|
+
PROVIDER_PRESETS = {
|
|
216
|
+
"orcid": {
|
|
217
|
+
"name": "orcid",
|
|
218
|
+
"authorization_url": "https://orcid.org/oauth/authorize",
|
|
219
|
+
"token_url": "https://orcid.org/oauth/token",
|
|
220
|
+
"userinfo_url": "", # ORCID returns user info in token response
|
|
221
|
+
"scope": "/authenticate",
|
|
222
|
+
"attribute_map": {
|
|
223
|
+
"orcid": "user_id",
|
|
224
|
+
"name": "display_name",
|
|
225
|
+
},
|
|
226
|
+
"username_field": "user_id",
|
|
227
|
+
},
|
|
228
|
+
"orcid_sandbox": {
|
|
229
|
+
"name": "orcid_sandbox",
|
|
230
|
+
"authorization_url": "https://sandbox.orcid.org/oauth/authorize",
|
|
231
|
+
"token_url": "https://sandbox.orcid.org/oauth/token",
|
|
232
|
+
"userinfo_url": "",
|
|
233
|
+
"scope": "/authenticate",
|
|
234
|
+
"attribute_map": {
|
|
235
|
+
"orcid": "user_id",
|
|
236
|
+
"name": "display_name",
|
|
237
|
+
},
|
|
238
|
+
"username_field": "user_id",
|
|
239
|
+
},
|
|
240
|
+
"github": {
|
|
241
|
+
"name": "github",
|
|
242
|
+
"authorization_url": "https://github.com/login/oauth/authorize",
|
|
243
|
+
"token_url": "https://github.com/login/oauth/access_token",
|
|
244
|
+
"userinfo_url": "https://api.github.com/user",
|
|
245
|
+
"scope": "read:user user:email",
|
|
246
|
+
"attribute_map": {
|
|
247
|
+
"id": "user_id",
|
|
248
|
+
"login": "username",
|
|
249
|
+
"email": "email",
|
|
250
|
+
"name": "display_name",
|
|
251
|
+
},
|
|
252
|
+
"username_field": "username",
|
|
253
|
+
},
|
|
254
|
+
"google": {
|
|
255
|
+
"name": "google",
|
|
256
|
+
"authorization_url": "https://accounts.google.com/o/oauth2/v2/auth",
|
|
257
|
+
"token_url": "https://oauth2.googleapis.com/token",
|
|
258
|
+
"userinfo_url": "https://openidconnect.googleapis.com/v1/userinfo",
|
|
259
|
+
"scope": "openid email profile",
|
|
260
|
+
"attribute_map": {
|
|
261
|
+
"sub": "user_id",
|
|
262
|
+
"email": "email",
|
|
263
|
+
"name": "display_name",
|
|
264
|
+
"given_name": "given_name",
|
|
265
|
+
"family_name": "surname",
|
|
266
|
+
},
|
|
267
|
+
"username_field": "email",
|
|
268
|
+
},
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
|
|
272
|
+
def get_provider_preset(name: str) -> dict:
|
|
273
|
+
"""Get a provider preset configuration by name."""
|
|
274
|
+
return PROVIDER_PRESETS.get(name.lower(), {})
|