def main():
    """
    main method
    """

    # initialize the manager
    l = LDAPManager()

    # If there is only one value in the attribute value list,
    # the value can be just a string – it need not be a list.
    # Example: ('ou', 'user') is an acceptable alternative to
    # ('ou', ['user']).

    person = {
        "objectclass":settings.LDAP_OJBECT_CLASS,
        "givenName":givenName,"sn":sn,"cn":cn,"loginDisabled":"false",
        "carthageDob":carthageDob,"carthageNameID":carthageNameID,
        "mail":mail,"userPassword":userPassword
    }

    if group.lower()=="faculty":
        person["carthageFacultyStatus"] = "A"
    elif group.lower()=="staff":
        person["carthageStaffStatus"] = "A"
    elif group.lower()=="student":
        person["carthageStudentStatus"] = "A"
    elif group.lower()=="alumni":
        person["carthageFormerStudentStatus"] = "A"
    else:
        person["carthageOtherStatus"] = "A"

    print cn
    print person
    user = l.create(person)
    print user
def main():
    """
    main method
    """

    # initialize the manager
    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
    )

    if cid:
        field = settings.LDAP_ID_ATTR
        value = cid
    if username:
        field = "cn"
        value = username

    result = l.search(value,field=field,ret=settings.LDAP_RETURN_PWM)

    try:
        question = result[0][1][settings.LDAP_CHALLENGE_ATTR][0]
    except:
        question = None

    print question
Esempio n. 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)
    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
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
    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
Esempio n. 6
0
def search_ldap(request):
    """
    Search the LDAP store for an alumna's record.
    POST required, which is sent via Ajax request.
    If we find a record, we check Informix to see
    if we have their LDAP username stored, and
    update it if not. Lastly, display login form.
    If no record, allow the user to create one.
    """
    if request.method == 'POST':
        form = RegistrationSearchForm(request.POST)
        if form.is_valid():
            # data dictionary
            data = form.cleaned_data
            # search ldap
            # we use the regular ldap server here
            l = LDAPManager()
            user = l.search(data['alumna'])
            if user:
                # we have a user
                user = user[0][1]
                # update informix if no ldap_user
                if not settings.DEBUG and data['ldap_name'] == '':
                    sql = '''
                        UPDATE cvid_rec SET ldap_name='{}',
                        ldap_add_date = TODAY
                        WHERE cx_id = '{}'
                    '''.format(user['cn'][0], data['alumna'])
                    results = do_sql(sql, key=settings.INFORMIX_DEBUG)
                # check for challenge questions
                l = LDAPBackend()
                request.session['ldap_questions'] = l.get_questions(
                    user['cn'][0]
                )
                # display the login form
                form = {'data':{'username':user['cn'][0],}}
                redir = reverse_lazy('alumni_directory_home')
                extra_context = {
                    'user':user,'form':form,
                    'next':redir,'action':settings.LOGIN_URL
                }
                template = 'login'
            else:
                # display the create form
                data['carthageNameID'] = data['alumna']
                request.session['ldap_name'] = data.get('ldap_name')
                form = CreateLdapForm(initial=data)
                action = reverse_lazy('registration_create_ldap')
                extra_context = {'action':action,'form':form,}
                template = 'create'
            return render(
                request,
                'registration/{}_ldap.inc.html'.format(template),
                extra_context
            )
    else:
        # POST required
        # or doing something nefarious
        return HttpResponseRedirect(reverse_lazy('registration_search'))
def main():
    """
    main method
    """


    # initialize the manager
    l = LDAPManager()
    result = l.search(cid, field='carthageNameID')
    print result[0][1]
    destroy = l.delete(result[0][1])
Esempio n. 8
0
 def clean_mail(self):
     cleaned_data = self.cleaned_data
     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
     )
     user = l.search(cleaned_data.get('mail'),field='cn')
     if user:
         raise forms.ValidationError(
             "That email already exists in the system. Use another."
         )
     return cleaned_data['mail']
def main():
    """
    main method
    """

    global cn
    global name
    global value

    print "cn = {}".format(cn)
    print "name = {}".format(name)
    print "value = {}".format(value)

    # encrypt the password
    if name == "userPassword":
        value = hash(value)

    # initialize the manager
    if name == "userPassword":
        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
        )
    else:
        l = LDAPManager()
    # use search to obtain dn
    search = l.search(cn,field="cn")
    print search
    dn = search[0][0]
    print "dn = {}".format(dn)
    #result = l.modify(dn, name, value)
    old = {
        "dn":search[0][0],
        "cn":search[0][1]["cn"],
        "mail":search[0][1]["mail"],
        "carthageNameID":search[0][1]["carthageNameID"],
        "sn":search[0][1]["sn"],
        "carthageFormerStudentStatus":search[0][1]["carthageFormerStudentStatus"],
        "givenName":search[0][1]["givenName"],
        "carthageDob":search[0][1]["carthageDob"]
    }
    new = old
    new[name] = value
Esempio n. 10
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
def main():
    """
    main method
    """

    # initialize the manager
    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,
        #password=settings.LDAP_PASS,
        base=settings.LDAP_BASE_PWM
    )
    #l = LDAPManager()
    print "dn = %s " % dn
    print "password = %s" % password
    status = l.update_password( dn, password )
    print status
Esempio n. 12
0
    def get_questions(self, cn=None):
        """
        check to see whether or not the user has her
        challenge question & answers set.
        not the best place for this, but for now it will do.
        """
        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(cn,field='cn',ret=settings.LDAP_RETURN_PWM)

        try:
            questions = result[0][1][settings.LDAP_CHALLENGE_ATTR][0]
            return True
        except:
            return False
def main():
    """
    Find all students who have staff attribute in LDAP
    """

    NOW  = datetime.datetime.now()
    term = get_term()
    sql = ''' {}
        AND stu_serv_rec.yr = "{}"
        AND stu_serv_rec.sess = "{}"
        AND prog_enr_rec.cl IN {}
    '''.format(
        STUDENTS_ALPHA, term["yr"], term["sess"],
        ('FN','FF','FR','SO','JR','SR','GD','UT')
    )
    #print "djsani sql = {}".format(sql)
    #print "djkotter sql = {}".format(STUDENTS_ALL)
    #objs = do_esql(sql)
    objs = do_esql(STUDENTS_ALL)

    # initialize the LDAP manager
    l = LDAPManager()
    print NOW
    for o in objs:
        print "{}, {} ({})".format(o.lastname, o.firstname, o[2])
        result = l.search(o.id,field=settings.LDAP_ID_ATTR)
        staff = result[0][1].get('carthageStaffStatus')

        if staff:
            staff = staff[0]
            username = result[0][1]['cn'][0]
            email = result[0][1].get('mail')
            if email:
                email = email[0]
            print "username = {} | id {} | email = {} | staff = {}".format(
                username, o.id, email, staff
            )
    print NOW
Esempio n. 14
0
def proposal_approver(request, pid=0):
    '''
    Add an approver to a proposal.
    OJO: we still need to validate that a Dean  can add an approver
    to the proposal but we can trust deans for now.
    '''

    user = request.user
    group = in_group(user, OSP_GROUP, DEANS_GROUP)
    if not group:
        return HttpResponseRedirect(
            reverse_lazy('home')
        )
    else:
        proposal = None
        proposal = get_object_or_404(Proposal, id=pid)
        if request.method=='POST':
            form = ProposalApproverForm(request.POST, user=user)
            if form.is_valid():
                cd = form.cleaned_data
                cid = cd['user']
                try:
                    user = User.objects.get(id=cid)
                except:
                    # create a new user
                    l = LDAPManager()
                    luser = l.search(cid)
                    data = luser[0][1]
                    password = User.objects.make_random_password(length=24)
                    user = User.objects.create(
                        pk=cid, username=data['cn'][0],
                        email=data['mail'][0], last_login=NOW
                    )
                    user.set_password(password)
                    user.first_name = data['givenName'][0]
                    user.last_name = data['sn'][0]
                    user.save()

                approver = ProposalApprover(
                    user=user, proposal=proposal
                )

                where = 'PT.pcn_03 = "{}"'.format(proposal.department)
                chairs = department_division_chairs(where)
                # in the future, users might be able to select the role
                # that an approver might replace but for now we handle it
                # here and by default in the model, which is 'level3',
                # and if a dean is adding an approver there is no replace
                if len(chairs) > 0:
                    approver.replace = None
                approver.save()

                # send an email to approver
                prefix = 'Your Review and Authorization Required'
                subject = u'{}: "{}" by {}, {}'.format(
                    prefix, proposal.title,
                    proposal.user.last_name, proposal.user.first_name
                )

                if DEBUG:
                    to_list = [MANAGER]
                    proposal.to_list = [
                        proposal.user.email, approver.user.email
                    ]
                else:
                    to_list = [approver.user.email]

                send_mail(
                    request, to_list, subject, PROPOSAL_EMAIL_LIST[0],
                    'approver/email.html', {'proposal':proposal,}, BCC
                )

                return HttpResponseRedirect(
                    reverse_lazy('proposal_approver_success')
                )

        else:
            form = ProposalApproverForm(initial={'proposal': pid}, user=user)

    template = 'approver/form.html'
    context = {'proposal':proposal, 'form':form}

    return render(
        request, template, context
    )
Esempio n. 15
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}
    )
Esempio n. 16
0
        def wrapper(request, *args, **kwargs):
            resolved_redirect_url = force_str(
                resolve_url(redirect_url or reverse_lazy("auth_login"))
            )
            if not request.session.get(session_var):
                if not request.user.is_authenticated:
                    # we want to redirect back to current view URL
                    refer = request.get_full_path()
                    redirect = '{}?next={}'.format(
                        reverse_lazy("auth_login"), refer
                    )
                    # UserID value from the portal
                    guid = request.GET.get('uid')
                    if guid:
                        if encryption:
                            test = 1
                            guid = decrypt(guid)
                        uid = get_userid(guid)
                        if uid:
                            uid = int(uid)
                            try:
                                user = User.objects.get(pk=uid)
                            except:
                                try:
                                    # create a new django user
                                    l = LDAPManager()
                                    luser = l.search(uid)
                                    data = luser[0][1]
                                    password = User.objects.make_random_password(
                                        length=32
                                    )
                                    user = User.objects.create(
                                        pk=uid, username=data['cn'][0],
                                        email=data['mail'][0], last_login=NOW
                                    )
                                    user.set_password(password)
                                    user.first_name = data['givenName'][0]
                                    user.last_name = data['sn'][0]
                                    user.save()
                                    # add to groups
                                    try:
                                        for key, val in settings.LDAP_GROUPS.items():
                                            grp = data.get(key)
                                            if grp and grp[0] == 'A':
                                                g = Group.objects.get(name__iexact=key)
                                                g.user_set.add(user)
                                    except:
                                        pass
                                except:
                                    return HttpResponseRedirect(redirect)
                        else:
                            # we could not find a user from portal's UID
                            return HttpResponseRedirect(redirect)
                    else:
                        return HttpResponseRedirect(redirect)
                else:
                    user = request.user
                if group:
                    if not in_group(user, group) and not user.is_superuser:
                        return HttpResponseRedirect(resolved_redirect_url)
                # sign in the user manually
                user.backend = 'django.contrib.auth.backends.ModelBackend'
                login(request, user)
                request.session[session_var] = True

            return view_func(request, *args, **kwargs)
Esempio n. 17
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'))
Esempio n. 18
0
import django
django.setup()

from django.conf import settings
from django.contrib.auth.models import User, Group

from djauth.LDAPManager import LDAPManager

username = ""
password = ""

# initialise the LDAP manager
l = LDAPManager()

result_data = l.search(username,field="cn")

if not result_data:
    print result_data
    print "fail"
else:
    print result_data
    print "\n\n"
    print "dn = %s" % result_data[0][0]
    print "\n\n"
    print "Attempt to bind to the user's DN."
    print "\n\n"
    l.bind(result_data[0][0],password)

# Get group
group = None
if result_data[0][1].get("carthageFacultyStatus"):