Login

Unusable passwords for LDAP users

Author:
rob.ward
Posted:
January 29, 2009
Language:
Python
Version:
1.0
Tags:
admin ldap password
Score:
0 (after 0 ratings)

An example of how to modify the admin user creation form to assign an unusable password to externally authenticated users when they are created.

This code is more intimate with the django.contrib.auth classes than I'd like, but it should be fairly straightforward to maintain should the relevant django.contrib.auth classes change.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
from django import forms
from django.contrib import admin
from django.contrib.auth.admin import UserAdmin 
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.models import User


class ExternalUserCreationForm(UserCreationForm):
	"""
	In your templates directory create a version of admin/auth/user/add_user.html
	that includes the is_ldap_authenticated field. E.g.

	<div class="form-row">
  		<label for="id_is_ldap_authenticated" class="required">
			LDAP authenticated:</label> {{ form.is_ldap_authenticated }}
	</div>
	"""
    is_ldap_authenticated = forms.BooleanField(initial=True, required=False)
    
    def _is_ldap_user(self):
        result = False
        if self.cleaned_data.has_key('is_ldap_authenticated'):
            result = self.cleaned_data['is_ldap_authenticated']
        return result
            
    def clean(self):
        cleaned_data = super(ExternalUserCreationForm, self).clean()
        # Ignore password errors if we aren't using the password field
        if self._is_ldap_user():
            if self.errors.has_key('password1'):
                del self.errors['password1']
            if self.errors.has_key('password2'):
                del self.errors['password2']
        return cleaned_data
        
    def save(self, commit=True):
        if self._is_ldap_user():
            user = super(UserCreationForm, self).save(commit=False)
            user.set_unusable_password()
            if commit:
                user.save()
        else:
            user = super(ExternalUserCreationForm, self).save(commit=commit)
        return user


class ExtendedUserAdmin(UserAdmin):
    add_form = ExternalUserCreationForm


admin.site.unregister(User) 
admin.site.register(User, ExtendedUserAdmin)

More like this

  1. Authenticate against Active Directory - LDAP (my version) by trebor74hr 6 years, 3 months ago
  2. Simple E-mail registration by bthomas 6 years, 7 months ago
  3. A complete Usercake compatible password hasher by moshthepitt 1 year, 2 months ago
  4. Authenticate with Email Address by thom 8 years, 3 months ago
  5. LDAP to Django Synchronization by Mogga 6 years, 11 months ago

Comments

Please login first before commenting.