コード例 #1
0
    def authenticate(self, username=None, password=None):
        if not password:
            return None

        username = username.lower()
        # works for username and [email protected]
        username = username.lower().split('@')[0]

        try:
            # initialise the LDAP manager
            l = LDAPManager()

            result_data = l.search(username,field="cn")
            # If the user does not exist in LDAP, Fail.
            if not result_data:
                return None
            # Attempt to bind to the user's DN.
            l.bind(result_data[0][0],password)
            # Success. The user existed and authenticated.
            # Get group
            group = None
            if result_data[0][1].get("carthageFacultyStatus"):
                if result_data[0][1]["carthageFacultyStatus"][0] == "A":
                    group = "carthageFacultyStatus"

            if result_data[0][1].get("carthageStaffStatus"):
                if result_data[0][1]["carthageStaffStatus"][0] == "A":
                    group = "carthageStaffStatus"

            if result_data[0][1].get("carthageStudentStatus"):
                if result_data[0][1]["carthageStudentStatus"][0] == "A":
                    group = "carthageStudentStatus"

            # Get the user record or create one with no privileges.
            try:
                user = User.objects.get(username__exact=username)
                if not user.last_name:
                    user.last_name = result_data[0][1]['sn'][0]
                    user.first_name = result_data[0][1]['givenName'][0]
                    user.save()
                try:
                    if group:
                        # add them to their group
                        # or 'except' if they already belong
                        g = Group.objects.get(name__iexact=group)
                        g.user_set.add(user)
                except:
                    return user
            except:
                # Create a User object.
                user = l.dj_create(
                    result_data, auth_user_pk=settings.LDAP_AUTH_USER_PK
                )

            # Success.
            return user

        except Exception, e:
            # Name or password were bad. Fail permanently.
            return None
コード例 #2
0
def main():
    """
    main method
    """

    # initialize the manager
    l = LDAPManager()
    """
    l = LDAPManager(
        protocol=settings.LDAP_PROTOCOL_PWM,
        server=settings.LDAP_SERVER_PWM,
        port=settings.LDAP_PORT_PWM,
        user=settings.LDAP_USER_PWM,
        password=settings.LDAP_PASS_PWM,
        base=settings.LDAP_BASE_PWM
    )
    """
    result = l.search(value,field=field)
    print result

    # authenticate
    if password:
        auth = l.bind(result[0][0],password)
        print auth
        # create a django user
        if create:
            user = l.dj_create(result[0][1]["cn"][0],result)
            print user
コード例 #3
0
def main():
    """
    main method
    """

    # initialize the manager
    l = LDAPManager()
    """
    l = LDAPManager(
        protocol=settings.LDAP_PROTOCOL_PWM,
        server=settings.LDAP_SERVER_PWM,
        port=settings.LDAP_PORT_PWM,
        user=settings.LDAP_USER_PWM,
        password=settings.LDAP_PASS_PWM,
        base=settings.LDAP_BASE_PWM
    )
    """
    result = l.search(value,field=field)

    if field == 'carthageDob':
        for r in result:
            p = "{cn[0]}|{carthageNameID[0]}|{sn[0]}|{givenName[0]}|{mail[0]}"
            print p.format(**r[1])
    else:
        print result

    # authenticate
    if password:
        auth = l.bind(result[0][0],password)
        print auth
        # create a django user
        if create:
            user = l.dj_create(result[0][1]['cn'][0],result)
            print user
コード例 #4
0
    def authenticate(self, username=None, password=None, request=None):
        if not password:
            return None
        username = username.lower()

        l = LDAPManager()
        '''
        l = LDAPManager(
            protocol=settings.LDAP_PROTOCOL_PWM,
            server=settings.LDAP_SERVER_PWM,
            port=settings.LDAP_PORT_PWM,
            user=settings.LDAP_USER_PWM,
            password=settings.LDAP_PASS_PWM,
            base=settings.LDAP_BASE_PWM
        )
        '''

        try:
            result_data = l.search(username,field='cn')
            # If the user does not exist in LDAP, Fail.
            if not result_data and request:
                request.session['ldap_account'] = False
                return None

            # Attempt to bind to the user's DN.
            l.bind(result_data[0][0],password)
            # Success. The user existed and authenticated.
            # Get the user record or create one with no privileges.
            try:
                user = User.objects.get(username__exact=username)
            except:
                # Create a User object.
                user = l.dj_create(result_data)

            # TODO: update the alumni container
            return user
        except ldap.INVALID_CREDENTIALS:
            # Name or password were bad. Fail permanently.
            if request:
                request.session['ldap_cn'] = username
                request.session['ldap_account'] = True
                request.session['ldap_questions'] = self.get_questions(username)
            return None
コード例 #5
0
def modify_ldap_password(request):
    """
    Modifies the password for an LDAP account.
    Requires POST.
    """
    errors = {}
    if request.method == 'POST':
        form = ModifyLdapPasswordForm(request.POST)
        if form.is_valid():
            data = form.cleaned_data
            where = 'WHERE'
            where+= ' ( lower(id_rec.lastname) = "{}" )'.format(
                data['sn'].lower()
            )
            where+= ' AND'
            where+= '''
                 (profile_rec.birth_date = "{}"
            '''.format(data['carthageDob'].strftime('%m/%d/%Y'))
            where+= ' OR profile_rec.birth_date is null)'
            where+= ' AND'
            where+= '''
                SUBSTRING(id_rec.ss_no FROM 8 FOR 4) = "{}"
            '''.format(data['ssn'])
            sql = CONFIRM_USER + where
            results = do_sql(sql, key=settings.INFORMIX_DEBUG)
            try:
                objects = results.fetchall()
            except:
                objects = ''
            if len(objects) == 1:
                # initial the ldap manager
                # we have to use the PWM server here
                l = LDAPManager(
                    protocol=settings.LDAP_PROTOCOL_PWM,
                    server=settings.LDAP_SERVER_PWM,
                    port=settings.LDAP_PORT_PWM,
                    user=settings.LDAP_USER_PWM,
                    password=settings.LDAP_PASS_PWM,
                    base=settings.LDAP_BASE_PWM
                )
                search = l.search(objects[0].id)
                if search:
                    # now modify password
                    # modify_s() returns a tuple with status code
                    # and an empty list: (103, [])
                    try:
                        status = l.modify(
                            search[0][0], 'userPassword',
                            data['userPassword']
                        )
                        # success = 103
                        if status[0] == 103:
                            # success
                            request.session['ldap_password_success'] = True
                            # Get the user record or create one with no privileges.
                            try:
                                user = User.objects.get(
                                    username__exact=search[0][1]['cn'][0]
                                )
                            except:
                                # Create a User object.
                                user = l.dj_create(search)
                            # authenticate user
                            user.backend = 'django.contrib.auth.backends.ModelBackend'
                            login(request, user)
                            return HttpResponseRedirect(
                                reverse_lazy('alumni_directory_home')
                            )
                    except Exception as e:
                        # log it for later
                        ldap_logger.debug('ldap error: {}\n{}'.format(e,data))

                        if '16019' in str(e):
                            error = """
                                There was an error creating your account. Verify that
                                your password does not contain any English words like
                                the names of months, colors, etc.
                            """
                        else:
                            error = """
                                There was an error creating your account. Verify that
                                your passwords meet the criteria.
                            """

                        messages.add_message(
                            request, messages.ERROR, error, extra_tags='alert alert-danger'
                        )

                    else:
                        # fail
                        errors['ldap'] = "We failed to update your password."
                else:
                    errors['ldap'] = "We failed to find your Alumni account."
            else:
                errors['informix'] = "We could not find you in the database."
    else:
        form = ModifyLdapPasswordForm()

    return render(
        request,
        'registration/modify_ldap_password.html',
        {'form':form,'errors':errors}
    )
コード例 #6
0
def create_ldap(request):
    """
    Creates an LDAP account.
    Requires POST.
    After successful create, we update Informix with
    the LDAP username.
    """
    if request.method == 'POST':
        form = CreateLdapForm(request.POST)
        if form.is_valid():
            data = form.cleaned_data
            # dob format: YYYY-MM-DD
            data['carthageDob'] = data['carthageDob'].strftime('%Y-%m-%d')
            # username (cn) will be email address
            data['cn'] = data['mail']
            # remove confirmation password
            data.pop('confPassword',None)
            # python ldap wants strings, not unicode
            for k,v in data.items():
                data[k] = str(v)
            data['objectclass'] = settings.LDAP_OBJECT_CLASS_LIST
            data['carthageFacultyStatus'] = ''
            data['carthageStaffStatus'] = ''
            data['carthageStudentStatus'] = ''
            data['carthageFormerStudentStatus'] = 'A'
            data['carthageOtherStatus'] = ''

            # create the ldap user
            # we have to use the PWM server here
            l = LDAPManager(
                protocol=settings.LDAP_PROTOCOL_PWM,
                server=settings.LDAP_SERVER_PWM,
                port=settings.LDAP_PORT_PWM,
                user=settings.LDAP_USER_PWM,
                password=settings.LDAP_PASS_PWM,
                base=settings.LDAP_BASE_PWM
            )

            try:
                user = l.create(data)
                # set session ldap_cn, why?
                request.session['ldap_cn'] = user[0][1]['cn'][0]
                if not settings.DEBUG:
                    # update informix cvid_rec.ldap_user
                    sql = '''
                        UPDATE cvid_rec SET ldap_name='{}',
                        ldap_add_date = TODAY
                        WHERE cx_id = '{}'
                    '''.format(
                        user[0][1]['cn'][0], user[0][1]['carthageNameID'][0]
                    )
                    ln = do_sql(sql, key=settings.INFORMIX_DEBUG)
                # create the django user
                djuser = l.dj_create(user)
                data['djuser'] = djuser
                # authenticate user
                djuser.backend = 'django.contrib.auth.backends.ModelBackend'
                login(request, djuser)

                # send email to admins
                subject = "[LDAP][Create] {} {}".format(
                    user[0][1]['givenName'][0],
                    user[0][1]['sn'][0]
                )

                if settings.DEBUG:
                    to_list = [settings.SERVER_EMAIL]
                else:
                    to_list = settings.LDAP_CREATE_TO_LIST

                send_mail(
                    request,to_list, subject, data['mail'],
                    'registration/create_ldap_email.html', data
                )
                return HttpResponseRedirect(
                    reverse_lazy('alumni_directory_home')
                )
            except Exception as e:

                # log it for later
                ldap_logger.debug('ldap error: {}\n{}'.format(e,data))

                if '16019' in str(e):
                    error = """
                        There was an error creating your account. Verify that
                        your password does not contain any English words like
                        the names of months, colors, etc.
                    """
                else:
                    error = """
                        There was an error creating your account. Verify that
                        your passwords meet the criteria.
                    """

                messages.add_message(
                    request, messages.ERROR, error, extra_tags='alert alert-danger'
                )

                return render(
                    request,
                    'registration/create_ldap.html', {'form':form,}
                )

        else:
            return render(
                request,
                'registration/create_ldap.html', {'form':form,}
            )
    elif settings.DEBUG:
        form = CreateLdapForm(initial={'carthageNameID':'901257',})
        return render(
            request,
            'registration/create_ldap.html', {'form':form,}
        )
    else:
        # POST required
        return HttpResponseRedirect(reverse_lazy('registration_search'))