Settingize some stuff and add custom AnonymousUser

This commit is contained in:
Skia 2015-12-14 15:43:30 +01:00
parent a6edfcc048
commit 787fd2f484
4 changed files with 87 additions and 10 deletions

View File

@ -1,6 +1,7 @@
import os import os
from django.core.management.base import BaseCommand, CommandError from django.core.management.base import BaseCommand, CommandError
from django.core.management import call_command from django.core.management import call_command
from django.conf import settings
from core.models import Group, User from core.models import Group, User
class Command(BaseCommand): class Command(BaseCommand):
@ -21,11 +22,8 @@ class Command(BaseCommand):
is_superuser=True, is_staff=True) is_superuser=True, is_staff=True)
u.set_password("plop") u.set_password("plop")
u.save() u.save()
Group(name="root").save() for g in settings.AE_GROUPS.values():
# Just some example groups, only root is truly mandatory Group(id=g['id'], name=g['name']).save()
Group(name="bureau_restreint_ae").save()
Group(name="bureau_ae").save()
Group(name="membre_ae").save()
if not options['prod']: if not options['prod']:
print("Dev mode, adding some test data") print("Dev mode, adding some test data")
u = User(username='skia', last_name="Kia", first_name="S'", u = User(username='skia', last_name="Kia", first_name="S'",
@ -34,4 +32,10 @@ class Command(BaseCommand):
is_superuser=True, is_staff=True) is_superuser=True, is_staff=True)
u.set_password("plop") u.set_password("plop")
u.save() u.save()
u = User(username='guy', last_name="Carlier", first_name="Guy",
email="guy@git.an",
date_of_birth="1942-06-12T00:00:00+01:00",
is_superuser=False, is_staff=False)
u.set_password("plop")
u.save()

31
core/middleware.py Normal file
View File

@ -0,0 +1,31 @@
import importlib
from django.conf import settings
from django.utils.functional import SimpleLazyObject
from django.contrib.auth import get_user
from django.contrib.auth.middleware import AuthenticationMiddleware as DjangoAuthenticationMiddleware
module, klass = settings.AUTH_ANONYMOUS_MODEL.rsplit('.', 1)
AnonymousUser = getattr(importlib.import_module(module), klass)
def get_cached_user(request):
if not hasattr(request, '_cached_user'):
user = get_user(request)
if user.is_anonymous():
user = AnonymousUser(request)
request._cached_user = user
return request._cached_user
class AuthenticationMiddleware(DjangoAuthenticationMiddleware):
def process_request(self, request):
assert hasattr(request, 'session'), (
"The Django authentication middleware requires session middleware "
"to be installed. Edit your MIDDLEWARE_CLASSES setting to insert "
"'django.contrib.sessions.middleware.SessionMiddleware' before "
"'account.middleware.AuthenticationMiddleware'."
)
request.user = SimpleLazyObject(lambda: get_cached_user(request))

View File

@ -1,10 +1,11 @@
from django.db import models from django.db import models
from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin, UserManager, Group as AuthGroup from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin, UserManager, Group as AuthGroup, AnonymousUser as AuthAnonymousUser
from django.utils.translation import ugettext_lazy as _ from django.utils.translation import ugettext_lazy as _
from django.utils import timezone from django.utils import timezone
from django.core import validators from django.core import validators
from django.core.exceptions import ValidationError from django.core.exceptions import ValidationError
from django.core.urlresolvers import reverse from django.core.urlresolvers import reverse
from django.conf import settings
from datetime import datetime, timedelta from datetime import datetime, timedelta
class Group(AuthGroup): class Group(AuthGroup):
@ -60,14 +61,15 @@ class User(AbstractBaseUser, PermissionsMixin):
), ),
) )
date_joined = models.DateTimeField(_('date joined'), default=timezone.now) date_joined = models.DateTimeField(_('date joined'), default=timezone.now)
owner_group = models.ForeignKey(Group, related_name="owned_user", default=1) owner_group = models.ForeignKey(Group, related_name="owned_user",
default=settings.AE_GROUPS['root']['id'])
edit_group = models.ManyToManyField(Group, related_name="editable_user", blank=True) edit_group = models.ManyToManyField(Group, related_name="editable_user", blank=True)
view_group = models.ManyToManyField(Group, related_name="viewable_user", blank=True) view_group = models.ManyToManyField(Group, related_name="viewable_user", blank=True)
objects = UserManager() objects = UserManager()
USERNAME_FIELD = 'username' USERNAME_FIELD = 'username'
REQUIRED_FIELDS = ['email', 'first_name', 'last_name', 'date_of_birth'] REQUIRED_FIELDS = ['email', 'date_of_birth']
class Meta: class Meta:
verbose_name = _('user') verbose_name = _('user')
@ -149,7 +151,8 @@ class User(AbstractBaseUser, PermissionsMixin):
if not hasattr(obj, "owner_group"): if not hasattr(obj, "owner_group"):
return False return False
if (self.is_superuser or self.groups.filter(name=obj.owner_group.name).exists() or if (self.is_superuser or self.groups.filter(name=obj.owner_group.name).exists() or
self.has_perm(obj.__class__.__module__.split('.')[0]+".change_prop_"+obj.__class__.__name__.lower())): self.has_perm(obj.__class__.__module__.split('.')[0]+".change_prop_"+obj.__class__.__name__.lower()) or
self.groups.filter(id=settings.AE_GROUPS['root']['id']).exists()):
return True return True
return False return False
@ -185,6 +188,21 @@ class User(AbstractBaseUser, PermissionsMixin):
return True return True
return False return False
class AnonymousUser(AuthAnonymousUser):
def __init__(self, request):
super(AnonymousUser, self).__init__()
def is_owner(self, obj):
return False
def can_edit(self, obj):
return False
def can_view(self, obj):
if obj.view_group.filter(pk=settings.AE_GROUPS['public']['id']).exists():
return True
return False
class LockError(Exception): class LockError(Exception):
"""There was a lock error on the object""" """There was a lock error on the object"""
pass pass
@ -213,7 +231,8 @@ class Page(models.Model):
# Attention: this field may not be valid until you call save(). It's made for fast query, but don't rely on it when # Attention: this field may not be valid until you call save(). It's made for fast query, but don't rely on it when
# playing with a Page object, use get_full_name() instead! # playing with a Page object, use get_full_name() instead!
full_name = models.CharField(_('page name'), max_length=255, blank=True) full_name = models.CharField(_('page name'), max_length=255, blank=True)
owner_group = models.ForeignKey(Group, related_name="owned_page", default=1) owner_group = models.ForeignKey(Group, related_name="owned_page",
default=settings.AE_GROUPS['root']['id'])
edit_group = models.ManyToManyField(Group, related_name="editable_page", blank=True) edit_group = models.ManyToManyField(Group, related_name="editable_page", blank=True)
view_group = models.ManyToManyField(Group, related_name="viewable_page", blank=True) view_group = models.ManyToManyField(Group, related_name="viewable_page", blank=True)
lock_mutex = {} lock_mutex = {}

View File

@ -49,6 +49,7 @@ MIDDLEWARE_CLASSES = (
'django.contrib.messages.middleware.MessageMiddleware', 'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware',
'django.middleware.security.SecurityMiddleware', 'django.middleware.security.SecurityMiddleware',
'core.middleware.AuthenticationMiddleware',
) )
ROOT_URLCONF = 'sith.urls' ROOT_URLCONF = 'sith.urls'
@ -105,6 +106,7 @@ STATIC_URL = '/static/'
# Auth configuration # Auth configuration
AUTH_USER_MODEL = 'core.User' AUTH_USER_MODEL = 'core.User'
AUTH_ANONYMOUS_MODEL = 'core.models.AnonymousUser'
LOGIN_URL = '/login' LOGIN_URL = '/login'
LOGOUT_URL = '/logout' LOGOUT_URL = '/logout'
LOGIN_REDIRECT_URL = '/' LOGIN_REDIRECT_URL = '/'
@ -113,3 +115,24 @@ DEFAULT_FROM_EMAIL="bibou@git.an"
# Email # Email
EMAIL_HOST="localhost" EMAIL_HOST="localhost"
EMAIL_PORT=25 EMAIL_PORT=25
# AE configuration
AE_GROUPS = {
'root': {
'id': 1,
'name': "root",
},
'board': {
'id': 2,
'name': "ae_bureau",
},
'members': {
'id': 3,
'name': "ae_membres",
},
'public': {
'id': 4,
'name': "not_registered_users",
},
}