def view_local_group(request):
    return_dict = {}
    try:
        if 'searchby' not in request.GET:
            raise Exception("Malformed request. Please use the menus.")
        if request.GET['searchby'] == 'grpname':
            if 'grpname' not in request.GET:
                raise Exception("Malformed request. Please use the menus.")
            gd, err = local_users.get_local_group(request.GET['grpname'])
        elif request.GET['searchby'] == 'gid':
            if 'gid' not in request.GET:
                raise Exception("Malformed request. Please use the menus.")
            gd, err = local_users.get_local_group(request.GET['grpname'],
                                                  False)

        if err:
            raise Exception(err)

        if not gd:
            raise Exception("Specified group not found. Please use the menus.")

        return_dict["group"] = gd

        if "ack" in request.GET:
            if request.GET["ack"] == "gid_changed":
                return_dict[
                    'ack_message'] = "Local user's group successfully updated"
            elif request.GET["ack"] == "changed_password":
                return_dict['ack_message'] = "Successfully update password"
            elif request.GET["ack"] == "set_membership":
                return_dict[
                    'ack_message'] = "Local group membership successfully modified"

        return django.shortcuts.render_to_response(
            'view_local_group.html',
            return_dict,
            context_instance=django.template.context.RequestContext(request))
    except Exception, e:
        return_dict['base_template'] = 'users_groups_base.html'
        return_dict["page_title"] = 'Local group details'
        return_dict['tab'] = 'view_local_groups_tab'
        return_dict["error"] = 'Error loading local group details '
        return_dict["error_details"] = str(e)
        return django.shortcuts.render_to_response(
            "logged_in_error.html",
            return_dict,
            context_instance=django.template.context.RequestContext(request))
def delete_local_group(request):
    return_dict = {}
    try:
        req_ret, err = django_utils.get_request_parameter_values(
            request, ['grpname'])
        if err:
            raise Exception(err)
        if 'grpname' not in req_ret:
            raise Exception('Invalid request, please use the menus.')

        gd, err = local_users.get_local_group(req_ret['grpname'])
        if err or (not gd):
            if err:
                raise Exception(err)
            else:
                raise Exception("Could not retrieve group information")

        if gd['members']:
            raise Exception(
                "Cannot delete this group as it has the following members : %s"
                % (','.join(gd['members'])))

        if request.method == "GET":
            # Return the form
            return_dict["grpname"] = request.GET["grpname"]
            return django.shortcuts.render_to_response(
                "delete_local_group_conf.html",
                return_dict,
                context_instance=django.template.context.RequestContext(
                    request))
        else:
            # Form submission so create
            return_dict = {}
            ret, err = local_users.delete_local_group(request.POST["grpname"])
            if not ret:
                if err:
                    raise Exception('Error deleting group : %s' % err)
                else:
                    raise Exception('Error deleting group')
            audit_str = "Deleted a local group %s" % request.POST["grpname"]
            audit.audit("delete_local_group", audit_str, request)
            url = '/users_groups/view_local_groups?ack=deleted'
            return django.http.HttpResponseRedirect(url)
    except Exception, e:
        return_dict['base_template'] = 'users_groups_base.html'
        return_dict["page_title"] = 'Delete a local user group'
        return_dict['tab'] = 'view_local_groups_tab'
        return_dict["error"] = 'Error deleting a local user group'
        return_dict["error_details"] = str(e)
        return django.shortcuts.render_to_response(
            "logged_in_error.html",
            return_dict,
            context_instance=django.template.context.RequestContext(request))
def view_local_group(request):
    return_dict = {}
    try:
        if 'searchby' not in request.GET:
            raise Exception("Malformed request. Please use the menus.")
        if request.GET['searchby'] == 'grpname':
            if 'grpname' not in request.GET:
                raise Exception("Malformed request. Please use the menus.")
            gd, err = local_users.get_local_group(request.GET['grpname'])
        elif request.GET['searchby'] == 'gid':
            if 'gid' not in request.GET:
                raise Exception("Malformed request. Please use the menus.")
            gd, err = local_users.get_local_group(
                request.GET['grpname'], False)

        if err:
            raise Exception(err)

        if not gd:
            raise Exception("Specified group not found. Please use the menus.")

        return_dict["group"] = gd

        if "ack" in request.GET:
            if request.GET["ack"] == "gid_changed":
                return_dict['ack_message'] = "Local user's group successfully updated"
            elif request.GET["ack"] == "changed_password":
                return_dict['ack_message'] = "Successfully update password"
            elif request.GET["ack"] == "set_membership":
                return_dict['ack_message'] = "Local group membership successfully modified"

        return django.shortcuts.render_to_response('view_local_group.html', return_dict, context_instance=django.template.context.RequestContext(request))
    except Exception, e:
        return_dict['base_template'] = 'users_groups_base.html'
        return_dict["page_title"] = 'Local group details'
        return_dict['tab'] = 'view_local_groups_tab'
        return_dict["error"] = 'Error loading local group details '
        return_dict["error_details"] = str(e)
        return django.shortcuts.render_to_response("logged_in_error.html", return_dict, context_instance=django.template.context.RequestContext(request))
def delete_local_group(request):
    return_dict = {}
    try:
        req_ret, err = django_utils.get_request_parameter_values(request, [
                                                                 'grpname'])
        if err:
            raise Exception(err)
        if 'grpname' not in req_ret:
            raise Exception('Invalid request, please use the menus.')

        gd, err = local_users.get_local_group(req_ret['grpname'])
        if err or (not gd):
            if err:
                raise Exception(err)
            else:
                raise Exception("Could not retrieve group information")

        if gd['members']:
            raise Exception("Cannot delete this group as it has the following members : %s" % (
                ','.join(gd['members'])))

        if request.method == "GET":
            # Return the form
            return_dict["grpname"] = request.GET["grpname"]
            return django.shortcuts.render_to_response("delete_local_group_conf.html", return_dict, context_instance=django.template.context.RequestContext(request))
        else:
            # Form submission so create
            return_dict = {}
            ret, err = local_users.delete_local_group(request.POST["grpname"])
            if not ret:
                if err:
                    raise Exception('Error deleting group : %s' % err)
                else:
                    raise Exception('Error deleting group')
            audit_str = "Deleted a local group %s" % request.POST["grpname"]
            audit.audit("delete_local_group", audit_str, request)
            url = '/users_groups/view_local_groups?ack=deleted'
            return django.http.HttpResponseRedirect(url)
    except Exception, e:
        return_dict['base_template'] = 'users_groups_base.html'
        return_dict["page_title"] = 'Delete a local user group'
        return_dict['tab'] = 'view_local_groups_tab'
        return_dict["error"] = 'Error deleting a local user group'
        return_dict["error_details"] = str(e)
        return django.shortcuts.render_to_response("logged_in_error.html", return_dict, context_instance=django.template.context.RequestContext(request))
def update_group_membership(request):
    return_dict = {}
    try:
        if "ack" in request.GET:
            if request.GET["ack"] == "created":
                return_dict['ack_message'] = "Local group successfully created"

        req_ret, err = django_utils.get_request_parameter_values(request, [
                                                                 'grpname'])
        if err:
            raise Exception(err)
        if 'grpname' not in req_ret:
            raise Exception('Invalid request, please use the menus.')

        gd, err = local_users.get_local_group(req_ret['grpname'])
        if err or (not gd):
            if err:
                raise Exception(err)
            else:
                raise Exception("Could not retrieve group information")

        # print 'gd - ', gd

        user_list, err = local_users.get_local_users()
        if err:
            raise Exception(err)

        # print 'user_list', user_list

        users = []
        primary_users = []
        permitted_users = []
        for u in user_list:
            if u['gid'] != gd['gid']:
                permitted_users.append(u)
            else:
                primary_users.append(u['username'])
            if u['username'] in gd['members']:
                users.append(u['username'])
        # print 'users', users
        #return_dict['primary_users'] = primary_users

        if request.method == "GET":
            # Return the form
            initial = {}
            initial['grpname'] = request.GET['grpname']
            initial['users'] = users
            form = local_user_forms.ModifyGroupMembershipForm(
                initial=initial, user_list=permitted_users)
            return_dict['form'] = form
            return django.shortcuts.render_to_response("update_group_membership.html", return_dict, context_instance=django.template.context.RequestContext(request))
        else:
            form = local_user_forms.ModifyGroupMembershipForm(
                request.POST, user_list=permitted_users)
            return_dict["form"] = form
            if form.is_valid():
                cd = form.cleaned_data
                users = cd['users']
                # print users

                audit_str = 'Modified group membership for group "%s". ' % cd['grpname']
                deleted_users = []
                for existing_user in gd['members']:
                    if existing_user not in users and existing_user not in primary_users:
                        deleted_users.append(existing_user)
                        # print 'delete user %s'%existing_user
                added_users = []
                for user in users:
                    if user not in gd['members'] and user not in primary_users:
                        added_users.append(user)
                        # print 'add user %s'%user
                if added_users:
                    audit_str += 'Added user(s) %s. ' % (','.join(added_users))
                if deleted_users:
                    audit_str += 'Removed user(s) %s.' % (
                        ','.join(deleted_users))
                # print audit_str
                #assert False
                ret, err = local_users.set_group_membership(
                    cd['grpname'], cd['users'])
                if err:
                    raise Exception('Error setting group membership: %s' % err)
                #assert False
                audit.audit("set_group_membership", audit_str, request)
                url = '/users_groups/view_local_groups?ack=set_membership'
                return django.http.HttpResponseRedirect(url)
            else:
                return django.shortcuts.render_to_response("update_group_membership.html", return_dict, context_instance=django.template.context.RequestContext(request))
    except Exception, e:
        return_dict['base_template'] = 'users_groups_base.html'
        return_dict["page_title"] = 'Modify group membership'
        return_dict['tab'] = 'view_local_groups_tab'
        return_dict["error"] = 'Error modifying group membership'
        return_dict["error_details"] = str(e)
        return django.shortcuts.render_to_response("logged_in_error.html", return_dict, context_instance=django.template.context.RequestContext(request))
def update_group_membership(request):
    return_dict = {}
    try:
        if "ack" in request.GET:
            if request.GET["ack"] == "created":
                return_dict['ack_message'] = "Local group successfully created"

        req_ret, err = django_utils.get_request_parameter_values(
            request, ['grpname'])
        if err:
            raise Exception(err)
        if 'grpname' not in req_ret:
            raise Exception('Invalid request, please use the menus.')

        gd, err = local_users.get_local_group(req_ret['grpname'])
        if err or (not gd):
            if err:
                raise Exception(err)
            else:
                raise Exception("Could not retrieve group information")

        # print 'gd - ', gd

        user_list, err = local_users.get_local_users()
        if err:
            raise Exception(err)

        # print 'user_list', user_list

        users = []
        primary_users = []
        permitted_users = []
        for u in user_list:
            if u['gid'] != gd['gid']:
                permitted_users.append(u)
            else:
                primary_users.append(u['username'])
            if u['username'] in gd['members']:
                users.append(u['username'])
        # print 'users', users
        #return_dict['primary_users'] = primary_users

        if request.method == "GET":
            # Return the form
            initial = {}
            initial['grpname'] = request.GET['grpname']
            initial['users'] = users
            form = local_user_forms.ModifyGroupMembershipForm(
                initial=initial, user_list=permitted_users)
            return_dict['form'] = form
            return django.shortcuts.render_to_response(
                "update_group_membership.html",
                return_dict,
                context_instance=django.template.context.RequestContext(
                    request))
        else:
            form = local_user_forms.ModifyGroupMembershipForm(
                request.POST, user_list=permitted_users)
            return_dict["form"] = form
            if form.is_valid():
                cd = form.cleaned_data
                users = cd['users']
                # print users

                audit_str = 'Modified group membership for group "%s". ' % cd[
                    'grpname']
                deleted_users = []
                for existing_user in gd['members']:
                    if existing_user not in users and existing_user not in primary_users:
                        deleted_users.append(existing_user)
                        # print 'delete user %s'%existing_user
                added_users = []
                for user in users:
                    if user not in gd['members'] and user not in primary_users:
                        added_users.append(user)
                        # print 'add user %s'%user
                if added_users:
                    audit_str += 'Added user(s) %s. ' % (','.join(added_users))
                if deleted_users:
                    audit_str += 'Removed user(s) %s.' % (
                        ','.join(deleted_users))
                # print audit_str
                #assert False
                ret, err = local_users.set_group_membership(
                    cd['grpname'], cd['users'])
                if err:
                    raise Exception('Error setting group membership: %s' % err)
                #assert False
                audit.audit("set_group_membership", audit_str, request)
                url = '/users_groups/view_local_groups?ack=set_membership'
                return django.http.HttpResponseRedirect(url)
            else:
                return django.shortcuts.render_to_response(
                    "update_group_membership.html",
                    return_dict,
                    context_instance=django.template.context.RequestContext(
                        request))
    except Exception, e:
        return_dict['base_template'] = 'users_groups_base.html'
        return_dict["page_title"] = 'Modify group membership'
        return_dict['tab'] = 'view_local_groups_tab'
        return_dict["error"] = 'Error modifying group membership'
        return_dict["error_details"] = str(e)
        return django.shortcuts.render_to_response(
            "logged_in_error.html",
            return_dict,
            context_instance=django.template.context.RequestContext(request))