Skip to content

Commit

Permalink
Merge pull request #238 from EsupPortail/dev
Browse files Browse the repository at this point in the history
Dev - V2.6
  • Loading branch information
ptitloup authored May 4, 2020
2 parents b16db9d + 45ba303 commit cd4fd60
Show file tree
Hide file tree
Showing 152 changed files with 4,800 additions and 2,899 deletions.
2 changes: 1 addition & 1 deletion .gitignore
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
# Compiled source #
# Compiled source #
###################
*.com
*.class
Expand Down
1 change: 1 addition & 0 deletions pod/authentication/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
default_app_config = 'pod.authentication.apps.AuthConfig'
96 changes: 91 additions & 5 deletions pod/authentication/admin.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,14 @@
from django.contrib.auth.admin import UserAdmin as BaseUserAdmin
from django.contrib.auth.models import User
from django.utils.translation import ugettext_lazy as _
from pod.authentication.models import Owner
from pod.authentication.forms import OwnerAdminForm
from pod.authentication.models import Owner, GroupSite
from pod.authentication.forms import OwnerAdminForm, GroupSiteAdminForm
from django.utils.html import format_html

from django.contrib.sites.shortcuts import get_current_site
from django.contrib.auth.models import Group
from pod.authentication.forms import GroupAdminForm
from django.contrib.sites.models import Site
from django.contrib.admin import widgets

# Define an inline admin descriptor for Owner model
# which acts a bit like a singleton
Expand All @@ -19,6 +21,34 @@
False)


class GroupSiteInline(admin.StackedInline):
model = GroupSite
form = GroupSiteAdminForm
can_delete = False
verbose_name_plural = 'groupssite'

def get_fields(self, request, obj=None):
if not request.user.is_superuser:
exclude = ()
exclude += ('sites',)
self.exclude = exclude
return list(super(GroupSiteInline, self).get_fields(request, obj))

class Media:
css = {
"all": (
'bootstrap-4/css/bootstrap.min.css',
'bootstrap-4/css/bootstrap-grid.css',
'css/pod.css'
)
}
js = (
'podfile/js/filewidget.js',
'js/main.js',
'feather-icons/feather.min.js',
'bootstrap-4/js/bootstrap.min.js')


class OwnerInline(admin.StackedInline):
model = Owner
form = OwnerAdminForm
Expand All @@ -35,6 +65,8 @@ def get_fields(self, request, obj=None):
exclude_set.add('auth_type')
exclude_set.add('affiliation')
exclude_set.add('commentaire')
if not request.user.is_superuser:
exclude_set.add('sites')
return [f for f in fields if f not in exclude_set]

class Media:
Expand All @@ -57,7 +89,6 @@ class UserAdmin(BaseUserAdmin):
def clickable_email(self, obj):
email = obj.email
return format_html('<a href="mailto:{}">{}</a>', email, email)

clickable_email.allow_tags = True
clickable_email.short_description = _('Email')
list_display = (
Expand All @@ -72,18 +103,53 @@ def clickable_email(self, obj):
'is_superuser',
'owner_hashkey'
)

list_filter = (
'is_staff',
'is_superuser',
'is_active',
('groups', admin.RelatedOnlyFieldListFilter)
)
if USE_ESTABLISHMENT_FIELD:
list_display = list_display + ('owner_establishment',)

def owner_hashkey(self, obj):
return "%s" % Owner.objects.get(user=obj).hashkey

def formfield_for_manytomany(self, db_field, request, **kwargs):
if (db_field.name) == "groups":
kwargs["queryset"] = Group.objects.filter(
groupsite__sites=Site.objects.get_current())
kwargs['widget'] = widgets.FilteredSelectMultiple(
db_field.verbose_name,
False)
return super().formfield_for_foreignkey(db_field, request, **kwargs)

def owner_establishment(self, obj):
return "%s" % Owner.objects.get(user=obj).establishment
owner_establishment.short_description = _('Establishment')

ordering = ('-is_superuser', 'username', )
inlines = (OwnerInline, )

def get_queryset(self, request):
qs = super().get_queryset(request)
if not request.user.is_superuser:
qs = qs.filter(owner__sites=get_current_site(
request))
return qs

def save_model(self, request, obj, form, change):
super().save_model(request, obj, form, change)
if not change:
obj.owner.sites.add(get_current_site(request))
obj.owner.save()

def get_inline_instances(self, request, obj=None):
_inlines = super().get_inline_instances(request, obj=None)
if obj is not None:
custom_inline = OwnerInline(self.model, self.admin_site)
_inlines.append(custom_inline)
return _inlines


# Create a new Group admin.
Expand All @@ -93,6 +159,26 @@ class GroupAdmin(admin.ModelAdmin):
# Filter permissions horizontal as well.
filter_horizontal = ['permissions']

def get_queryset(self, request):
qs = super().get_queryset(request)
if not request.user.is_superuser:
qs = qs.filter(groupsite__sites=get_current_site(
request))
return qs

def save_model(self, request, obj, form, change):
super().save_model(request, obj, form, change)
if not change:
obj.groupsite.sites.add(get_current_site(request))
obj.save()

def get_inline_instances(self, request, obj=None):
_inlines = super().get_inline_instances(request, obj=None)
if obj is not None:
custom_inline = GroupSiteInline(self.model, self.admin_site)
_inlines.append(custom_inline)
return _inlines


# Re-register UserAdmin
admin.site.unregister(User)
Expand Down
20 changes: 19 additions & 1 deletion pod/authentication/apps.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,23 @@
from django.apps import AppConfig
from django.db.models.signals import post_migrate


def set_default_site(sender, **kwargs):
from pod.authentication.models import GroupSite
from pod.authentication.models import Owner
from django.contrib.sites.models import Site
for gs in GroupSite.objects.all():
if len(gs.sites.all()) == 0:
gs.sites.add(Site.objects.get_current())
gs.save()
for owner in Owner.objects.all():
if len(owner.sites.all()) == 0:
owner.sites.add(Site.objects.get_current())
owner.save()


class AuthConfig(AppConfig):
name = 'auth'
name = 'pod.authentication'

def ready(self):
post_migrate.connect(set_default_site, sender=self)
13 changes: 13 additions & 0 deletions pod/authentication/backends.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
from shibboleth.backends import ShibbolethRemoteUserBackend
from django.contrib.sites.shortcuts import get_current_site


class ShibbBackend(ShibbolethRemoteUserBackend):
@staticmethod
def update_user_params(user, params):
super(ShibbBackend,
ShibbBackend).update_user_params(user, params)
user.owner.auth_type = "Shibboleth"
if get_current_site(None) not in user.owner.sites.all():
user.owner.sites.add(get_current_site(None))
user.owner.save()
16 changes: 14 additions & 2 deletions pod/authentication/forms.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
from django import forms
from pod.authentication.models import Owner
from pod.authentication.models import Owner, GroupSite
from django.conf import settings

from django.contrib.auth import get_user_model
from django.contrib.admin.widgets import FilteredSelectMultiple
from django.contrib.auth.models import Group
from django.utils.translation import ugettext_lazy as _
from django.contrib.sites.models import Site

FILEPICKER = False
if getattr(settings, 'USE_PODFILE', False):
Expand All @@ -26,6 +26,16 @@ class Meta(object):
fields = '__all__'


class GroupSiteAdminForm(forms.ModelForm):

def __init__(self, *args, **kwargs):
super(GroupSiteAdminForm, self).__init__(*args, **kwargs)

class Meta(object):
model = GroupSite
fields = '__all__'


class FrontOwnerForm(OwnerAdminForm):

class Meta(object):
Expand Down Expand Up @@ -58,6 +68,8 @@ def __init__(self, *args, **kwargs):
if self.instance.pk:
# Populate the users field with the current Group users.
self.fields['users'].initial = self.instance.user_set.all()
self.fields['users'].queryset = self.fields['users'].queryset.filter(
owner__sites=Site.objects.get_current())

def save_m2m(self):
# Add the users to the Group.
Expand Down
37 changes: 35 additions & 2 deletions pod/authentication/models.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
from django.db import models
from django.utils.translation import ugettext_lazy as _
from django.contrib.auth.models import User, Permission
from django.contrib.auth.models import User, Permission, Group
from django.conf import settings
from django.dispatch import receiver
from django.db.models.signals import post_save
from django.contrib.sites.models import Site

import hashlib
import logging
Expand Down Expand Up @@ -73,6 +74,7 @@ class Owner(models.Model):
establishment = models.CharField(
_('Establishment'), max_length=10, blank=True, choices=ESTABLISHMENTS,
default=ESTABLISHMENTS[0][0])
sites = models.ManyToManyField(Site)

def __str__(self):
if HIDE_USERNAME:
Expand All @@ -86,7 +88,9 @@ def save(self, *args, **kwargs):
super(Owner, self).save(*args, **kwargs)

def is_manager(self):
group_ids = self.user.groups.all().values_list('id', flat=True)
group_ids = self.user.groups.all().filter(
groupsite__sites=Site.objects.get_current()).values_list(
'id', flat=True)
return (
self.user.is_staff
and Permission.objects.filter(group__id__in=group_ids).count() > 0)
Expand All @@ -96,6 +100,12 @@ def email(self):
return self.user.email


@receiver(post_save, sender=Owner)
def default_site_owner(sender, instance, created, **kwargs):
if len(instance.sites.all()) == 0:
instance.sites.add(Site.objects.get_current())


@receiver(post_save, sender=User)
def create_owner_profile(sender, instance, created, **kwargs):
if created:
Expand All @@ -106,3 +116,26 @@ def create_owner_profile(sender, instance, created, **kwargs):
msg += '\n%s' % traceback.format_exc()
logger.error(msg)
print(msg)


class GroupSite(models.Model):
group = models.OneToOneField(Group, on_delete=models.CASCADE)
sites = models.ManyToManyField(Site)


@receiver(post_save, sender=GroupSite)
def default_site_groupsite(sender, instance, created, **kwargs):
if len(instance.sites.all()) == 0:
instance.sites.add(Site.objects.get_current())


@receiver(post_save, sender=Group)
def create_groupsite_profile(sender, instance, created, **kwargs):
if created:
try:
GroupSite.objects.create(group=instance)
except Exception as e:
msg = u'\n Create groupsite profile ***** Error:%r' % e
msg += '\n%s' % traceback.format_exc()
logger.error(msg)
print(msg)
3 changes: 2 additions & 1 deletion pod/authentication/populatedCASbackend.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
from django.contrib.auth.models import Group
from pod.authentication.models import Owner
from pod.authentication.models import AFFILIATION

from django.contrib.sites.models import Site
from ldap3 import Server
from ldap3 import ALL
from ldap3 import Connection
Expand Down Expand Up @@ -171,6 +171,7 @@ def populate_user_from_entry(user, owner, entry):
if CREATE_GROUP_FROM_AFFILIATION:
group, group_created = Group.objects.get_or_create(
name=affiliation)
group.groupsite.sites.add(Site.objects.get_current())
user.groups.add(group)
user.save()

Expand Down
9 changes: 9 additions & 0 deletions pod/authentication/shibmiddleware.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
from shibboleth.middleware import ShibbolethRemoteUserMiddleware
from django.conf import settings

REMOTE_USER_HEADER = getattr(
settings, 'REMOTE_USER_HEADER', "REMOTE_USER")


class ShibbMiddleware(ShibbolethRemoteUserMiddleware):
header = REMOTE_USER_HEADER
7 changes: 5 additions & 2 deletions pod/authentication/templates/authentication/login.html
Original file line number Diff line number Diff line change
Expand Up @@ -12,9 +12,12 @@ <h2>{% trans 'Authentication' %}</h2>

<div class="text-center">
{% if USE_CAS %}
<a class="btn btn-success" href="{% url 'cas-login' %}?next={{ referrer|urlencode }}" title="{% trans "Single sign on" %} {{TITLE_ETB}}">{% trans "Single sign on" %} {{TITLE_ETB}}</a>
<p><a class="btn btn-primary" href="{% url 'cas-login' %}?next={{ referrer|urlencode }}" title="{% trans "Single sign on" %} {{TITLE_ETB}}">{% trans "Single sign on" %} {{TITLE_ETB}}</a></p>
{% endif %}
<a class="btn btn-primary" href="{% url 'local-login'%}?{% if request.GET.is_iframe %}is_iframe=true&{%endif%}next={{ referrer|urlencode }}" title="">{% trans "local sign on" %}</a>
{% if USE_SHIB %}
<p><a class="btn btn-primary" href="{{SHIB_URL }}?target={{ referrer|urlencode }}" title="{{ SHIB_NAME }}">{{ SHIB_NAME}}</a></p>
{% endif %}
<p><a class="btn btn-primary" href="{% url 'local-login'%}?{% if request.GET.is_iframe %}is_iframe=true&{%endif%}next={{ referrer|urlencode }}" title="">{% trans "local sign on" %}</a></p>
</div>

{% endblock %}
2 changes: 1 addition & 1 deletion pod/authentication/templates/userpicture/userpicture.html
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
<div class="modal-content">
<form method="post" action="{% url 'userpicture' %}" id="userpicture_form">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">{% trans "Change your picture" %}</h5>
<h2 class="modal-title" id="exampleModalLabel">{% trans "Change your picture" %}</h2>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">&times;</span>
</button>
Expand Down
Loading

0 comments on commit cd4fd60

Please sign in to comment.