add ocid based login

This commit is contained in:
j 2024-11-08 12:29:15 +00:00
parent d83309d4cd
commit 34af2b1fab
12 changed files with 131 additions and 28 deletions

34
pandora/app/oidc.py Normal file
View file

@ -0,0 +1,34 @@
import unicodedata
from django.contrib.auth import get_user_model
import mozilla_django_oidc.auth
from user.utils import prepare_user
User = get_user_model()
class OIDCAuthenticationBackend(mozilla_django_oidc.auth.OIDCAuthenticationBackend):
def create_user(self, claims):
user = super(OIDCAuthenticationBackend, self).create_user(claims)
username = claims.get("preferred_username")
n = 1
if username and username != user.username:
uname = username
while User.objects.filter(username=uname).exclude(id=user.id).exists():
n += 1
uname = '%s (%s)' % (username, n)
user.username = uname
user.save()
prepare_user(user)
return user
def update_user(self, user, claims):
print("update user", user, claims)
#user.save()
return user
def generate_username(email):
return unicodedata.normalize('NFKC', email)[:150]

View file

@ -184,6 +184,7 @@ def init(request, data):
except:
pass
config['site']['oidc'] = bool(getattr(settings, 'OIDC_RP_CLIENT_ID', False))
response['data']['site'] = config
response['data']['user'] = init_user(request.user, request)
request.session['last_init'] = str(datetime.now())

View file

@ -111,6 +111,7 @@ ROOT_URLCONF = 'urls'
INSTALLED_APPS = (
'django.contrib.auth',
'mozilla_django_oidc',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
@ -158,6 +159,27 @@ INSTALLED_APPS = (
)
AUTH_USER_MODEL = 'system.User'
AUTH_PROFILE_MODULE = 'user.UserProfile'
AUTH_CHECK_USERNAME = True
AUTHENTICATION_BACKENDS = (
'django.contrib.auth.backends.ModelBackend',
)
# OpenID Connect login support
LOGIN_REDIRECT_URL = "/grid"
LOGOUT_REDIRECT_URL = "/grid"
OIDC_USERNAME_ALGO = "app.oidc.generate_username"
OIDC_RP_CLIENT_ID = None
# define those in local_settings to enable OCID based login
#OIDC_RP_CLIENT_ID = '<client id>'
#OIDC_RP_CLIENT_SECRET = '<client secret>'
#OIDC_RP_SIGN_ALGO = "RS256"
#OIDC_OP_JWKS_ENDPOINT = "<jwks endpoint>"
#OIDC_OP_AUTHORIZATION_ENDPOINT = "<authorization endpoint>"
#OIDC_OP_TOKEN_ENDPOINT = "<token endpoint>"
#OIDC_OP_USER_ENDPOINT = "<user endpoint>"
# Log errors into db
LOGGING = {
@ -193,8 +215,6 @@ CACHES = {
DEFAULT_AUTO_FIELD = "django.db.models.BigAutoField"
AUTH_PROFILE_MODULE = 'user.UserProfile'
AUTH_CHECK_USERNAME = True
FFMPEG = 'ffmpeg'
FFPROBE = 'ffprobe'
USE_VP9 = True
@ -323,3 +343,7 @@ except NameError:
INSTALLED_APPS = tuple(list(INSTALLED_APPS) + LOCAL_APPS)
if OIDC_RP_CLIENT_ID:
AUTHENTICATION_BACKENDS = list(AUTHENTICATION_BACKENDS) + [
'app.oidc.OIDCAuthenticationBackend'
]

View file

@ -2,7 +2,7 @@
import os
import importlib
from django.urls import path, re_path
from django.urls import path, re_path, include
from oxdjango.http import HttpFileResponse
from django.conf import settings
@ -36,6 +36,8 @@ def serve_static_file(path, location, content_type):
urlpatterns = [
#path('admin/', admin.site.urls),
path('oidc/', include('mozilla_django_oidc.urls')),
re_path(r'^api/locale.(?P<lang>.*).json$', translation.views.locale_json),
re_path(r'^api/upload/text/?$', text.views.upload),
re_path(r'^api/upload/document/?$', document.views.upload),

View file

@ -20,3 +20,4 @@ future
pytz
pypdfium2
Pillow>=10
mozilla-django-oidc==4.0.1

View file

@ -337,7 +337,11 @@ pandora.ui.accountSignoutDialog = function() {
that.close();
pandora.UI.set({page: ''});
pandora.api.signout({}, function(result) {
if (pandora.site.site.oidc) {
pandora.oidcLogout();
} else {
pandora.signout(result.data);
}
});
}
})

View file

@ -100,6 +100,10 @@ pandora.ui.appPanel = function() {
pandora.$ui.siteDialog = pandora.ui.siteDialog(page).open();
}
} else if (['signup', 'signin'].indexOf(page) > -1) {
if (pandora.site.site.oidc) {
pandora.oidcLogin()
return
}
if (pandora.user.level == 'guest') {
if (pandora.$ui.accountDialog && pandora.$ui.accountDialog.is(':visible')) {
pandora.$ui.accountDialog.options(pandora.ui.accountDialogOptions(page));

View file

@ -424,18 +424,26 @@ pandora.ui.folders = function(section) {
}).bindEvent({
click: function() {
var $dialog = pandora.ui.iconDialog({
buttons: title != Ox._('Featured ' + folderItems) ? [
buttons: title != Ox._('Featured ' + folderItems) ? [].concat(
pandora.site.site.oidc ? []
: [
Ox.Button({title: Ox._('Sign Up...')}).bindEvent({
click: function() {
$dialog.close();
pandora.$ui.accountDialog = pandora.ui.accountDialog('signup').open();
}
}),
})
],
[
Ox.Button({title: Ox._('Sign In...')}).bindEvent({
click: function() {
$dialog.close();
if (pandora.site.site.oidc) {
pandora.oidcLogin()
} else {
pandora.$ui.accountDialog = pandora.ui.accountDialog('signin').open();
}
}
}),
{},
Ox.Button({title: Ox._('Not Now')}).bindEvent({
@ -443,7 +451,8 @@ pandora.ui.folders = function(section) {
$dialog.close();
}
})
] : [
]
): [
Ox.Button({title: Ox._('Close')}).bindEvent({
click: function() {
$dialog.close();

View file

@ -171,13 +171,13 @@ pandora.ui.home = function() {
}),
$signinButton = Ox.Button({
title: Ox._('Sign In'),
width: 74
width: pandora.site.site.oidc ? 156 : 74
})
.css({
position: 'absolute',
left: 0,
top: '112px',
right: '82px',
right: pandora.site.site.oidc ? '164px' : '82px',
bottom: 0,
margin: 'auto',
opacity: 0
@ -248,7 +248,13 @@ pandora.ui.home = function() {
adjustRatio();
if (pandora.user.level == 'guest') {
if (pandora.site.site.oidc) {
$signinButton.options({
width: 156
})
} else {
$signupButton.appendTo(that);
}
$signinButton.appendTo(that);
} else {
$preferencesButton.appendTo(that);

View file

@ -46,7 +46,9 @@ pandora.ui.mainMenu = function() {
{ id: 'tasks', title: Ox._('Tasks...'), disabled: isGuest },
{ id: 'archives', title: Ox._('Archives...'), disabled: /*isGuest*/ true },
{},
{ id: 'signup', title: Ox._('Sign Up...'), disabled: !isGuest },
!pandora.site.site.oidc
? { id: 'signup', title: Ox._('Sign Up...'), disabled: !isGuest }
: [],
isGuest ? { id: 'signin', title: Ox._('Sign In...')}
: { id: 'signout', title: Ox._('Sign Out...')}
] },

View file

@ -2650,6 +2650,20 @@ pandora.logEvent = function(data, event, element) {
}
};
pandora.oidcLogin = function() {
Ox.LoadingScreen().css({zIndex: 100}).addClass('OxScreen').appendTo(document.body).show().start()
document.location.href = '/oidc/authenticate/';
};
pandora.oidcLogout = function() {
Ox.LoadingScreen().css({zIndex: 100}).addClass('OxScreen').appendTo(document.body).show().start()
const form = document.createElement("form");
form.setAttribute("method", "post");
form.setAttribute("action", "/oidc/logout/");
document.body.appendChild(form);
form.submit();
};
pandora.openLicenseDialog = function() {
if (!Ox.Focus.focusedElementIsInput() && !pandora.hasDialogOrScreen()) {
pandora.ui.licenseDialog().open().bindEvent({

View file

@ -302,6 +302,8 @@ if __name__ == "__main__":
if old <= 6581:
run('./bin/pip', 'install', '-U', 'pip')
run('./bin/pip', 'install', '-r', 'requirements.txt')
if old <= 6659:
run('./bin/pip', 'install', '-r', 'requirements.txt')
else:
if len(sys.argv) == 1:
branch = get_branch()