Ejemplo n.º 1
0
 def test_role_access_control_granted(self):
     client = Client()
     service = self.service
     service.add_authorized_role(self.authorized_service)
     get_user_model().objects.get(username=self.LOGIN).roles.add(
         self.authorized_service)
     assert service.authorized_roles.exists() is True
     response = client.get('/idp/cas/login',
                           {constants.SERVICE_PARAM: self.URL})
     location = response['Location']
     query = urlparse.parse_qs(location.split('?')[1])
     next_url, next_url_query = query['next'][0].split('?')
     next_url_query = urlparse.parse_qs(next_url_query)
     response = client.post(location, {
         'login-password-submit': '',
         'username': self.LOGIN,
         'password': self.PASSWORD
     },
                            follow=False)
     response = client.get(response.url)
     client = Client()
     ticket_id = urlparse.parse_qs(
         response.url.split('?')[1])[constants.TICKET_PARAM][0]
     response = client.get('/idp/cas/validate', {
         constants.TICKET_PARAM: ticket_id,
         constants.SERVICE_PARAM: self.URL
     })
Ejemplo n.º 2
0
    def create_user(self, ssl_info):
        """
        This method creates a new django User and ClientCertificate record
        for the passed certificate info. It does not create an issuer record,
        just a subject for the ClientCertificate.
        """
        # auto creation only created a DN for the subject, not the issuer
        User = get_user_model()

        # get username and check if the user exists already
        if app_settings.CREATE_USERNAME_CALLBACK:
            build_username = app_settings.CEATE_USERNAME_CALLBACK
        else:
            build_username = self.build_username

        username = build_username(ssl_info)

        try:
            user = User.objects.get(username=username)
        except User.DoesNotExist:
            if app_settings.CREATE_USER_CALLBACK:
                build_user = app_settings.CREATE_USER_CALLBACK
            else:
                build_user = self.build_user
            user = build_user(username, ssl_info)

        # create the certificate record and save
        self.link_user(ssl_info, user)
        return user
Ejemplo n.º 3
0
 def setUp(self):
     User = get_user_model()
     Role = get_role_model()
     self.user = User.objects.create_user(self.LOGIN,
                                          password=self.PASSWORD,
                                          email=self.EMAIL,
                                          first_name=self.FIRST_NAME,
                                          last_name=self.LAST_NAME)
     self.service = Service.objects.create(
         name=self.NAME,
         slug=self.SLUG,
         urls=self.URL,
         identifier_attribute='django_user_username',
         ou=get_default_ou(),
         logout_url=self.URL + 'logout/')
     self.service_attribute1 = Attribute.objects.create(
         service=self.service,
         slug='email',
         attribute_name='django_user_email')
     self.service2 = Service.objects.create(
         name=self.NAME2,
         slug=self.SLUG2,
         urls=self.URL2,
         ou=get_default_ou(),
         identifier_attribute='django_user_email')
     self.service2_attribute1 = Attribute.objects.create(
         service=self.service2,
         slug='username',
         attribute_name='django_user_username')
     self.authorized_service = Role.objects.create(name='rogue',
                                                   ou=get_default_ou())
     self.factory = RequestFactory()
Ejemplo n.º 4
0
 def setUp(self):
     User = get_user_model()
     self.user = User.objects.create_user(
         self.LOGIN, password=self.PASSWORD, email=self.EMAIL, first_name=self.FIRST_NAME, last_name=self.LAST_NAME
     )
     self.service = Service.objects.create(
         name=self.NAME,
         slug=self.SLUG,
         urls=self.URL,
         identifier_attribute="django_user_username",
         ou=get_default_ou(),
         logout_url=self.URL + "logout/",
     )
     self.service_attribute1 = Attribute.objects.create(
         service=self.service, slug="email", attribute_name="django_user_email"
     )
     self.service2 = Service.objects.create(
         name=self.NAME2,
         slug=self.SLUG2,
         urls=self.URL2,
         ou=get_default_ou(),
         identifier_attribute="django_user_email",
     )
     self.service2_attribute1 = Attribute.objects.create(
         service=self.service2, slug="username", attribute_name="django_user_username"
     )
     self.factory = RequestFactory()
Ejemplo n.º 5
0
 def get(self, request, *args, **kwargs):
     if 'token' in request.GET:
         User = get_user_model()
         try:
             token = signing.loads(request.GET['token'], max_age=7200)
             user_pk = token['user_pk']
             email = token['email']
             site_pk = token['site_pk']
             site = get_current_site(request)
             if site.pk != site_pk:
                 raise ValueError
             user = User.objects.get(pk=user_pk)
             user.email = email
             user.save()
             messages.info(request, _('your request for changing your email for {0} '
                 'is successful').format(email))
         except signing.SignatureExpired:
             messages.error(request, _('your request for changing your email is too '
                 'old, try again'))
         except signing.BadSignature:
             messages.error(request, _('your request for changing your email is '
                 'invalid, try again'))
         except ValueError:
             messages.error(request, _('your request for changing your email was not '
                 'on this site, try again'))
         except User.DoesNotExist:
             messages.error(request, _('your request for changing your email is for '
                 'an unknown user, try again'))
     return shortcuts.redirect(settings.LOGIN_REDIRECT_URL)
Ejemplo n.º 6
0
    def clean(self):
        if 'username' in self.fields or 'email' in self.fields:
            if not self.cleaned_data.get('username') and \
               not self.cleaned_data.get('email'):
                raise forms.ValidationError(
                    _('You must set a username or an email.'))

        User = get_user_model()
        if self.cleaned_data.get('email'):
            qs = User.objects.all()
            ou = getattr(self, 'ou', None)

            if self.instance and self.instance.pk:
                qs = qs.exclude(pk=self.instance.pk)
                ou = self.instance.ou

            email = self.cleaned_data['email']
            already_used = False

            if a2_app_settings.A2_EMAIL_IS_UNIQUE and qs.filter(
                    email=email).exists():
                already_used = True

            if ou and ou.email_is_unique and qs.filter(ou=ou,
                                                       email=email).exists():
                already_used = True

            if already_used:
                raise forms.ValidationError(
                    {'email': _('Email already used.')})
Ejemplo n.º 7
0
 def save(self, profile_callback=None):
     """
     Create the new ``User`` and ``RegistrationProfile``, and
     returns the ``User``.
     
     This is essentially a light wrapper around
     ``RegistrationProfile.objects.create_inactive_user()``,
     feeding it the form data and a profile callback (see the
     documentation on ``create_inactive_user()`` for details) if
     supplied.
     
     """
     User = get_user_model()
     ssl_info = SSLInfo(self.request)
     if not ssl_info.cert:
         raise ValueError('Missing cert')
     new_user = User.objects.create_user(
             username=self.cleaned_data['username'],
             email=self.cleaned_data['email'])
     new_user.backend = 'authentic2.auth2_auth.auth2_ssl.backend.SSLBackend'
     cert = ClientCertificate()
     cert.user = new_user
     cert.cert = ssl_info.cert
     cert.save()
     # Automatically log in the new user
     login(self.request, new_user)
     return new_user
Ejemplo n.º 8
0
    def create_user(self, ssl_info):
        """
        This method creates a new django User and ClientCertificate record
        for the passed certificate info. It does not create an issuer record,
        just a subject for the ClientCertificate.
        """
        # auto creation only created a DN for the subject, not the issuer
        User = get_user_model()

        # get username and check if the user exists already
        if app_settings.CREATE_USERNAME_CALLBACK:
            build_username = app_settings.CEATE_USERNAME_CALLBACK
        else:
            build_username = self.build_username

        username = build_username(ssl_info)

        try:
            user = User.objects.get(username=username)
        except User.DoesNotExist:
            if app_settings.CREATE_USER_CALLBACK:
                build_user = app_settings.CREATE_USER_CALLBACK
            else:
                build_user = self.build_user
            user = build_user(username, ssl_info)

        # create the certificate record and save
        self.link_user(ssl_info, user)
        return user
Ejemplo n.º 9
0
 def lookup_by_username(self, username):
     User = get_user_model()
     try:
         log.debug('lookup using username %r', username)
         return LDAPUser.objects.get(username=username)
     except User.DoesNotExist:
         return
Ejemplo n.º 10
0
    def clean(self):
        super(UserAddForm, self).clean()
        User = get_user_model()

        if not self.cleaned_data.get('username') and \
           not self.cleaned_data.get('email'):
            raise forms.ValidationError(
                _('You must set a username or an email.'))
Ejemplo n.º 11
0
 class Meta:
     model = get_user_model()
     attrs = {'class': 'main', 'id': 'user-table'}
     fields = ('username', 'email', 'first_name', 'last_name', 'is_active',
               'email_verified', 'ou')
     sequence = ('link', '...')
     empty_text = _('None')
     order_by = ('first_name', 'last_name', 'email', 'username')
Ejemplo n.º 12
0
    def test_ldap_provisionning(self):
        conn = self.slapd.get_connection()
        ressources = [{
            'name': 'ldap',
            'url': self.slapd.ldap_url,
            'bind_dn': self.slapd.root_bind_dn,
            'bind_pw': self.slapd.root_bind_password,
            'base_dn': 'o=orga',
            'rdn_attributes': [
                'uid',
            ],
            'attribute_mapping': {
                'uid': 'django_user_username',
                'givenName': 'django_user_first_name',
                'sn': 'django_user_last_name',
                'mail': 'django_user_email',
            },
            'format_mapping': {
                'cn': ['{django_user_first_name} {django_user_last_name}'],
            },
            'static_attributes': {
                'objectclass': 'inetorgperson',
            },
            'ldap_filter': '(objectclass=inetorgperson)',
        }]
        User = compat.get_user_model()
        users = [
            User(username='******' % i,
                 first_name='john',
                 last_name='doe',
                 email='*****@*****.**') for i in range(1000)
        ]

        User.objects.bulk_create(users)
        self.slapd.add_ldif('''dn: uid=test,o=orga
objectClass: inetOrgPerson
uid: test
cn: test
sn: test
gn: test
mail: test''')
        with self.settings(A2_PROVISIONNING_RESSOURCES=ressources):
            call_command('provision', 'ldap')
        results = conn.search_s('o=orga', ldap.SCOPE_ONELEVEL)
        self.assertEqual(len(results), 1000)
        for dn, entry in results:
            uid = entry['uid'][0]
            self.assertTrue(uid.startswith('john.doe'))
            self.assertEquals(
                entry, {
                    'objectClass': ['inetOrgPerson'],
                    'uid': [uid],
                    'sn': [users[0].last_name],
                    'givenName': [users[0].first_name],
                    'cn':
                    ['%s %s' % (users[0].first_name, users[0].last_name)],
                    'mail': [users[0].email]
                })
Ejemplo n.º 13
0
 def get_user(self, user_id):
     """
     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:
         return None
Ejemplo n.º 14
0
 def get_user(self, user_id):
     """
     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:
         return None
Ejemplo n.º 15
0
 def clean_username(self):
     # Since User.username is unique, this check is redundant,
     # but it sets a nicer error message than the ORM. See #13147.
     username = self.cleaned_data["username"]
     User = get_user_model()
     try:
         User._default_manager.get(username=username)
     except User.DoesNotExist:
         return username
     raise ValidationError(self.error_messages["duplicate_username"])
Ejemplo n.º 16
0
    def clean_username(self):
        """
        Validate that the username is alphanumeric and is not already
        in use.

        """
        existing = get_user_model().objects.filter(username__iexact=self.cleaned_data['username'])
        if existing.exists():
            raise forms.ValidationError(_("A user with that username already exists."))
        else:
            return self.cleaned_data['username']
Ejemplo n.º 17
0
    def _return_user(self, uri, dn, username, password, conn, block):
        try:
            user = get_user_model().objects.get(username=username)
        except get_user_model().DoesNotExist:
            log.info('User %s did not exist in Django database, creating' % username)
            user = get_user_model()(username=username, password='')
            user.set_unusable_password()
        backend_id = '%s!%s' % (uri, dn)
        if user.backend != self.backend_name() or user.backend_id != backend_id:
            user.backend = self.backend_name()
            user.backend_id = backend_id

        log.debug('Getting information for %s from LDAP' % username)
        try:
            results = conn.search_s(dn, ldap.SCOPE_BASE, '(objectclass=*)',
                    [block['email_field'], block['fname_field'],
                        block['lname_field']])
        except ldap.LDAPError, e:
            log.warning('Could not get user information for %r, returning possibly stale user object' % username)
            user.save()
            return user
Ejemplo n.º 18
0
    def register(self, request, **kwargs):
        """
        Create and immediately log in a new user.
        """
        create_kwargs = {
                'username': kwargs['username'],
                'email': kwargs['email'], 
                'password': kwargs['password1']
        }
        for required_field in get_user_model().REQUIRED_FIELDS:
            create_kwargs[required_field] = kwargs[required_field]
        get_user_model().objects.create_user(**create_kwargs)

        # authenticate() always has to be called before login(), and
        # will return the user we just created.
        new_user = authenticate(username=create_kwargs['username'], password=create_kwargs['password'])
        login(request, new_user)
        signals.user_registered.send(sender=self.__class__,
                                     user=new_user,
                                     request=request)
        return new_user
Ejemplo n.º 19
0
def su(request, username, redirect_url='/'):
    '''To use this view add:

       url(r'^su/(?P<username>.*)/$', 'authentic2.views.su', {'redirect_url': '/'}),
    '''
    if request.user.is_superuser or request.session.get('has_superuser_power'):
        su_user = shortcuts.get_object_or_404(get_user_model(), username=username)
        if su_user.is_active:
            request.session[SESSION_KEY] = su_user.id
            request.session['has_superuser_power'] = True
            return http.HttpResponseRedirect(redirect_url)
    else:
        return http.HttpResponseRedirect('/')
Ejemplo n.º 20
0
    def test_ldap_provisionning(self):
        ressources = [{
            'name': 'ldap',
            'url': self.slapd.ldapi_url,
            'bind_dn': 'uid=admin,o=orga',
            'bind_pw': 'admin',
            'base_dn': 'o=orga',
            'rdn_attributes': ['uid',],
            'attribute_mapping': {
                'uid': 'django_user_username',
                'givenName': 'django_user_first_name',
                'sn': 'django_user_last_name',
                'mail': 'django_user_email',
            },
            'format_mapping': {
                'cn': ['{django_user_first_name} {django_user_last_name}'],
            },
            'static_attributes': {
                'objectclass': 'inetorgperson',
            },
            'ldap_filter': '(objectclass=inetorgperson)',
        }]
        User = compat.get_user_model()
        users = [User(username='******' % i,
                first_name='john',
                last_name='doe',
                email='*****@*****.**') for i in range(1000)]

        User.objects.bulk_create(users)
        self.slapd.add_ldif('''dn: uid=test,o=orga
objectClass: inetOrgPerson
uid: test
cn: test
sn: test
gn: test
mail: test''')
        with self.settings(A2_PROVISIONNING_RESSOURCES=ressources):
            call_command('provision', 'ldap', batch_size=1000)
        results = self.conn.search_s('o=orga', ldap.SCOPE_ONELEVEL)
        self.assertEqual(len(results), 1000)
        for dn, entry in results:
            uid = entry['uid'][0]
            self.assertTrue(uid.startswith('john.doe'))
            self.assertEquals(entry, {
                        'objectClass': ['inetOrgPerson'],
                        'uid': [uid],
                        'sn': [users[0].last_name],
                        'givenName': [users[0].first_name],
                        'cn': ['%s %s' % (users[0].first_name, users[0].last_name)],
                        'mail': [users[0].email]
            })
Ejemplo n.º 21
0
 def authenticate(self, username, oath_otp, format='dec6'):
     '''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:
         return None
     try:
         accepted, drift = hotp.accept_totp(secret.key, oath_otp, format=format)
     except Exception, e:
         logger.exception('hotp.accept_totp raised', e)
         raise
Ejemplo n.º 22
0
 def lookup_by_external_id(self, block, attributes):
     User = get_user_model()
     for eid_tuple in block['external_id_tuples']:
         external_id = self.build_external_id(eid_tuple, attributes)
         if not external_id:
             continue
         try:
             log.debug('lookup using external_id %r: %r', eid_tuple,
                     external_id)
             return LDAPUser.objects.get(
                     userexternalid__external_id=external_id,
                     userexternalid__source=block['realm'])
         except User.DoesNotExist:
             pass
Ejemplo n.º 23
0
 def clean_username(self):
     """
     Validate that the username is alphanumeric and is not already
     in use.
     
     """
     User = get_user_model()
     try:
         User.objects. \
             get(username__iexact=self.cleaned_data['username'])
     except User.DoesNotExist:
         return self.cleaned_data['username']
     raise forms.ValidationError(_(u'This username is already taken. \
         Please choose another.'))
Ejemplo n.º 24
0
 def build_user(self, username, ssl_info):
     """
     create a valid (and stored) django user to be associated with the
     newly created certificate record. This method can be "overwritten" by
     using the SSLAUTH_CREATE_USER_CALLBACK setting.
     """
     User = get_user_model()
     user = User()
     setattr(user, User.USERNAME_FIELD, username)
     if hasattr(User, 'set_unusable_password'):
         user.set_unusable_password()
     user.is_active = True
     user.save()
     return user
Ejemplo n.º 25
0
 def build_user(self, username, ssl_info):
     """
     create a valid (and stored) django user to be associated with the
     newly created certificate record. This method can be "overwritten" by
     using the SSLAUTH_CREATE_USER_CALLBACK setting.
     """
     User = get_user_model()
     user = User()
     setattr(user, User.USERNAME_FIELD, username)
     if hasattr(User, 'set_unusable_password'):
         user.set_unusable_password()
     user.is_active = True
     user.save()
     return user
Ejemplo n.º 26
0
 class Meta:
     model = get_user_model()
     exclude = ('password', 'user_permissions', 'is_staff',
                'is_superuser', 'groups')
     export_order = ('ou', 'uuid', 'id', 'username', 'email',
                     'first_name', 'last_name', 'last_login',
                     'date_joined', 'roles')
     widgets = {
         'roles': {
             'field': 'name',
         },
         'ou': {
             'field': 'name',
         }
     }
Ejemplo n.º 27
0
 def save_user(self, user, username):
     User = get_user_model()
     parts = username.split('@', 1)
     if len(parts) == 1:
         left, right = user, ''
     else:
         left, right = parts
     for i in itertools.count(0):
         setattr(user, User.USERNAME_FIELD, username)
         try:
             sid = transaction.savepoint()
             user.save()
             transaction.savepoint_commit(sid)
             break
         except DatabaseError:
             transaction.savepoint_rollback(sid)
         username = u'{0}{1}@{2}'.format(left, i, right)
Ejemplo n.º 28
0
def patch_authentic_user():
    User = get_user_model()
    OU = get_ou_model()
    Role = get_role_model()
    organisation_unit = OU.objects.get(default=True)
    user_admin_commune = User.objects.get_or_create(
        username='******')[0]
    with provisionning:

        role_agent_fabriques = Role(name='Agent ayant acces aux fabriques',
                                    ou=organisation_unit)
        role_agent_fabriques.save()

        with open("/tmp/tmp_uuid_agent_fabriques.txt", 'w') as f:
            f.write(role_agent_fabriques.uuid)

        # Set role to user
        role_agent_fabriques.members.add(user_admin_commune)
Ejemplo n.º 29
0
    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:
                user = User.objects.get(username=username)
            except:
                user = User(username=username, password='******')

                if getattr(settings, 'PAM_IS_SUPERUSER', False):
                  user.is_superuser = True

                if getattr(settings, 'PAM_IS_STAFF', user.is_superuser):
                  user.is_staff = True

                user.save()
            return user
        return None
Ejemplo n.º 30
0
def modelform_factory(model, **kwargs):
    '''Build a modelform for the given model,

       For the user model also add attribute based fields.
    '''
    from authentic2 import models

    form = kwargs.pop('form', None)
    fields = kwargs.get('fields') or []
    required = list(kwargs.pop('required', []) or [])
    d = {}
    # KV attributes are only supported for the user model currently
    modelform = None
    if issubclass(model, get_user_model()):
        if not form:
            form = BaseUserForm
        attributes = models.Attribute.objects.all()
        for attribute in attributes:
            if attribute.name not in fields:
                continue
            d[attribute.name] = attribute.get_form_field()
        for field in app_settings.A2_REQUIRED_FIELDS:
            if not field in required:
                required.append(field)
    if not form or not hasattr(form, 'Meta'):
        meta_d = {'model': model, 'fields': '__all__'}
        meta = type('Meta', (), meta_d)
        d['Meta'] = meta
    if not form:  # fallback
        form = forms.ModelForm
    modelform = None
    if required:

        def __init__(self, *args, **kwargs):
            super(modelform, self).__init__(*args, **kwargs)
            for field in required:
                if field in self.fields:
                    self.fields[field].required = True

        d['__init__'] = __init__
    modelform = type(model.__name__ + 'ModelForm', (form, ), d)
    kwargs['form'] = modelform
    modelform.required_css_class = 'form-field-required'
    return django_modelform_factory(model, **kwargs)
Ejemplo n.º 31
0
 def create_user(self, username=None, name_id=None, provider_id=None):
     '''Create a new user mapping to the given NameID'''
     if not name_id or \
              name_id.format != \
              lasso.SAML2_NAME_IDENTIFIER_FORMAT_PERSISTENT:
         raise ValueError('Invalid NameID')
     if not username:
         # FIXME: maybe keep more information in the forged username
         username = '******' % ''. \
             join([random.choice(string.letters) for x in range(10)])
     User = get_user_model()
     user = User()
     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)
     return user
Ejemplo n.º 32
0
    def create_user(self, ssl_info):
        """
        This method creates a new django User and ClientCertificate record
        for the passed certificate info. It does not create an issuer record,
        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 = ''
            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

        username = build_username(ssl_info)

        try:
            user = User.objects.get(username=username)
        except User.DoesNotExist:
            if settings_get('SSLAUTH_CREATE_USER_CALLBACK'):
                build_user = settings_get('SSLAUTH_CREATE_USER_CALLBACK')
            else:
                build_user = self.build_user
            user = build_user(username, ssl_info)

        # create the certificate record and save
        cert = ClientCertificate()
        cert.user = user
        cert.subject = subject
        if ssl_info.cert:
            cert.cert = ssl_info.cert
        if ssl_info.serial:
            cert.serial = ssl_info.serial
        cert.save()

        return user
Ejemplo n.º 33
0
def modelform_factory(model, **kwargs):
    '''Build a modelform for the given model,

       For the user model also add attribute based fields.
    '''
    form = kwargs.pop('form', None)
    fields = kwargs.get('fields') or []
    required = list(kwargs.pop('required', []) or [])
    d = {}
    # KV attributes are only supported for the user model currently
    modelform = None
    if issubclass(model, get_user_model()):
        if not form:
            form = BaseUserForm
        attributes = models.Attribute.objects.all()
        for attribute in attributes:
            if attribute.name not in fields:
                continue
            d[attribute.name] = attribute.get_form_field()
        for field in app_settings.A2_REQUIRED_FIELDS:
            if not field in required:
                required.append(field)
    if not form or not hasattr(form, 'Meta'):
        meta_d = {'model': model, 'fields': '__all__'}
        meta = type('Meta', (), meta_d)
        d['Meta'] = meta
    if not form:  # fallback
        form = forms.ModelForm
    modelform = None
    if required:
        def __init__(self, *args, **kwargs):
            super(modelform, self).__init__(*args, **kwargs)
            for field in required:
                if field in self.fields:
                    self.fields[field].required = True
        d['__init__'] = __init__
    modelform = type(model.__name__ + 'ModelForm', (form,), d)
    kwargs['form'] = modelform
    return django_modelform_factory(model, **kwargs)
Ejemplo n.º 34
0
    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:
                user = User.objects.get(username=username)
            except:
                user = User(username=username, password='******')

                if getattr(settings, 'PAM_IS_SUPERUSER', False):
                    user.is_superuser = True

                if getattr(settings, 'PAM_IS_STAFF', user.is_superuser):
                    user.is_staff = True

                user.save()
            if not is_user_authenticable(user):
                logger.info(
                    u'auth_pam: authentication refused by user filters')
                return None

            return user
        return None
Ejemplo n.º 35
0
 def get_user(self, user_id):
     User = get_user_model()
     try:
         return User.objects.get(id=user_id)
     except User.DoesNotExist:
         return None
Ejemplo n.º 36
0
 class Meta:
     model = get_user_model()
     fields = ()
Ejemplo n.º 37
0
 class Meta:
     model = get_user_model()
     fields = '__all__'
     exclude = ('ou', )
Ejemplo n.º 38
0
 def get_user(self, user_id):
     try:
         return get_user_model().objects.get(pk=user_id)
     except get_user_model().DoesNotExist:
         return None
Ejemplo n.º 39
0
 def setUp(self):
     User = get_user_model()
     self.user = User.objects.create_user(self.LOGIN, password=self.PASSWORD)
     self.factory = RequestFactory()
Ejemplo n.º 40
0
 def __init__(self, user=None, *args, **kwargs):
     self.user = user
     super(UserProfileForm, self).__init__(**kwargs)
     for field in get_user_model().REQUIRED_FIELDS:
         self.fields[field].required = True
Ejemplo n.º 41
0
 def __init__(self, *args, **kwargs):
     super(RegistrationForm, self).__init__(*args, **kwargs)
     for field in get_user_model().REQUIRED_FIELDS:
         self.fields[field].required = True
Ejemplo n.º 42
0
 def get_user(self, user_id):
     User = get_user_model()
     try:
         return User.objects.get(pk=user_id)
     except User.DoesNotExist:
         return None
Ejemplo n.º 43
0
 def sync_ldap_ressource(self, ressource, **options):
     verbosity = int(options['verbosity'])
     fake = options['fake']
     # FIXME: Check ressource well formedness
     conn = paged.PagedLDAPObject(ressource['url'],
                                  retry_max=10,
                                  retry_delay=2)
     base_dn = ressource['base_dn']
     use_tls = ressource.get('use_tls')
     bind_dn = ressource.get('bind_dn')
     bind_pw = ressource.get('bind_pw')
     if use_tls:
         conn.start_tls_s()
     if bind_dn:
         conn.simple_bind_s(bind_dn, bind_pw)
     attribute_mapping = utils.lower_keys(ressource['attribute_mapping'])
     static_attributes = utils.lower_keys(
         ressource.get('static_attributes', {}))
     format_mapping = utils.lower_keys(ressource.get('format_mapping', {}))
     attributes = set(attribute_mapping.keys()) | set(
         static_attributes.keys())
     default_ctx = ressource.get('attribute_context', {})
     ldap_filter = ressource.get('ldap_filter', '(objectclass=*)')
     delete = ressource.get('delete', True)
     User = compat.get_user_model()
     qs = User.objects.filter(**ressource.get('a2_filter', {}))
     todelete = set()
     user_dns = set()
     for batch in utils.batch(qs, options['batch_size']):
         ldap_users = {}
         filters = []
         for user in batch:
             ctx = default_ctx.copy()
             ctx['user'] = user
             ctx = get_attributes(ctx)
             ldap_attributes = {}
             for ldap_attribute, a2_attributes in attribute_mapping.iteritems(
             ):
                 if not isinstance(a2_attributes, (tuple, list)):
                     a2_attributes = [a2_attributes]
                 for a2_attribute in a2_attributes:
                     self.add_values(ldap_attributes, ldap_attribute,
                                     ctx.get(a2_attribute))
             for ldap_attribute, values in static_attributes.iteritems():
                 self.add_values(ldap_attributes, ldap_attribute, values)
             for ldap_attribute, fmt_tpls in format_mapping.iteritems():
                 for fmt_tpl in fmt_tpls:
                     self.add_values(ldap_attributes, ldap_attribute,
                                     [fmt_tpl.format(**ctx)])
             dn, filt = self.build_dn_and_filter(ressource, ldap_attributes)
             user_dns.add(dn)
             ldap_users[dn] = ldap_attributes
             filters.append(filt)
         batch_filter = ldap_filter
         if filters:
             batch_filter = self.format_filter(
                 ('&', (batch_filter, ('|', filters))))
         existing_dn = set()
         for dn, entry in conn.paged_search_ext_s(base_dn,
                                                  ldap.SCOPE_SUBTREE,
                                                  batch_filter,
                                                  list(attributes)):
             entry = utils.to_dict_of_set(utils.lower_keys(entry))
             if dn not in ldap_users:
                 todelete.add(dn)
                 continue
             if entry == utils.to_dict_of_set(ldap_users[dn]):
                 # no need to update, entry is already ok
                 del ldap_users[dn]
                 continue
             existing_dn.add(dn)
         for dn, ldap_attributes in ldap_users.iteritems():
             if dn in existing_dn:
                 modlist = []
                 for key, values in ldap_attributes:
                     modlist.append((ldap.MOD_REPLACE, key, values))
                 if not fake:
                     conn.modify(dn, modlist)
                 if verbosity > 1:
                     print '- Replace %s values for %s' % (dn, ', '.join(
                         ldap_attributes.keys()))
             else:
                 if not fake:
                     conn.add(dn, ldap.modlist.addModlist(ldap_attributes))
                 if verbosity > 1:
                     print '- Add %s with values for %s' % (dn, ', '.join(
                         ldap_attributes.keys()))
         # wait for results
         if not fake:
             for x in ldap_users:
                 conn.result()
     for dn, entry in conn.paged_search_ext_s(base_dn, ldap.SCOPE_SUBTREE,
                                              ldap_filter):
         # ignore the basedn
         if dn == base_dn:
             continue
         if dn not in user_dns and dn not in todelete:
             if not fake:
                 todelete.add(dn)
     if delete:
         if verbosity > 1:
             print '- Deleting:', ', '.join(todelete)
         if not fake:
             for dn in todelete:
                 conn.delete(dn)
             for dn in todelete:
                 conn.result()
Ejemplo n.º 44
0
 class Meta:
     model = get_user_model()
     exclude = ('is_staff', 'groups', 'user_permissions', 'last_login',
                'date_joined', 'password')
Ejemplo n.º 45
0
 def sync_ldap_ressource(self, ressource, **options):
     verbosity = int(options['verbosity'])
     fake = options['fake']
     # FIXME: Check ressource well formedness
     conn = ldap_utils.PagedLDAPObject(ressource['url'], retry_max=10,
             retry_delay=2)
     base_dn = ressource['base_dn']
     use_tls = ressource.get('use_tls')
     bind_dn = ressource.get('bind_dn')
     bind_pw = ressource.get('bind_pw')
     if use_tls:
         conn.start_tls_s()
     if bind_dn:
         conn.simple_bind_s(bind_dn, bind_pw)
     attribute_mapping = utils.lower_keys(ressource['attribute_mapping'])
     static_attributes = utils.lower_keys(ressource.get('static_attributes', {}))
     format_mapping = utils.lower_keys(ressource.get('format_mapping', {}))
     attributes = set(attribute_mapping.keys()) | set(static_attributes.keys())
     default_ctx = ressource.get('attribute_context', {})
     ldap_filter = ressource.get('ldap_filter', '(objectclass=*)')
     delete = ressource.get('delete', True)
     User = compat.get_user_model()
     qs = User.objects.filter(**ressource.get('a2_filter', {}))
     todelete = set()
     user_dns = set()
     for batch in utils.batch(qs, options['batch_size']):
         ldap_users = {}
         filters = []
         for user in batch:
             ctx = default_ctx.copy()
             ctx['user'] = user
             ctx = get_attributes(ctx)
             ldap_attributes = {}
             for ldap_attribute, a2_attributes in attribute_mapping.iteritems():
                 if not isinstance(a2_attributes, (tuple, list)):
                     a2_attributes = [a2_attributes]
                 for a2_attribute in a2_attributes:
                     self.add_values(ldap_attributes, ldap_attribute, ctx.get(a2_attribute))
             for ldap_attribute, values in static_attributes.iteritems():
                 self.add_values(ldap_attributes, ldap_attribute, values)
             for ldap_attribute, fmt_tpls in format_mapping.iteritems():
                 for fmt_tpl in fmt_tpls:
                     self.add_values(ldap_attributes, ldap_attribute,
                             [fmt_tpl.format(**ctx)])
             dn, filt = self.build_dn_and_filter(ressource, ldap_attributes)
             user_dns.add(dn)
             ldap_users[dn] = ldap_attributes
             filters.append(filt)
         batch_filter = ldap_filter
         if filters:
             batch_filter = self.format_filter(('&', (batch_filter, ('|',
                 filters))))
         existing_dn = set()
         for dn, entry in conn.paged_search_ext_s(base_dn,
                  ldap.SCOPE_SUBTREE,
                  batch_filter, list(attributes)):
             entry = utils.to_dict_of_set(utils.lower_keys(entry))
             if dn not in ldap_users:
                 todelete.add(dn)
                 continue
             if entry == utils.to_dict_of_set(ldap_users[dn]):
                 # no need to update, entry is already ok
                 del ldap_users[dn]
                 continue
             existing_dn.add(dn)
         for dn, ldap_attributes in ldap_users.iteritems():
             if dn in existing_dn:
                 modlist = []
                 for key, values in ldap_attributes:
                     modlist.append((ldap.MOD_REPLACE, key, values))
                 if not fake:
                     conn.modify(dn, modlist)
                 if verbosity > 1:
                     print '- Replace %s values for %s' % (dn, ', '.join(ldap_attributes.keys()))
             else:
                 if not fake:
                     conn.add(dn, ldap.modlist.addModlist(ldap_attributes))
                 if verbosity > 1:
                     print '- Add %s with values for %s' % (dn, ', '.join(ldap_attributes.keys()))
         # wait for results
         if not fake:
             for x in ldap_users:
                 conn.result()
     for dn, entry in conn.paged_search_ext_s(base_dn,
             ldap.SCOPE_SUBTREE, ldap_filter):
         # ignore the basedn
         if dn == base_dn:
             continue
         if dn not in user_dns and dn not in todelete:
             if not fake:
                 todelete.add(dn)
     if delete:
         if verbosity > 1:
             print '- Deleting:', ', '.join(todelete)
         if not fake:
             for dn in todelete:
                 conn.delete(dn)
             for dn in todelete:
                 conn.result()
Ejemplo n.º 46
0
from django import forms
from django.contrib.auth import models as auth_models

from authentic2.compat import get_user_model

auth_models.User.USER_PROFILE = ('first_name', 'last_name', 'email')
User = get_user_model()
all_field_names = [field.name for field in User._meta.fields]
field_names = getattr(User, 'USER_PROFILE', all_field_names)


class UserProfileForm(forms.ModelForm):
    error_css_class = 'form-field-error'
    required_css_class = 'form-field-required'

    def __init__(self, user=None, *args, **kwargs):
        self.user = user
        super(UserProfileForm, self).__init__(**kwargs)
        for field in get_user_model().REQUIRED_FIELDS:
            self.fields[field].required = True

    def save(self, commit=True):
        instance = super(UserProfileForm, self).save(commit=False)
        instance.user = self.user
        if commit:
            instance.save()
        return instance

    class Meta:
        model = User
        fields = [ field_name