From 222c4e26d666fcf78ad5ca0d0cdf636bb76f4057 Mon Sep 17 00:00:00 2001 From: lian Date: Wed, 27 Oct 2021 12:28:35 +0800 Subject: [PATCH] add jwt sso --- seahub/urls.py | 1 + seahub/views/sso.py | 42 ++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 43 insertions(+) diff --git a/seahub/urls.py b/seahub/urls.py index ac687a49a1..98bc509925 100644 --- a/seahub/urls.py +++ b/seahub/urls.py @@ -193,6 +193,7 @@ urlpatterns = [ url(r'^accounts/', include('seahub.base.registration_urls')), url(r'^sso/$', sso, name='sso'), + url(r'^jwt-sso/$', jwt_sso, name='jwt_sso'), url(r'^shib-login/', shib_login, name="shib_login"), url(r'^oauth/', include('seahub.oauth.urls')), url(r'^thirdparty-editor/', include('seahub.thirdparty_editor.urls')), diff --git a/seahub/views/sso.py b/seahub/views/sso.py index e7215c1562..e1bda05ffe 100644 --- a/seahub/views/sso.py +++ b/seahub/views/sso.py @@ -1,10 +1,18 @@ # Copyright (c) 2012-2016 Seafile Ltd. +import jwt +import time + from django.conf import settings from django.urls import reverse from django.http import HttpResponseRedirect from django.utils.http import is_safe_url, urlquote +from django.utils.translation import ugettext as _ + +from seahub.base.templatetags.seahub_tags import email2nickname from seahub.auth import REDIRECT_FIELD_NAME +from seahub.utils import render_error + def sso(request): # Ensure the user-originating redirection url is safe. @@ -43,6 +51,40 @@ def sso(request): return HttpResponseRedirect(next_page) + +def jwt_sso(request): + + ENABLE_JWT_SSO = getattr(settings, 'ENABLE_JWT_SSO', False) + JWT_SSO_SECRET_KEY = getattr(settings, 'JWT_SSO_SECRET_KEY', '') + JWT_SSO_EXPIRATION = getattr(settings, 'JWT_SSO_EXPIRATION', 60 * 60) + JWT_SSO_ALGORITHM = getattr(settings, 'JWT_SSO_ALGORITHM', 'HS256') + + if not ENABLE_JWT_SSO: + error_msg = _("jwt sso feature is not enabled.") + return render_error(request, error_msg) + + if not JWT_SSO_SECRET_KEY: + error_msg = _("jwt sso secret key is not set.") + return render_error(request, error_msg) + + page_url = request.GET.get('page', '') + if not page_url: + error_msg = _("page parameter is not passed.") + return render_error(request, error_msg) + + username = request.user.username + + data = { + 'exp': time.time() + JWT_SSO_EXPIRATION, + 'email': username, + 'name': email2nickname(username) + } + + jwt_token = jwt.encode(data, JWT_SSO_SECRET_KEY, JWT_SSO_ALGORITHM) + redirect_to = "{}?jwt-token={}".format(page_url, jwt_token) + return HttpResponseRedirect(redirect_to) + + def shib_login(request): # client platform args used to create api v2 token next_page = request.GET.get(REDIRECT_FIELD_NAME, '')