adapt all applications to Django 1.5 custom user model

This commit is contained in:
Benjamin Dauvergne 2013-05-24 09:34:28 +02:00
parent 1b74b824ab
commit c63ef71ddb
16 changed files with 69 additions and 66 deletions

View File

@ -3,11 +3,11 @@ from django.contrib.auth.admin import UserAdmin
from django.conf import settings
from .nonce.models import Nonce
from models import User
class NonceModelAdmin(admin.ModelAdmin):
list_display = ("value", "context", "not_on_or_after")
admin.site.register(Nonce, NonceModelAdmin)
if settings.AUTH_USER_MODEL == 'authentic2.User':
from models import User
admin.site.register(User, UserAdmin)

View File

@ -25,7 +25,6 @@ from cPickle import loads, dumps
from django.utils.translation import ugettext_lazy as _
from django.db import models
from django.contrib.auth.models import User
from django.conf import settings
try:
import ldap

View File

@ -1,9 +1,9 @@
import logging
from django.contrib.auth.models import User
from django.db import transaction
from django.conf import settings
from authentic2.compat import get_user_model
import authentic2.vendor.oath.hotp as hotp
from authentic2.nonce import accept_nonce
import models
@ -21,6 +21,7 @@ class OATHTOTPBackend:
'''Lookup the TOTP or HOTP secret for the user and try to authenticate
the proposed OTP using it.
'''
User = get_user_model()
try:
secret = models.OATHTOTPSecret.objects.get(user__username=username)
except models.OATHTOTPSecret.DoesNotExist:
@ -46,6 +47,7 @@ class OATHTOTPBackend:
simply return the user object. That way, we only need top look-up the
certificate once, when loggin in
"""
User = get_user_model()
try:
return User.objects.get(id=user_id)
except User.DoesNotExist:

View File

@ -1,9 +1,9 @@
from django.db import models
from django.contrib.auth.models import User
from django.conf import settings
class OATHTOTPSecret(models.Model):
user = models.OneToOneField(User, primary_key= True,
related_name='oath_totp_secret')
user = models.OneToOneField(getattr(settings, 'AUTH_USER_MODEL', 'auth.User'),
primary_key= True, related_name='oath_totp_secret')
# 20 bytes string as hexadecimal
key = models.CharField(max_length=40)
drift = models.IntegerField(default=0,max_length=4)

View File

@ -1,8 +1,8 @@
from django.db.models import Q
from django.db import transaction
from django.contrib.auth.models import User, UserManager
import logging
from authentic2.compat import get_user_model
from util import settings_get
from models import ClientCertificate, DistinguishedName
@ -33,6 +33,7 @@ class SSLBackend:
simply return the user object. That way, we only need top look-up the
certificate once, when loggin in
"""
User = get_user_model()
try:
return User.objects.get(id=user_id)
except User.DoesNotExist:
@ -84,6 +85,7 @@ settings')
just a subject for the ClientCertificate.
"""
# auto creation only created a DN for the subject, not the issuer
User = get_user_model()
subject = DistinguishedName()
for attr,val in ssl_info.get_subject().iteritems():
if not val: val = ''
@ -127,7 +129,7 @@ settings')
just a subject for the ClientCertificate.
"""
if not user:
return none
return None
# auto creation only created a DN for the subject, not the issuer
subject = DistinguishedName()
@ -136,12 +138,6 @@ settings')
subject.__setattr__(attr.replace('subject_',''), val)
subject.save()
# get username and check if the user exists already
if settings_get('SSLAUTH_CREATE_USERNAME_CALLBACK'):
build_username = settings_get('SSLAUTH_CREATE_USERNAME_CALLBACK')
else:
build_username = self.build_username
# create the certificate record and save
cert = ClientCertificate()
cert.user = user
@ -170,13 +166,13 @@ settings')
newly created certificate record. This method can be "overwritten" by
using the SSLAUTH_CREATE_USER_CALLBACK setting.
"""
name_parts = ssl_info.subject_cn.split()
User = get_user_model()
user = User()
user.username=username
user.password=UserManager().make_random_password()
user.first_name = " ".join(name_parts[:-1])
user.last_name = name_parts[-1]
user.email = ssl_info.subject_email
setattr(user, User.USERNAME_FIELD, username)
if hasattr(User, 'set_unusable_password'):
user.set_unusable_password()
if hasattr(User, 'email'):
user.email = ssl_info.subject_email
user.is_active = True
user.save()
return user

View File

@ -1,9 +1,9 @@
import django.forms as forms
from django.contrib.auth.models import User
from django.contrib.auth import login
from django.utils.translation import ugettext_lazy as _
from models import ClientCertificate, DistinguishedName
from authentic2.compat import get_user_model
from models import ClientCertificate
from util import SSLInfo
# I put this on all required fields, because it's easier to pick up
@ -44,8 +44,9 @@ class RegistrationForm(forms.Form):
in use.
"""
User = get_user_model()
try:
user = User.objects. \
User.objects. \
get(username__iexact=self.cleaned_data['username'])
except User.DoesNotExist:
return self.cleaned_data['username']
@ -64,6 +65,7 @@ class RegistrationForm(forms.Form):
supplied.
"""
User = get_user_model()
ssl_info = SSLInfo(self.request)
if not ssl_info.cert:
raise ValueError('Missing cert')

View File

@ -1,31 +1,26 @@
import logging
import urllib
import django.forms
import authentic2.auth2_auth.models as auth_models
import views
from django.conf import settings
from django.utils.translation import ugettext as _
from django.http import HttpResponseRedirect
from django.shortcuts import render_to_response
from django.core.urlresolvers import reverse
from django.views.decorators.csrf import csrf_exempt
from django.template import RequestContext
from django.template.loader import render_to_string
from django.contrib import messages
from django.contrib.auth.models import AnonymousUser
from django.contrib.auth.views import redirect_to_login
from django.contrib.auth.forms import AuthenticationForm
from django.contrib.auth import authenticate, login, logout, get_user
from django.contrib.auth import authenticate, login
from django.contrib.auth import REDIRECT_FIELD_NAME
from authentic2.auth2_auth import NONCE_FIELD_NAME
from authentic2.saml.common import error_page
from models import ClientCertificate, DistinguishedName
from util import SSLInfo, settings_get
from models import ClientCertificate
from util import SSLInfo
logger = logging.getLogger('authentic2.auth2_auth.auth2_ssl')
@ -226,7 +221,6 @@ def delete_certificate(request, next='/'):
_('No certificate name provided for deletion.'))
return HttpResponseRedirect(next)
certificates = []
try:
certs = ClientCertificate.objects.filter(user=request.user)
for c in certs:

View File

@ -1,19 +1,18 @@
from django.contrib.auth import authenticate, login, get_user
from django.contrib.auth.models import AnonymousUser
from django.conf import settings
from util import SSLInfo, settings_get
from django.contrib.auth.middleware import AuthenticationMiddleware
class SSLAuthMiddleware(object):
"""
attempts to find a valid user based on the client certificate info
"""
def process_request(self, request):
USE_COOKIE = settings_get('SSLAUTH_USE_COOKIE')
if USE_COOKIE:
request.user = get_user(request)
if request.user.is_authenticated():

View File

@ -7,12 +7,12 @@ from django.db import transaction
from django.core.urlresolvers import reverse
from django.utils.translation import ugettext as _
from authentic2.compat import get_user_model
from authentic2.saml.common import \
lookup_federation_by_name_id_and_provider_id, add_federation, \
get_idp_options_policy
from authentic2.saml.models import LIBERTY_SESSION_DUMP_KIND_SP, \
LibertySessionDump, LibertyProvider
from authentic2.models import User, UserManager
from authentic2.authsaml2.models import SAML2TransientUser
logger = logging.getLogger('authentic2.authsaml2.backends')
@ -88,6 +88,7 @@ class AuthSAML2PersistentBackend:
return fed.user
def get_user(self, user_id):
User = get_user_model()
try:
return User.objects.get(id=user_id)
except User.DoesNotExist:
@ -105,9 +106,11 @@ class AuthSAML2PersistentBackend:
# FIXME: maybe keep more information in the forged username
username = 'saml2-%s' % ''. \
join([random.choice(string.letters) for x in range(10)])
User = get_user_model()
user = User()
user.username=username
user.password=UserManager().make_random_password()
user.username = username
if hasattr(User, 'set_unusable_password'):
user.set_unusable_password()
user.is_active = True
user.save()
add_federation(user, name_id=name_id, provider_id=provider_id)

5
authentic2/compat.py Normal file
View File

@ -0,0 +1,5 @@
try:
from django.contrib.auth import get_user_model
except ImportError:
from django.contrib.auth.models import User
get_user_model = lambda: User

View File

@ -10,9 +10,9 @@ from django.http import HttpResponse, HttpResponseForbidden, \
from django.utils.translation import ugettext as _
from django.views.decorators.csrf import csrf_exempt
from django.core.urlresolvers import reverse
from django.contrib.auth.models import User
from django.conf import settings
from authentic2.compat import get_user_model
from authentic2.saml.models import LibertyArtifact
from authentic2.saml.common import get_idff12_metadata, create_idff12_server, \
load_provider, load_federation, load_session, save_federation, \
@ -255,6 +255,7 @@ def check_delegated_authentication_permission(request):
def idp_sso(request, provider_id, user_id = None):
'''Initiate an SSO toward provider_id without a prior AuthnRequest
'''
User = get_user_model()
assert provider_id, 'You must call idp_initiated_sso with a provider_id parameter'
server = create_idff12_server(request, reverse(metadata))
login = lasso.Login(server)

View File

@ -34,11 +34,11 @@ from django.http import HttpResponse, HttpResponseRedirect, \
from django.utils.translation import ugettext as _
from django.views.decorators.csrf import csrf_exempt
from django.contrib.auth import BACKEND_SESSION_KEY
from django.contrib.auth.models import User
from django.conf import settings
from django.utils.encoding import smart_unicode
from django.contrib.auth import load_backend
from authentic2.compat import get_user_model
import authentic2.idp as idp
import authentic2.idp.views as idp_views
from authentic2.idp.models import get_attribute_policy
@ -929,6 +929,7 @@ def idp_sso(request, provider_id=None, user_id=None, nid_format=None,
save=True, return_profile=False):
'''Initiate an SSO toward provider_id without a prior AuthnRequest
'''
User = get_user_model()
if request.method == 'GET':
logger.info('idp_sso: to initiate a sso we need a post form')
return error_page(request,
@ -951,7 +952,6 @@ def idp_sso(request, provider_id=None, user_id=None, nid_format=None,
logger.info('idp_sso: sso for an unknown provider %s' % provider_id)
return error_page(request, _('Provider %s is unknown') % provider_id,
logger=logger)
service_provider = liberty_provider.service_provider
if user_id:
user = User.get(id=user_id)
if not check_delegated_authentication_permission(request):

View File

@ -11,8 +11,7 @@ from django.contrib.auth.models import (AbstractBaseUser, PermissionsMixin,
BaseUserManager, SiteProfileNotAvailable)
from django.contrib.auth import load_backend
from django.utils.http import urlquote
from idp.models import UserProfile
from django.conf import settings
class UserManager(BaseUserManager):
@ -48,7 +47,7 @@ class AbstractUser(AbstractBaseUser, PermissionsMixin):
Username, password and email are required. Other fields are optional.
"""
username = models.CharField(_('username'), max_length=30, unique=True,
username = models.CharField(_('username'), max_length=256, unique=True,
help_text=_('Required. 30 characters or fewer. Letters, numbers and '
'@/./+/-/_ characters'),
validators=[
@ -164,18 +163,19 @@ class AbstractUser(AbstractBaseUser, PermissionsMixin):
roles = property(get_roles)
class User(AbstractUser):
first_name = models.CharField(_('first name'), max_length=30, blank=True)
last_name = models.CharField(_('last name'), max_length=30, blank=True)
email = models.EmailField(_('e-mail address'), max_length=128, blank=True)
nickname = models.CharField(_('nickname'), max_length=50, blank=True)
url = models.URLField(_('Website'), blank=True)
company = models.CharField(verbose_name=_("Company"),
max_length=50, blank=True)
phone = models.CharField(verbose_name=_("Phone"),
max_length=50, blank=True)
postal_address = models.TextField(verbose_name=_("Postal address"),
max_length=255, blank=True)
if settings.AUTH_USER_MODEL == 'authentic2.User':
class User(AbstractUser):
first_name = models.CharField(_('first name'), max_length=30, blank=True)
last_name = models.CharField(_('last name'), max_length=30, blank=True)
email = models.EmailField(_('e-mail address'), max_length=128, blank=True)
nickname = models.CharField(_('nickname'), max_length=50, blank=True)
url = models.URLField(_('Website'), blank=True)
company = models.CharField(verbose_name=_("Company"),
max_length=50, blank=True)
phone = models.CharField(verbose_name=_("Phone"),
max_length=50, blank=True)
postal_address = models.TextField(verbose_name=_("Postal address"),
max_length=255, blank=True)
USER_PROFILE = ( 'username', 'first_name', 'last_name', 'email',
'nickname', 'url', 'phone', ('roles', _('roles')),)
USER_PROFILE = ( 'username', 'first_name', 'last_name', 'email',
'nickname', 'url', 'phone', ('roles', _('roles')),)

View File

@ -3,11 +3,9 @@ from django.contrib.auth import login
from registration.backends.simple import SimpleBackend as OldSimpleBackend
from registration import signals
try:
from django.contrib.auth import get_user_model
except ImportError: # django < 1.5
from django.contrib.auth.models import User
get_user_model = lambda: User
from authentic2.compat import get_user_model
class SimpleBackend(OldSimpleBackend):
def register(self, request, **kwargs):

View File

@ -7,7 +7,6 @@ import datetime
import lasso
from django.db import models
from django.conf import settings
from django.contrib.auth.models import User
from django.core.exceptions import ValidationError
from django.utils.translation import ugettext_lazy as _
from django.core.exceptions import ObjectDoesNotExist

View File

@ -1,10 +1,14 @@
import pam
from django.conf import settings
from django.contrib.auth.models import User
from authentic2.compat import get_user_model
class PAMBackend:
def authenticate(self, username=None, password=None):
User = get_user_model()
service = getattr(settings, 'PAM_SERVICE', 'login')
if pam.authenticate(username, password, service=service):
try:
@ -23,6 +27,7 @@ class PAMBackend:
return None
def get_user(self, user_id):
User = get_user_model()
try:
return User.objects.get(pk=user_id)
except User.DoesNotExist: