def setup_module():
    cfg.dse_keyspace = TEST_KEYSPACE
    initialise()
    connect()
    create_tables()
    create_default_users()
    create_root()

    grp1 = Group.create(name=GRP1_NAME)
    grp2 = Group.create(name=GRP2_NAME)
    grp3 = Group.create(name=GRP3_NAME)

    user_name = USR1_NAME
    email = uuid.uuid4().hex
    password = uuid.uuid4().hex
    administrator = True
    groups = [GRP1_NAME]
    user1 = User.create(name=user_name,
                        email=email,
                        password=password,
                        administrator=administrator,
                        groups=groups)

    user_name = USR2_NAME
    email = uuid.uuid4().hex
    password = uuid.uuid4().hex
    administrator = False
    groups = [GRP1_NAME, GRP2_NAME]
    user2 = User.create(name=user_name,
                        email=email,
                        password=password,
                        administrator=administrator,
                        groups=groups)
def setup_module():
    cfg.dse_keyspace = TEST_KEYSPACE
    initialise()
    connect()
    create_tables()
    create_root()
    Group.create(name="grp1")
Beispiel #3
0
    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))
Beispiel #4
0
def test_create():
    grp_name = uuid.uuid4().hex
    grp = Group.create(name=grp_name)

    assert grp.name == grp_name

    # Test already existing group
    with pytest.raises(GroupConflictError):
        grp = Group.create(name=grp_name)

    grp.delete()

    # Test the username for the notification
    grp = Group.create(name=grp_name, username="******")
    grp.delete()
Beispiel #5
0
def test_add_user():
    grp1_name = uuid.uuid4().hex
    grp2_name = uuid.uuid4().hex
    grp3_name = uuid.uuid4().hex

    g1 = Group.create(name=grp1_name)
    g2 = Group.create(name=grp2_name)
    g3 = Group.create(name=grp3_name)

    u1 = create_random_user([])
    u2 = create_random_user([])
    u3 = create_random_user([])
    u4 = create_random_user([g2.name, g3.name])

    # g2 = [u4]
    # g3 = [u4]

    g1.add_user(u1.name)
    assert u1.name in g1.get_usernames()
    # g1 = [u1]

    added, not_added, already_there = g2.add_users(
        [u1.name, u2.name, u4.name, "unknown_user"])
    # g2 = [u1, u2, u4]
    assert u1.name in g2.get_usernames()
    assert u2.name in g2.get_usernames()
    assert u4.name in g2.get_usernames()  # From create
    assert added == [u1.name, u2.name]
    assert not_added == ["unknown_user"]
    assert already_there == [u4.name]

    g2.rm_user(u4.name)
    # g2 = [u1, u2]
    assert not u4.name in g2.get_usernames()

    removed, not_there, not_exist = g2.rm_users(
        [u1.name, u2.name, u4.name, "unknown_user"])
    assert removed == [u1.name, u2.name]
    assert not_there == [u4.name]
    assert not_exist == ["unknown_user"]

    g1.delete()
    g2.delete()
    g3.delete()
    u1.delete()
    u2.delete()
    u3.delete()
    u4.delete()
Beispiel #6
0
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)
Beispiel #7
0
    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)))
Beispiel #8
0
 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)))
Beispiel #9
0
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)
Beispiel #10
0
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)
Beispiel #11
0
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})
Beispiel #12
0
def test_update():
    grp1_name = uuid.uuid4().hex
    g1 = Group.create(name=grp1_name)

    g1.update(uuid=default_uuid())
    g1.update(uuid=default_uuid(), username="******")

    g1.delete()
Beispiel #13
0
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)
Beispiel #14
0
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)
Beispiel #15
0
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
        )
Beispiel #16
0
def create_default_users():
    """Create some users and groups
    
    Users and groups are defined in DEFAULT_GROUPS and DEFAULT_USERS in the 
    :mod:`radon.model.config` module, .
    
    """
    for name in cfg.default_groups:
        try:
            Group.create(name=name)
        except GroupConflictError:
            pass
    for name, email, pwd, is_admin, groups in cfg.default_users:
        try:
            User.create(name=name,
                        email=email,
                        password=pwd,
                        administrator=is_admin,
                        groups=groups)
        except UserConflictError:
            pass
Beispiel #17
0
 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))
Beispiel #18
0
def test_group():
    grp1_name = uuid.uuid4().hex
    grp2_name = uuid.uuid4().hex
    grp1 = Group.create(name=grp1_name)
    grp2 = Group.create(name=grp2_name)

    user_name = uuid.uuid4().hex
    email = uuid.uuid4().hex
    password = uuid.uuid4().hex
    administrator = True
    groups = [grp1_name, grp2_name]
    user = User.create(name=user_name,
                       email=email,
                       password=password,
                       administrator=administrator,
                       groups=groups)

    assert set(user.get_groups()) == set([grp1_name, grp2_name])

    user.rm_group(grp1_name)
    assert set(user.get_groups()) == set([grp2_name])
Beispiel #19
0
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)
Beispiel #20
0
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)
Beispiel #21
0
def test_to_dict():
    grp1_name = uuid.uuid4().hex
    g1 = Group.create(name=grp1_name)

    u1 = create_random_user([g1.name])

    g_dict = g1.to_dict()
    assert g_dict['uuid'] == g1.uuid
    assert g_dict['name'] == grp1_name
    assert g_dict['members'] == [u1.name]

    g1.delete()
    u1.delete()
Beispiel #22
0
 def mqtt_get_state(self):
     """
     Get the user state that will be used in the payload
     
     :return: The user state as a dictionary
     :rtype: dict
     """
     payload = dict()
     payload["uuid"] = self.uuid
     payload["name"] = self.name
     payload["email"] = self.email
     payload["active"] = self.active
     payload["groups"] = [g.name for g in Group.find_all(self.groups)]
     return payload
Beispiel #23
0
 def to_dict(self):
     """
     Return a dictionary which describes a resource for the web ui
     
     :return: The dictionary with the information needed for the UI
     :rtype: dict
     """
     return {
         "uuid": self.uuid,
         "name": self.name,
         "email": self.email,
         "administrator": self.administrator,
         "active": self.active,
         "ldap": self.ldap,
         "groups": [g.to_dict() for g in Group.find_all(self.groups)],
     }
Beispiel #24
0
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
Beispiel #25
0
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)
Beispiel #26
0
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
Beispiel #27
0
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)
Beispiel #28
0
def new_group(request):
    """Display the form to create a new group"""
    if request.method == "POST":
        form = GroupForm(request.POST)
        if form.is_valid():
            data = form.cleaned_data
            group = Group.create(name=data.get("name"),
                                 username=request.user.name)
            messages.add_message(
                request,
                messages.INFO,
                "The group '{}' has been created".format(group.name),
            )
            return redirect("groups:home")
    else:
        form = GroupForm()
    ctx = {
        "form": form,
    }

    return render(request, "groups/new.html", ctx)
Beispiel #29
0
def setup_module():
    cfg.dse_keyspace = TEST_KEYSPACE
    initialise()
    connect()
    create_tables()
    create_default_users()
    create_root()
    pwd = uuid.uuid4().hex
    email = uuid.uuid4().hex
    grp1 = Group.create(name="grp1")
    u1 = User.create(name="user1",
                     password=pwd,
                     email=email,
                     administrator=True)
    u2 = User.create(name="user2",
                     password=pwd,
                     email=email,
                     administrator=False)

    grp1.add_users(["user2"])

    try:
        coll = Collection.create("/", "1")
        coll = Collection.create("/1", "11")
        coll = Collection.create("/1", "12")
        coll = Collection.create("/1", "13")
        coll = Collection.create("/", "2")
        coll = Collection.create("/2", "21")
        coll = Collection.create("/2/21", "211")
        coll = Collection.create("/2/21", "212")
        r = Resource.create("/1/11", "a")
        r = Resource.create("/1/11", "b", url=TEST_URL)
        r = Resource.create("/1/12", "c")
        r = Resource.create("/1/13", "d")
        r = Resource.create("/2/21/211", "e")
        r = Resource.create("/2/21/212", "f")
        r = Resource.create("/", "g")
    except:  # If collections or resources already exist
        pass
Beispiel #30
0
 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)