def edit_group(request, name): """Edit a group (add/delete users)""" group = Group.find(name) if not group: raise Http404() if not request.user.administrator: raise PermissionDenied if request.method == "POST": form = GroupForm(request.POST) if form.is_valid(): data = form.cleaned_data group.update(name=data["name"], username=request.user.name) return redirect("groups:home") else: initial_data = {"name": group.name} form = GroupForm(initial=initial_data) ctx = { "form": form, "group": group, } return render(request, "groups/edit.html", ctx)
def add_to_group(self, args): """Add user(s) to a group.""" groupname = args[ARG_NAME] ls_users = args[ARG_USERLIST] group = Group.find(groupname) if not group: self.print_error(MSG_GROUP_NOT_EXIST.format(groupname)) return added, not_added, already_there = group.add_users(ls_users) if added: self.print_success( MSG_ADD_USER.format(", ".join(added), group.name) ) if already_there: if len(already_there) == 1: verb = "is" else: verb = "are" self.print_error( MSG_USER_IN_GROUP.format( ", ".join(already_there), verb, group.name ) ) if not_added: if len(not_added) == 1: msg = MSG_USER_NOT_EXIST else: msg = MSG_USERS_NOT_EXIST self.print_error(msg.format(", ".join(not_added)))
def add_user(request, name): """Add a user to a group""" group = Group.find(name) if not group: raise Http404 if not request.user.administrator: raise PermissionDenied users = [(u.name, u.name) for u in User.objects.all() if not group.name in u.groups] if request.method == "POST": form = GroupAddForm(users, request.POST) if form.is_valid(): data = form.cleaned_data new_users = data.get("users", []) added, _, _ = group.add_users(new_users, username=request.user.name) if added: msg = "{} has been added to the group '{}'".format( ", ".join(added), group.name) group.update(username=request.user.name) else: msg = "No user has been added to the group '{}'".format( group.name) messages.add_message(request, messages.INFO, msg) return redirect("groups:view", name=name) else: form = GroupAddForm(users) ctx = {"group": group, "form": form, "users": users} return render(request, "groups/add.html", ctx)
def modify_group(request, groupname): """Expecting json in the body: { "add_users": [user1, user2, ...], "rm_users": [user1, user2, ...] } """ try: body = request.body request_body = json.loads(body) except (TypeError, json.JSONDecodeError): return Response("Invalid JSON body", status=HTTP_400_BAD_REQUEST) group_db = Group.find(groupname) if not group_db: return Response( u"Group {} doesn't exist".format(groupname), status=HTTP_404_NOT_FOUND ) # Add users to group if "add_users" in request_body: return add_user_group(group_db, request_body["add_users"]) # Remove users from group if "rm_users" in request_body: return rm_user_group(group_db, request_body["rm_users"]) return Response("Bad request", status=HTTP_400_BAD_REQUEST)
def rm_from_group(self, args): """Remove user(s) from a group.""" groupname = args[ARG_NAME] group = Group.find(groupname) if not group: self.print_error(MSG_GROUP_NOT_EXIST.format(groupname)) return ls_users = args[ARG_USERLIST] removed, not_there, not_exist = group.rm_users(ls_users) if removed: self.print_success( "Removed {} from the group {}".format(", ".join(removed), group.name) ) if not_there: if len(not_there) == 1: verb = "isn't" else: verb = "aren't" self.print_error( "{} {} in the group {}".format(", ".join(not_there), verb, group.name) ) if not_exist: if len(not_exist) == 1: msg = "{} doesn't exist" else: msg = "{} don't exist" self.print_error(msg.format(", ".join(not_exist)))
def home(request): """Default view for Activities""" notifications = Notification.recent(10) activities = [] for notif in notifications: tmpl = template.Template(notif["tmpl"]) obj_uuid = notif["object_uuid"] obj = None if notif["object_type"] == OBJ_RESOURCE: obj = Resource.find(obj_uuid) if obj: object_dict = obj.to_dict() else: object_dict = {"name": obj_uuid} elif notif["object_type"] == OBJ_COLLECTION: obj = Collection.find(obj_uuid) if obj: object_dict = obj.to_dict() else: object_dict = {"name": obj_uuid} elif notif["object_type"] == OBJ_USER: obj = User.find(obj_uuid) if obj: object_dict = obj.to_dict() else: # User has been deleted it can't be find by uuid # look in payload of the message to get the name if notif["operation"] in [OP_CREATE, OP_UPDATE]: name = notif["payload"]["post"]["name"] else: # OP_DELETE name = notif["payload"]["pre"]["name"] object_dict = {"name": name} elif notif["object_type"] == OBJ_GROUP: obj = Group.find(obj_uuid) if obj: object_dict = obj.to_dict() else: # User has been deleted it can't be find by uuid # look in payload of the message to get the name if notif["operation"] in [OP_CREATE, OP_UPDATE]: name = notif["payload"]["post"]["name"] else: # OP_DELETE name = notif["payload"]["pre"]["name"] object_dict = {"uuid": obj_uuid, "name": name} user_dict = {} if notif["username"]: user = User.find(notif["username"]) if user: user_dict = user.to_dict() else: user_dict = { 'name': notif["username"], 'email': notif["username"]+ '@radon.org' } variables = {"user": user_dict, "when": notif["when"], "object": object_dict} ctx = template.Context(variables) activities.append({"html": tmpl.render(ctx)}) return render(request, "activity/index.html", {"activities": activities})
def delete_group(request, groupname): """Delete a group""" group_db = Group.find(groupname) if not group_db: return Response( u"Group {} doesn't exist".format(groupname), status=HTTP_404_NOT_FOUND ) group_db.delete() return Response(u"Group {} has been deleted".format(groupname), status=HTTP_200_OK)
def ls_group(request, groupname): """Get a list of groups""" # TODO check if groupname is valid to test ? group_db = Group.find(groupname) try: return Response(group_db.to_dict()) except NameError: return Response( u"Group {} not found".format(groupname), status=HTTP_404_NOT_FOUND )
def group_view(request, name): """Display the content of a group (users)""" group = Group.find(name) if not group: return redirect("groups:home") # raise Http404 ctx = { "user": request.user, "group_obj": group, "members": group.get_usernames() } return render(request, "groups/view.html", ctx)
def rm_group(self, args): """Remove a group.""" if not args[ARG_NAME]: name = input(MSG_PROMPT_GROUP) else: name = args[ARG_NAME] group = Group.find(name) if not group: self.print_error(MSG_GROUP_NOT_EXIST.format(name)) return group.delete() print(MSG_GROUP_DELETED.format(name))
def user_view(request, name): """Render the view page for users""" # argument is the login name, not the uuid in Cassandra user = User.find(name) if not user: return redirect("users:home") ctx = { "req_user": request.user, "user_obj": user, "groups": [Group.find(gname) for gname in user.groups], } return render(request, "users/view.html", ctx)
def mk_group(self, args): """Create a new group. Ask in the terminal for mandatory fields""" if not args[ARG_NAME]: name = input("Please enter the group name: ") else: name = args[ARG_NAME] group = Group.find(name) if group: self.print_error(MSG_GROUP_EXIST.format(name)) return group = Group.create(name=name) print(MSG_GROUP_CREATED.format(group.name))
def create_group(request): """Expecting json in the body: { "groupname": groupname } """ try: body = request.body request_body = json.loads(body) except (TypeError, json.JSONDecodeError): return Response("Invalid JSON body", status=HTTP_400_BAD_REQUEST) try: groupname = request_body["groupname"] except KeyError: return Response("Missing groupname", status=HTTP_400_BAD_REQUEST) group_db = Group.find(groupname) if group_db: return Response("Group already exists", status=HTTP_409_CONFLICT) new_group_db = Group.create(name=groupname) return Response(new_group_db.to_dict(), status=HTTP_201_CREATED)
def acl_list_to_cql(read_access, write_access): """Convert a list of read/write access for groups to the cql string used to update the Cassandra model :param read_access: A list of group names which have read access :type read_access: List[str] :param write_access: A list of group names which have write access :type write_access: List[str] :return: A CQL string that can be used to update values in Cassandra :rtype: str """ access = {} for gname in read_access: access[gname] = ACCESS_STR_READ for gname in write_access: if gname in access: access[gname] = ACCESS_STR_RW else: access[gname] = ACCESS_STR_WRITE ls_access = [] for gname in access: g = Group.find(gname) if g: ident = g.name elif gname.upper() == "AUTHENTICATED@": ident = "AUTHENTICATED@" elif gname.upper() == "ANONYMOUS@": ident = "ANONYMOUS@" else: # TODO log or return error if the identifier isn't found ? radon.cfg.logger.warning( "The group {0} doesn't exist".format(gname)) continue s = (u"'{}': {{" "acetype: 'ALLOW', " "identifier: '{}', " "aceflags: {}, " "acemask: {}" "}}").format(ident, ident, 0, str_to_acemask(access[gname], False)) ls_access.append(s) acl = u"{{{}}}".format(", ".join(ls_access)) return acl
def acl_cdmi_to_cql(cdmi_acl): """Convert a list of ACL for groups stored in cdmi format to the cql string used to update the Cassandra model :param cdmi_acl: a cdmi string for :type cdmi_acl: List[dict] :return: A CQL string that can be used to update values in Cassandra :rtype: str """ ls_access = [] for cdmi_ace in cdmi_acl: if 'identifier' in cdmi_ace: gid = cdmi_ace['identifier'] else: # Wrong syntax for the ace radon.cfg.logger.warning( "Wrong format for the cdmi string for ACL, 'identifier' field not found" ) continue group = Group.find(gid) if group: ident = group.name elif gid.upper() == "AUTHENTICATED@": ident = "AUTHENTICATED@" elif gid.upper() == "ANONYMOUS@": ident = "ANONYMOUS@" else: radon.cfg.logger.warning( "Wrong format for the cdmi string for ACL, {} group not found". format(gid)) continue s = (u"'{}': {{" "acetype: '{}', " "identifier: '{}', " "aceflags: {}, " "acemask: {}" "}}").format(ident, cdmi_ace['acetype'].upper(), ident, cdmi_str_to_aceflag(cdmi_ace['aceflags']), cdmi_str_to_acemask(cdmi_ace['acemask'], False)) ls_access.append(s) acl = u"{{{}}}".format(", ".join(ls_access)) return acl
def delete_group(request, name): """Delete a group""" group = Group.find(name) if not group: raise Http404 if not request.user.administrator: raise PermissionDenied if request.method == "POST": group.delete(username=request.user.name) messages.add_message( request, messages.INFO, "The group '{}' has been deleted".format(group.name)) return redirect("groups:home") # Requires delete on user ctx = { "group": group, } return render(request, "groups/delete.html", ctx)
def rm_user(request, name, uname): """Remove a user from a group""" group = Group.find(name) user = User.find(uname) if not request.user.administrator: raise PermissionDenied if user and group: removed, not_there, not_exist = group.rm_user( uname, username=request.user.name) if removed: msg = "'{}' has been removed from the group '{}'".format( uname, name) elif not_there: msg = "'{}' isn't in the group '{}'".format(uname, name) elif not_exist: msg = "'{}' doesn't exist".format(uname) messages.add_message(request, messages.INFO, msg) else: raise Http404 return redirect("groups:view", name=name)
def list_groups(self, args): """List all groups or a specific group if the name is specified""" if args[ARG_NAME]: name = args[ARG_NAME] group = Group.find(name) if group: group_info = group.to_dict() members = ", ".join(group_info.get("members", [])) print( "{0.bold}Group name{0.normal}: {1}".format( self.terminal, group_info.get("name", name) ) ) print( "{0.bold}Group id{0.normal}: {1}".format( self.terminal, group_info.get("uuid", "") ) ) print("{0.bold}Members{0.normal}: {1}".format(self.terminal, members)) else: self.print_error(MSG_GROUP_NOT_EXIST.format(name)) else: for group in Group.objects.all(): print(group.name)