コード例 #1
0
def ajax_ldap_pop_name_mail(request, cn):
    try:

        lists = dict()

        # Get user
        auth = AuthSession(request.session)
        ldap_user = Ldap(auth).get_user(cn)
        lists['ldap_name'] = '%s %s %s' % (ldap_user['givenName'],
            ldap_user.get('initials', ''), ldap_user['sn'])
        lists['ldap_email'] = ldap_user['mail']
        lists['error'] = ' '

        response = HttpResponse(loader.render_to_string(
            AJAX_LDAP_USER_POP_NAME_MAIL, lists, context_instance=RequestContext(request)))
        #render_to_response_ajax(AJAX_LDAP_USER_POP_NAME_MAIL, lists, context_instance=RequestContext(request))
        response.status_code = 200
        return response

    except LDAPError, e:
        logger.error("LDAP Error on ajax_ldap_pop_name_mail %s" % e)
        lists['ldap_name'] = ' '
        lists['ldap_email'] = ' '
        lists[
            'error'] = 'O LDAP não está disponível, não será possível associar o usuário CadVlan a um usuário do LDAP.'
コード例 #2
0
def add_group_form(request):

    try:

        lists = dict()
        ldap = Ldap(AuthSession(request.session).get_user().get_username())

        users_list = get_users(ldap)

        if request.method == "POST":

            form = GroupForm(users_list, request.POST)

            if form.is_valid():
                cn = str(form.cleaned_data['cn'])
                gidNumber = str(form.cleaned_data['gidNumber'])
                member_uid = form.cleaned_data['member_uid']

                if valid_form_group(ldap, request, cn, gidNumber):

                    ldap.add_group(cn, gidNumber, member_uid)

                    messages.add_message(
                        request, messages.SUCCESS, ldap_messages.get("success_insert_group"))

                    return redirect('ldap.group.list')

        else:

            form = GroupForm(
                users_list, initial={'gidNumber': gidNumber_suggest(ldap)})

    except LDAPError, e:
        logger.error(e)
        messages.add_message(request, messages.ERROR, e)
コード例 #3
0
def delete_sudoer_all(request):

    if request.method == 'POST':

        ldap = Ldap(AuthSession(request.session).get_user().get_username())
        form = DeleteForm(request.POST)

        if form.is_valid():

            # All cns to be deleted
            cns = split_to_array(form.cleaned_data['ids'])

            # All messages to display
            error_list = list()

            # Control others exceptions
            have_errors = False

            # For each sudoer selected to remove
            for cn in cns:

                try:

                    ldap.rem_sudoer(cn)

                except LDAPNotFoundError, e:
                    error_list.append(cn)
                    have_errors = True

                except LDAPError, e:
                    logger.error(e)
                    messages.add_message(request, messages.ERROR, e)
                    have_errors = True
                    break

            # If cant remove nothing
            if len(error_list) == len(cns):
                messages.add_message(
                    request, messages.ERROR, error_messages.get("can_not_remove_all"))

            # If cant remove someones
            elif len(error_list) > 0:
                msg = ""
                for id_error in error_list:
                    msg = msg + id_error + ", "

                msg = error_messages.get("can_not_remove") % msg[:-2]

                messages.add_message(request, messages.WARNING, msg)

            # If all has ben removed
            elif have_errors == False:
                messages.add_message(
                    request, messages.SUCCESS, ldap_messages.get("success_remove_sudoer"))

            else:
                messages.add_message(
                    request, messages.SUCCESS, error_messages.get("can_not_remove_error"))
コード例 #4
0
    def clean(self):
        cleaned_data = self.cleaned_data
        gidNumber = cleaned_data.get("gidNumber")

        if gidNumber is not None:

            ldap = Ldap(None)

            if not ldap.valid_range_group(gidNumber):
                self._errors["gidNumber"] = self.error_class([ldap_messages.get(
                    "error_range_out_group") % (ldap.rangeGroups[0], ldap.rangeGroups[-1])])

        return cleaned_data
コード例 #5
0
def add_user_form(request, pattern):

    try:

        lists = dict()
        ldap = Ldap(AuthSession(request.session).get_user().get_username())

        group_list = get_groups(ldap)
        policy_list = get_policies(ldap)

        if pattern == PATTERN_TYPES.INTERNAL:
            groupPattern = ldap.groupStandard
            usertype_list = CHOICES_GROUP
            loginShell = "/bin/bash"

        elif pattern == PATTERN_TYPES.EXTERNAL:
            groupPattern = ldap.groupStandardExternal
            usertype_list = None
            loginShell = "/sbin/nologin"

        if request.method == "POST":

            form = UserForm(group_list, policy_list, usertype_list, request.POST, initial={
                            'groupPattern': groupPattern})

            if form.is_valid():

                data = form.cleaned_data

                for e in data.keys():
                    if type(data[e]) == unicode or type(data[e]) == int:
                        data[e] = str(data[e])

                if valid_form_user(ldap, request, data['cn'], data['uidNumber'], data['employeeNumber'], data['mail']):

                    ldap.add_user(data['cn'], data['uidNumber'], data['groupPattern'], data['homeDirectory'], data['givenName'], data['initials'], data['sn'], data['mail'], data['homePhone'], data['mobile'], data['street'], data[
                                  'description'], data['employeeNumber'], data['employeeType'], data['loginShell'], data['shadowLastChange'], data['shadowMin'], data['shadowMax'], data['shadowWarning'], data['policy'], data['groups'])

                    messages.add_message(
                        request, messages.SUCCESS, ldap_messages.get("success_insert_user"))

                    return HttpResponseRedirect(reverse('ldap.user.list', args=[pattern]))

        else:

            form = UserForm(group_list, policy_list, usertype_list, initial={'uidNumber': uidNumber_suggest(
                ldap, pattern), 'groupPattern': groupPattern, 'shadowMin': 1, 'shadowMax': 365, 'shadowWarning': 335, 'shadowLastChange': 1, 'loginShell': loginShell})

    except LDAPError, e:
        logger.error(e)
        messages.add_message(request, messages.ERROR, e)
コード例 #6
0
def ajax_reset_password_user(request):

    lists = dict()
    ldap = Ldap(AuthSession(request.session).get_user().get_username())
    status_code = 500

    try:
        cn = request.GET['cn']
        ldap.reset_pwd(cn)
        lists["password"] = LDAP_PASSWORD_DEFAULT
        status_code = 200

    except LDAPNotFoundError, e:
        messages.add_message(
            request, messages.ERROR, ldap_messages.get("invalid_user") % cn)
コード例 #7
0
def ajax_unlock_user(request):

    ldap = Ldap(AuthSession(request.session).get_user().get_username())
    status_code = 500

    try:
        cn = request.GET['cn']
        ldap.unlock_user(cn)
        status_code = 200
        messages.add_message(
            request, messages.SUCCESS, ldap_messages.get("success_unlock_user") % cn)

    except LDAPNotFoundError, e:
        messages.add_message(
            request, messages.ERROR, ldap_messages.get("invalid_user") % cn)
コード例 #8
0
    def clean(self):
        cleaned_data = self.cleaned_data
        gidNumber = cleaned_data.get("gidNumber")

        if gidNumber is not None:

            ldap = Ldap(None)

            if not ldap.valid_range_group(gidNumber):
                self._errors["gidNumber"] = self.error_class([
                    ldap_messages.get("error_range_out_group") %
                    (ldap.rangeGroups[0], ldap.rangeGroups[-1])
                ])

        return cleaned_data
コード例 #9
0
def create_form_user(id_user, auth, groups, edit, ldap_grps=None):

    if edit:
        user = auth.get_clientFactory().create_usuario().get_by_id(
            id_user).get('usuario')

        if type(user['grupos']) == unicode:
            user['grupos'] = list([user['grupos'], 'one_group'])
        # Get LDAP user and the first group associated
        is_ldap = False
        usr_list = None
        ini_grp = None
        if user['user_ldap'] is not None:
            ldap = Ldap(auth)
            ldap_user_ = ldap.get_user(user['user_ldap'])

            users_grps = ldap.get_groups_user(ldap_user_['cn'])

            ldap_ini_grps = [grp[1] for grp in ldap_grps]
            for grp in users_grps:
                if grp in ldap_ini_grps:
                    ini_grp = ldap_grps[ldap_ini_grps.index(grp)][0]
                    usr_list = ldap.get_users_group(ini_grp)
                    is_ldap = True
                    break

        form_user = UserForm(groups,
                             ldap_group_list=ldap_grps,
                             ldap_user_list=usr_list,
                             initial={
                                 "name": user['nome'],
                                 "email": user['email'],
                                 "user": user['user'],
                                 "groups": user['grupos'],
                                 "password": user['pwd'],
                                 "active": user['ativo'],
                                 "is_ldap": is_ldap,
                                 "ldap_group": ini_grp,
                                 "ldap_user": user['user_ldap']
                             })
        #action = "user.edit %s 1" % (str(id_user))
        action = url("user.edit", id_user, 1)
    else:
        #action = "user.edit 0 0"
        action = url("user.edit", 0, 0)
        form_user = UserForm(groups, ldap_grps)

    return form_user, action
コード例 #10
0
def ajax_ldap_users_by_group(request, ldap_group, id_user):
    try:

        lists = dict()

        # Get user
        auth = AuthSession(request.session)
        client = auth.get_clientFactory()

        exclude_list = []
        user_list = client.create_usuario().listar().get('usuario')
        for usr in user_list:
            if usr['user_ldap'] is not None and usr['user_ldap'] != '' and usr['id'] != id_user:
                exclude_list.append(usr['user_ldap'])

        ldap_users = Ldap(auth).get_users_group(ldap_group, exclude_list)
        lists['ldap_users'] = ldap_users

        # Returns HTML
        response = HttpResponse(loader.render_to_string(
            AJAX_LDAP_USERS_BY_GROUP, lists, context_instance=RequestContext(request)))
        response.status_code = 200
        return response

    except LDAPError:
        lists[
            'error'] = 'O LDAP não está disponível, não será possível associar o usuário CadVlan a um usuário do LDAP.'

    # Returns HTML
    response = HttpResponse(loader.render_to_string(
        AJAX_LDAP_USERS_BY_GROUP, lists, context_instance=RequestContext(request)))
    # Send response status with error
    response.status_code = 278
    return response
コード例 #11
0
def edit_sudoer_form(request, cn):
    try:

        lists = dict()
        lists["edit"] = True
        lists["action"] = reverse("ldap.sudoer.edit", args=[cn])

        ldap = Ldap(AuthSession(request.session).get_user().get_username())
        groups_list = get_groups(ldap)

        if request.method == "POST":

            commands_list = request.POST.getlist(
                'commands') if "commands" in request.POST else []

            form = SudoerForm(groups_list, commands_list, request.POST)

            if form.is_valid():
                cn = str(form.cleaned_data['cn'])
                sudoHost = str(form.cleaned_data['host'])
                sudoUser = form.cleaned_data['groups']
                sudoCommand = form.cleaned_data['commands']

                ldap.edit_sudoer(cn, sudoHost, sudoUser, sudoCommand)

                messages.add_message(
                    request, messages.SUCCESS, ldap_messages.get("success_edit_sudoer"))
                return redirect('ldap.sudoer.list')
        else:

            sudoer = ldap.get_sudoer(cn)

            groups = []
            for grp in validates_dict(sudoer, ("sudoUser")):
                groups.append(str(grp).replace("%", ""))

            form = SudoerForm(groups_list, validates_dict(sudoer, ("sudoCommand")), initial={'cn': sudoer.get(
                "cn"), 'host': sudoer.get("sudoHost"), 'groups': groups, 'commands': validates_dict(sudoer, ("sudoCommand"))})

    except LDAPNotFoundError, e:
        messages.add_message(
            request, messages.ERROR, ldap_messages.get("invalid_sudoer") % cn)
        return redirect('ldap.sudoer.form')
コード例 #12
0
    def clean(self):
        cleaned_data = self.cleaned_data

        userType = cleaned_data.get("userType")
        homeDirectory = cleaned_data.get("homeDirectory")
        uidNumber = cleaned_data.get("uidNumber")
        groupPattern = cleaned_data.get("groupPattern")

        if groupPattern is not None:

            if str(groupPattern) == str(CHOICES_GROUP[0][0]):

                if homeDirectory is None or homeDirectory == "":
                    self._errors["homeDirectory"] = self.error_class(
                        [error_messages.get("required")])

                if userType is None or userType == "":
                    self._errors["userType"] = self.error_class(
                        [error_messages.get("required")])

            if uidNumber is not None:

                ldap = Ldap(None)

                if groupPattern == ldap.groupStandard:

                    if not ldap.valid_range_user_internal(uidNumber):
                        self._errors["uidNumber"] = self.error_class([
                            ldap_messages.get("error_range_out_user") %
                            (ldap.rangeUsers[0], ldap.rangeUsers[-1])
                        ])

                else:

                    if not ldap.valid_range_user_external(uidNumber):
                        self._errors["uidNumber"] = self.error_class([
                            ldap_messages.get("error_range_out_user") %
                            (ldap.rangeUsersExternal[0],
                             ldap.rangeUsersExternal[-1])
                        ])

        return cleaned_data
コード例 #13
0
def add_sudoer_form(request):
    try:

        lists = dict()
        ldap = Ldap(AuthSession(request.session).get_user().get_username())

        groups_list = get_groups(ldap)

        if request.method == "POST":

            commands_list = request.POST.getlist(
                'commands') if "commands" in request.POST else []

            form = SudoerForm(groups_list, commands_list, request.POST)

            if form.is_valid():
                cn = str(form.cleaned_data['cn'])
                sudoHost = str(form.cleaned_data['host'])
                sudoUser = form.cleaned_data['groups']
                sudoCommand = form.cleaned_data['commands']

                try:
                    # Valid cn
                    sudoer = None
                    sudoer = ldap.get_sudoer(cn)
                except LDAPError, e:
                    pass

                if sudoer is None:

                    ldap.add_sudoer(cn, sudoHost, sudoUser, sudoCommand)

                    messages.add_message(
                        request, messages.SUCCESS, ldap_messages.get("success_insert_sudoer"))
                    return redirect('ldap.sudoer.list')

                else:
                    messages.add_message(request, messages.WARNING, ldap_messages.get(
                        "error_duplicated_name_sudoer") % cn)

        else:
コード例 #14
0
def list_all_sudoer(request):
    try:

        lists = dict()
        ldap = Ldap(AuthSession(request.session).get_user().get_username())

        lists['sudoers'] = get_sudoers(ldap)
        lists['form'] = DeleteForm()

    except LDAPError, e:
        logger.error(e)
        messages.add_message(request, messages.ERROR, e)
コード例 #15
0
    def clean(self):
        cleaned_data = self.cleaned_data

        userType = cleaned_data.get("userType")
        homeDirectory = cleaned_data.get("homeDirectory")
        uidNumber = cleaned_data.get("uidNumber")
        groupPattern = cleaned_data.get("groupPattern")

        if groupPattern is not None:

            if str(groupPattern) == str(CHOICES_GROUP[0][0]):

                if homeDirectory is None or homeDirectory == "":
                    self._errors["homeDirectory"] = self.error_class(
                        [error_messages.get("required")])

                if userType is None or userType == "":
                    self._errors["userType"] = self.error_class(
                        [error_messages.get("required")])

            if uidNumber is not None:

                ldap = Ldap(None)

                if groupPattern == ldap.groupStandard:

                    if not ldap.valid_range_user_internal(uidNumber):
                        self._errors["uidNumber"] = self.error_class([ldap_messages.get(
                            "error_range_out_user") % (ldap.rangeUsers[0], ldap.rangeUsers[-1])])

                else:

                    if not ldap.valid_range_user_external(uidNumber):
                        self._errors["uidNumber"] = self.error_class([ldap_messages.get(
                            "error_range_out_user") % (ldap.rangeUsersExternal[0], ldap.rangeUsersExternal[-1])])

        return cleaned_data
コード例 #16
0
def edit_group_form(request, cn):
    try:

        lists = dict()
        lists["edit"] = True
        lists["action"] = reverse("ldap.group.edit", args=[cn])

        ldap = Ldap(AuthSession(request.session).get_user().get_username())

        users_list = get_users(ldap)

        form = GroupForm(users_list)

        if request.method == "POST":

            form = GroupForm(users_list, request.POST)

            if form.is_valid():
                cn = str(form.cleaned_data['cn'])
                gidNumber = str(form.cleaned_data['gidNumber'])
                member_uid = form.cleaned_data['member_uid']

                ldap.edit_group(cn, gidNumber, member_uid)

                messages.add_message(
                    request, messages.SUCCESS, ldap_messages.get("success_edit_group"))
                return redirect('ldap.group.list')

        else:
            group = ldap.get_group(cn)
            form = GroupForm(users_list, initial={'cn': group.get("cn"), 'gidNumber': group.get(
                "gidNumber"), 'member_uid': validates_dict(group, ("memberUid"))})

    except LDAPNotFoundError, e:
        messages.add_message(
            request, messages.ERROR, ldap_messages.get("invalid_group") % cn)
        return redirect('ldap.group.form')
コード例 #17
0
def create_form_user(id_user, auth, groups, edit, ldap_grps=None):

    if edit:
        user = auth.get_clientFactory().create_usuario().get_by_id(
            id_user).get('usuario')

        if type(user['grupos']) == unicode:
            user['grupos'] = list([user['grupos'], 'one_group'])
        # Get LDAP user and the first group associated
        is_ldap = False
        usr_list = None
        ini_grp = None
        if user['user_ldap'] is not None:
            ldap = Ldap(auth)
            ldap_user_ = ldap.get_user(user['user_ldap'])

            users_grps = ldap.get_groups_user(ldap_user_['cn'])

            ldap_ini_grps = [grp[1] for grp in ldap_grps]
            for grp in users_grps:
                if grp in ldap_ini_grps:
                    ini_grp = ldap_grps[ldap_ini_grps.index(grp)][0]
                    usr_list = ldap.get_users_group(ini_grp)
                    is_ldap = True
                    break

        form_user = UserForm(groups, ldap_group_list=ldap_grps, ldap_user_list=usr_list, initial={"name": user['nome'], "email": user['email'], "user": user[
                             'user'], "groups": user['grupos'], "password": user['pwd'], "active": user['ativo'], "is_ldap": is_ldap, "ldap_group": ini_grp, "ldap_user": user['user_ldap']})
        #action = "user.edit %s 1" % (str(id_user))
        action = url("user.edit", id_user, 1)
    else:
        #action = "user.edit 0 0"
        action = url("user.edit", 0, 0)
        form_user = UserForm(groups, ldap_grps)

    return form_user, action
コード例 #18
0
def list_all_user(request, pattern):
    try:

        lists = dict()
        ldap = Ldap(AuthSession(request.session).get_user().get_username())
        formSearch = UserSearchForm()

        if request.method == 'POST':

            formSearch = UserSearchForm(request.POST)

            if formSearch.is_valid():

                uidNumner = formSearch.cleaned_data['uidNumner']
                cn = formSearch.cleaned_data['cn']
                name = formSearch.cleaned_data['name']
                lock = formSearch.cleaned_data['lock']

                users = []
                for user in get_users_search(ldap, pattern, lock):

                    if uidNumner is not None:
                        if str(uidNumner) != user.get('uidNumber'):
                            continue

                    if cn is not None and cn != "":
                        if str(cn).upper() not in str(user.get('cn')).upper():
                            continue

                    if name is not None and name != "":
                        if str(name).upper() not in str(user.get('name')).upper():
                            continue

                    users.append(user)

                lists['users'] = users

        else:

            lists['users'] = get_users_search(ldap, pattern)

    except LDAPError, e:
        logger.error(e)
        messages.add_message(request, messages.ERROR, e)
コード例 #19
0
def generate_token(request):
    try:

        lists = {}

        form = forms.GenerateTokenForm(
            request.POST
        ) if request.method == 'POST' else forms.GenerateTokenForm()

        if form.is_valid():

            user_ldap_ass = ""
            user = str(form.cleaned_data['user'])
            idt = None if not form.cleaned_data[
                'requestVip'] else form.cleaned_data['requestVip']
            ttl = ACCESS_EXTERNAL_TTL if not form.cleaned_data[
                'p'] else form.cleaned_data['p']

            # Login with LDAP
            if form.cleaned_data['is_ldap_user']:
                username_ldap, password_ldap = str(user).split("@")
                try:
                    user_ldap = Ldap("").get_user(username_ldap)
                except LDAPNotFoundError, e:
                    raise Exception(auth_messages.get("user_ldap_not_found"))

                pwd_ldap = user_ldap['userPassword']
                activate = user_ldap.get('nsaccountlock')
                pwd = password_ldap

                if re.match("\{(MD|md)5\}.*", pwd_ldap, 0):
                    pwd = base64.b64encode(hashlib.md5(pwd).digest())
                    pwd_ldap = pwd_ldap[pwd_ldap.index("}") + 1:]

                if pwd == pwd_ldap and (activate is None
                                        or activate.upper() == 'FALSE'):
                    # Valid User
                    client, client_user = facade.validate_user_networkapi(
                        user, form.cleaned_data['is_ldap_user'])
                    user_ldap_client = client_user.get('user')
                    user_ldap_ass = user_ldap_client['user_ldap']
                else:
                    client_user = None
            else:
                # Valid User
                client, client_user = facade.validate_user_networkapi(
                    user, form.cleaned_data['is_ldap_user'])

            # Valid User
            if client_user is None:
                raise UserNotAuthenticatedError("user_invalid")
            else:
                # Valid idt
                if idt is not None and not is_valid_int_param(idt):
                    raise Exception(
                        error_messages.get("invalid_param") % "requestVip")

                # Valid ttl
                if not is_valid_int_param(ttl):
                    raise Exception(error_messages.get("invalid_param") % "p")

                if idt is not None:
                    client.create_vip().get_by_id(idt)

                # Encrypt hash
                user_hash = Encryption().Encrypt(user + "@" +
                                                 str(user_ldap_ass))

                # Get Authenticate User
                authenticate_user = client_user.get('user')

                # Get Permissions by Authenticate User
                permissions = authenticate_user and authenticate_user.get(
                    'permission')

                # Generates token
                key = "%s:%s:%s" % (__name__, str(user),
                                    str(strftime("%Y%m%d%H%M%S")))

                token = hashlib.sha1(key).hexdigest()

                data_to_cache = {
                    "user_hash": user_hash,
                    "permissions": permissions
                }

                # Set token in cache
                cache.set(token, data_to_cache, int(ttl))

                lists["token"] = token

                if idt is not None:
                    lists["url"] = reverse("vip-request.edit.external",
                                           args=[idt])
                else:
                    lists["url"] = reverse("vip-request.form.external")

            return render_to_response(templates.VIPREQUEST_TOKEN,
                                      lists,
                                      context_instance=RequestContext(request))

    except InvalidParameterError, e:
        logger.error(e)
        lists["error"] = error_messages.get("invalid_param") % "id"
コード例 #20
0
def list_all(request, id_user, status):

    lists = dict()
    edit = False if id_user == "0" else True
    lists['open_form'] = "True" if edit or status == "1" else "False"
    lists['edit'] = str(edit)
    lists['id_user'] = id_user
    lists['action_new_users'] = reverse("user.form", args=[0, 0])

    try:
        # Get user
        auth = AuthSession(request.session)
        client = auth.get_clientFactory()
        # Get all users from NetworkAPI

        try:
            ldap_groups_ = get_groups(Ldap(auth))
            ldap_groups = [(ldap_grp['gidNumber'], ldap_grp['cn'])
                           for ldap_grp in ldap_groups_]
            ldap_up = True
        except LDAPError:
            messages.add_message(request, messages.ERROR,
                                 user_messages.get("ldap_offline"))
            ldap_up = False
            ldap_groups_ = None
            ldap_groups = None

        lists['ldap_up'] = ldap_up

        groups = client.create_grupo_usuario().listar()
        lists['ldap_groups'] = ldap_groups_
        lists['form'] = DeleteForm()
        lists['form_user'], lists['action'] = create_form_user(
            id_user, auth, groups, edit, ldap_groups)

        if request.method == 'POST':

            try:
                ldap_grp = int(request.POST['ldap_group'])
            except:
                ldap_grp = 0

            if ldap_grp > 0 and ldap_up:
                list_users_ldap = Ldap(auth).get_users_group(ldap_grp)
            else:
                list_users_ldap = None

            form = UserForm(groups, ldap_groups, list_users_ldap, request.POST)
            lists['form_user'] = form

            if form.is_valid():

                if edit:

                    edit_user(form, client, id_user)
                    messages.add_message(request, messages.SUCCESS,
                                         user_messages.get("success_edit"))

                else:

                    save_user(form, client)
                    messages.add_message(request, messages.SUCCESS,
                                         user_messages.get("success_insert"))

                lists['form_user'], lists['action'] = create_form_user(
                    0, auth, groups, False, ldap_groups)
                lists['open_form'] = "False"

            else:
                lists['open_form'] = 'True'

        lists['users'] = list_user(client)

    except NetworkAPIClientError, e:
        logger.error(e)
        messages.add_message(request, messages.ERROR, e)
コード例 #21
0
def edit_user_form(request, pattern, cn):
    try:

        lists = dict()
        lists["pattern"] = pattern
        lists["action"] = reverse(
            "ldap.user.edit", kwargs={"pattern": pattern, "cn": cn})
        lists["edit"] = True

        ldap = Ldap(AuthSession(request.session).get_user().get_username())

        group_list = get_groups(ldap)
        policy_list = get_policies(ldap)

        if pattern == PATTERN_TYPES.INTERNAL:
            groupPattern = ldap.groupStandard
            usertype_list = CHOICES_GROUP

        elif pattern == PATTERN_TYPES.EXTERNAL:
            groupPattern = ldap.groupStandardExternal
            usertype_list = None

        if request.method == "POST":

            form = UserForm(group_list, policy_list, usertype_list, request.POST, initial={
                            'groupPattern': groupPattern})

            if form.is_valid():

                data = form.cleaned_data

                for e in data.keys():
                    if type(data[e]) == unicode or type(data[e]) == int:
                        data[e] = str(data[e])

                if valid_form_user(ldap, request, data['cn'], data['uidNumber'], data['employeeNumber'], data['mail'], edit=True):

                    ldap.edit_user(data['cn'], data['uidNumber'], data['groupPattern'], data['homeDirectory'], data['givenName'], data['initials'], data['sn'], data['mail'], data['homePhone'], data['mobile'], data['street'], data[
                                   'description'], data['employeeNumber'], data['employeeType'], data['loginShell'], data['shadowLastChange'], data['shadowMin'], data['shadowMax'], data['shadowWarning'], data['policy'], data['groups'])

                    client_user = AuthSession(
                        request.session).get_clientFactory().create_usuario()

                    try:
                        local_user = client_user.get_by_user_ldap(data['cn'])
                        local_user = local_user['usuario']
                        name = data['givenName'] + ' ' + \
                            data['initials'] + ' ' + data['sn']
                        client_user.alterar(local_user['id'], local_user['user'], local_user[
                                            'pwd'], name, local_user['ativo'], data['mail'], local_user['user_ldap'])
                    except UsuarioNaoExisteError:
                        pass

                    messages.add_message(
                        request, messages.SUCCESS, ldap_messages.get("success_edit_user"))
                    return HttpResponseRedirect(reverse('ldap.user.list', args=[pattern]))

        else:

            user = ldap.get_user(cn)
            user['groups'] = ldap.get_groups_user(cn)
            user['groupPattern'] = groupPattern

            form = UserForm(
                group_list, policy_list, usertype_list, initial=user)

    except LDAPNotFoundError, e:
        messages.add_message(
            request, messages.ERROR, ldap_messages.get("invalid_user") % cn)
        return HttpResponseRedirect(reverse('ldap.user.list', args=[pattern]))
コード例 #22
0
def delete_user_all(request, pattern):

    if request.method == 'POST':

        ldap = Ldap(AuthSession(request.session).get_user().get_username())
        form = DeleteForm(request.POST)

        if form.is_valid():

            # All cns to be deleted
            cns = split_to_array(form.cleaned_data['ids'])

            # All messages to display
            error_list = list()

            # Control others exceptions
            have_errors = False

            # For each user selected to remove
            for cn in cns:

                try:

                    ldap.rem_user(cn)

                    client_user = AuthSession(
                        request.session).get_clientFactory().create_usuario()

                    try:
                        local_user = client_user.get_by_user_ldap(cn)
                        local_user = local_user['usuario']
                        client_user.alterar(local_user['id'], local_user['user'], local_user[
                                            'pwd'], local_user['nome'], local_user['ativo'], local_user['email'], None)
                    except UsuarioNaoExisteError:
                        pass

                except LDAPMethodError, e:
                    error_list.append(cn)
                    have_errors = True

                except LDAPError, e:
                    logger.error(e)
                    messages.add_message(request, messages.ERROR, e)
                    have_errors = True
                    break

            # If cant remove nothing
            if len(error_list) == len(cns):
                messages.add_message(
                    request, messages.ERROR, error_messages.get("can_not_remove_all"))

            # If cant remove someones
            elif len(error_list) > 0:
                msg = ""
                for id_error in error_list:
                    msg = msg + id_error + ", "

                msg = error_messages.get("can_not_remove") % msg[:-2]

                messages.add_message(request, messages.WARNING, msg)

            # If all has ben removed
            elif have_errors == False:
                messages.add_message(
                    request, messages.SUCCESS, ldap_messages.get("success_remove_user"))

            else:
                messages.add_message(
                    request, messages.SUCCESS, error_messages.get("can_not_remove_error"))
コード例 #23
0
def generate_token(request):
    try:

        lists = {}

        form = forms.GenerateTokenForm(
            request.POST) if request.method == 'POST' else forms.GenerateTokenForm()

        if form.is_valid():

            user_ldap_ass = ""
            user = str(form.cleaned_data['user'])
            idt = None if not form.cleaned_data[
                'requestVip'] else form.cleaned_data['requestVip']
            ttl = ACCESS_EXTERNAL_TTL if not form.cleaned_data[
                'p'] else form.cleaned_data['p']

            # Login with LDAP
            if form.cleaned_data['is_ldap_user']:
                username_ldap, password_ldap = str(user).split("@")
                try:
                    user_ldap = Ldap("").get_user(username_ldap)
                except LDAPNotFoundError, e:
                    raise Exception(auth_messages.get("user_ldap_not_found"))

                pwd_ldap = user_ldap['userPassword']
                activate = user_ldap.get('nsaccountlock')
                pwd = password_ldap

                if re.match("\{(MD|md)5\}.*", pwd_ldap, 0):
                    pwd = base64.b64encode(hashlib.md5(pwd).digest())
                    pwd_ldap = pwd_ldap[pwd_ldap.index("}") + 1:]

                if pwd == pwd_ldap and (activate is None or activate.upper() == 'FALSE'):
                    # Valid User
                    client, client_user = facade.validate_user_networkapi(
                        user, form.cleaned_data['is_ldap_user'])
                    user_ldap_client = client_user.get('user')
                    user_ldap_ass = user_ldap_client['user_ldap']
                else:
                    client_user = None
            else:
                # Valid User
                client, client_user = facade.validate_user_networkapi(
                    user, form.cleaned_data['is_ldap_user'])

            # Valid User
            if client_user is None:
                raise UserNotAuthenticatedError("user_invalid")
            else:
                # Valid idt
                if idt is not None and not is_valid_int_param(idt):
                    raise Exception(
                        error_messages.get("invalid_param") % "requestVip")

                # Valid ttl
                if not is_valid_int_param(ttl):
                    raise Exception(error_messages.get("invalid_param") % "p")

                if idt is not None:
                    client.create_vip().get_by_id(idt)

                # Encrypt hash
                user_hash = Encryption().Encrypt(user + "@" + str(user_ldap_ass))

                # Get Authenticate User
                authenticate_user = client_user.get('user')

                # Get Permissions by Authenticate User
                permissions = authenticate_user and authenticate_user.get('permission')

                # Generates token
                key = "%s:%s:%s" % (__name__, str(user), str(strftime("%Y%m%d%H%M%S")))

                token = hashlib.sha1(key).hexdigest()

                data_to_cache = {"user_hash": user_hash, "permissions": permissions}

                # Set token in cache
                cache.set(token, data_to_cache, int(ttl))

                lists["token"] = token

                if idt is not None:
                    lists["url"] = reverse("vip-request.edit.external", args=[idt])
                else:
                    lists["url"] = reverse("vip-request.form.external")

            return render_to_response(templates.VIPREQUEST_TOKEN, lists, context_instance=RequestContext(request))

    except InvalidParameterError, e:
        logger.error(e)
        lists["error"] = error_messages.get("invalid_param") % "id"