77 lines
2.7 KiB
Python
Executable File
77 lines
2.7 KiB
Python
Executable File
"""
|
|
MIT License
|
|
|
|
Copyright (c) 2025 Hopsenn
|
|
|
|
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
of this software and associated documentation files (the "Software"), to deal
|
|
in the Software without restriction, including without limitation the rights
|
|
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
copies of the Software, and to permit persons to whom the Software is
|
|
furnished to do so, subject to the following conditions:
|
|
|
|
The above copyright notice and this permission notice shall be included in all
|
|
copies or substantial portions of the Software.
|
|
|
|
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
SOFTWARE.
|
|
"""
|
|
|
|
from functools import wraps
|
|
from django.contrib.auth import login as auth_login
|
|
|
|
from . import settings
|
|
from .validators import verify_id_token
|
|
from .utils import get_jwt_tokens, get_user_from_token
|
|
|
|
|
|
def hopid_callback(response=None):
|
|
def decorator(view_func):
|
|
@wraps(view_func)
|
|
def _wrapped_view(request, *args, **kwargs):
|
|
def fail(reason):
|
|
if callable(response):
|
|
return response(request, reason)
|
|
|
|
return view_func(request, *args, **kwargs, error=reason)
|
|
|
|
code = request.GET.get('code')
|
|
if not code:
|
|
return fail("No code returned")
|
|
|
|
tokens = get_jwt_tokens(code, request.session.pop('pkce_verifier', ''))
|
|
error = tokens.get('error', '')
|
|
|
|
if error:
|
|
return fail(error)
|
|
|
|
access_token = tokens.get('access_token')
|
|
id_token = tokens.get('id_token')
|
|
|
|
if not access_token or not id_token:
|
|
return fail("No ID token returned")
|
|
|
|
claims = verify_id_token(id_token, access_token)
|
|
if not claims:
|
|
return fail("Invalid ID token")
|
|
|
|
expected_nonce = request.session.pop('oidc_nonce', None)
|
|
|
|
if not claims or claims.get("nonce") != expected_nonce:
|
|
return fail("Invalid or missing nonce")
|
|
|
|
profile = get_user_from_token(access_token)
|
|
if not profile:
|
|
return fail("User info request failed")
|
|
|
|
auth_login(request, profile)
|
|
return view_func(request, *args, **kwargs)
|
|
|
|
return _wrapped_view
|
|
return decorator
|