Unusable passwords for LDAP users

 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. Support for permissions for anonymous users in django ModelBackend by jb 1 year, 6 months ago
  2. Require login by url by zbyte64 4 years, 9 months ago
  3. Authenticate against Active Directory - LDAP (my version) by trebor74hr 4 years, 1 month ago
  4. Simple E-mail registration by bthomas 4 years, 6 months ago
  5. create_model_instances management command by Lacrymology 3 months, 4 weeks ago

Comments

(Forgotten your password?)