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)
Beispiel #2
0
def create_user(request):
    """Expecting json in the body:
    { "username": username,
      "password": password,
      "email": email,
      "administrator": is_admin }
    """
    try:
        body = request.body
        request_body = json.loads(body)
    except (TypeError, json.JSONDecodeError):
        return Response("Invalid JSON body", status=HTTP_400_BAD_REQUEST)
    try:
        username = request_body["username"]
    except KeyError:
        return Response("Missing username", status=HTTP_400_BAD_REQUEST)
    user_db = User.find(username)
    if user_db:
        return Response("User already exists", status=HTTP_409_CONFLICT)
    try:
        email = request_body["email"]
    except KeyError:
        return Response("Missing email", status=HTTP_400_BAD_REQUEST)
    try:
        password = request_body["password"]
    except KeyError:
        return Response("Missing password", status=HTTP_400_BAD_REQUEST)
    administrator = request_body.get("administrator", False)
    new_user_db = User.create(
        name=username, password=password, email=email, administrator=administrator
    )
    return Response(new_user_db.to_dict(), status=HTTP_201_CREATED)
def test_dict():
    coll_name = uuid.uuid4().hex
    coll = Collection.create("/", coll_name)
    myFactory = Faker()
    content = myFactory.text()

    # Read/Write resource stored in Cassandra
    do = DataObject.create(content.encode())
    resc_name = uuid.uuid4().hex
    resc = Resource.create(coll.path,
                           resc_name,
                           url="{}{}".format(cfg.protocol_cassandra, do.uuid))
    resc = Resource.find(resc.path)

    resc_dict = resc.full_dict(User.find(USR1_NAME))
    assert resc_dict['size'] == len(content)
    assert resc_dict['can_read']
    assert resc_dict['can_write']
    assert resc_dict['uuid'] == resc.uuid

    resc_dict = resc.simple_dict(User.find(USR1_NAME))

    assert resc_dict['name'] == resc_name
    assert resc_dict['is_reference'] == False
    assert resc_dict['can_read']
    assert resc_dict['can_write']
    assert resc_dict['id'] == resc.uuid

    assert resc.simple_dict() == resc.to_dict()

    resc.delete()
    coll.delete()
Beispiel #4
0
def test_to_dict():
    # Create a new collection with a random name
    coll_name = uuid.uuid4().hex
    coll1 = Collection.create('/', coll_name)
    coll_dict = coll1.to_dict()
    assert coll_dict['id'] == coll1.uuid
    assert coll_dict['name'] == coll_name + '/'
    assert coll_dict['path'] == "/{}/".format(coll_name)

    # Specify a user to get ACL
    # user 1 is admin, he can do everything
    coll_dict = coll1.to_dict(User.find("user1"))
    assert coll_dict['can_read'] == True
    assert coll_dict["can_write"] == True
    assert coll_dict["can_edit"] == True
    assert coll_dict["can_delete"] == True

    # user 2 should have limited access
    coll_dict = coll1.to_dict(User.find("user2"))
    assert coll_dict['can_read'] == True
    assert coll_dict["can_write"] == False
    assert coll_dict["can_edit"] == False
    assert coll_dict["can_delete"] == False

    coll1.delete()
Beispiel #5
0
def test_authenticate(mocker):
    user_name = uuid.uuid4().hex
    email = uuid.uuid4().hex
    password = uuid.uuid4().hex
    administrator = True
    groups = ['grp1']

    user = User.create(name=user_name,
                       email=email,
                       password=password,
                       administrator=administrator,
                       groups=groups)
    user = User.find(user_name)

    assert user.authenticate(password)
    assert not user.authenticate(uuid.uuid4().hex)

    # Check ldap authentication (mock the actual test)
    cfg.auth_ldap_server_uri = "ldap://ldap.example.com"
    cfg.auth_ldap_user_dn_template = "uid=%(user)s,ou=users,dc=example,dc=com"
    mocker.patch('ldap.ldapobject.SimpleLDAPObject.simple_bind_s',
                 return_value=True)
    user.update(ldap=True)
    assert user.authenticate(password)

    # Check inactive user
    user.update(active=False)
    assert not user.authenticate(password)
Beispiel #6
0
def test_users():
    user_name = uuid.uuid4().hex
    email = uuid.uuid4().hex
    password = uuid.uuid4().hex
    administrator = True
    groups = ['grp1']
    notification_username = uuid.uuid4().hex

    # Simple create
    user = User.create(name=user_name,
                       email=email,
                       password=password,
                       administrator=administrator,
                       groups=groups)
    user = User.find(user_name)
    assert user.get_groups() == groups
    assert user.is_active() == True
    assert user.is_authenticated() == True

    with pytest.raises(UserConflictError):
        user = User.create(name=user_name,
                           email=email,
                           password=password,
                           administrator=administrator,
                           groups=groups)
    user.delete()

    # Create with a username for notification
    user = User.create(name=user_name,
                       email=email,
                       password=password,
                       administrator=administrator,
                       groups=groups,
                       username=notification_username)
    user.delete()
Beispiel #7
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 #8
0
def new_user(request):
    """Create a new user"""
    if request.method == "POST":
        form = UserForm(request.POST)
        if form.is_valid():
            data = form.cleaned_data
            user = User.create(
                name=data.get("username"),
                password=data.get("password").encode("ascii", "ignore"),
                email=data.get("email", ""),
                administrator=data.get("administrator", False),
                active=data.get("active", False),
                username=request.user.name,
            )
            messages.add_message(
                request,
                messages.INFO,
                "The user '{}' has been created".format(user.name),
            )
            return redirect("users:home")
    else:
        form = UserForm()
 
    ctx = {
        "form": form,
    }
    return render(request, "users/new.html", ctx)
Beispiel #9
0
def userlogin(request):
    """Try to log a user in the system"""
    if request.method == "GET":
        return render(request, "users/login.html", {})

    errors = ""
    username = request.POST.get("username")
    password = request.POST.get("password")

    invalid = "Username/Password not valid"

    if not username or not password:
        errors = "Username and password are required"

    if not errors:
        user = User.find(username)
        if not user:
            errors = invalid
        else:
            if not user.authenticate(password):
                errors = invalid
 
        if not errors:
            request.session["user"] = user.name
            return redirect("/")
 
    ctx = {}
    if errors:
        ctx = {"errors": errors}
 
    return render(request, "users/login.html", ctx)
Beispiel #10
0
def modify_user(request, username=""):
    """Expecting json in the body:
    { "username": username,
      "password": password,
      "email": email,
      "administrator": is_admin,
      "active": is_active}
    """
    try:
        body = request.body
        request_body = json.loads(body)
    except (TypeError, json.JSONDecodeError):
        return Response("Invalid JSON body", status=HTTP_400_BAD_REQUEST)
    if username is None:
        try:
            username = request_body["username"]
        except KeyError:
            return Response("Missing username", status=HTTP_400_BAD_REQUEST)
    user_db = User.find(username)
    if not user_db:
        return Response(
            u"User {} doesn't exist".format(username), status=HTTP_404_NOT_FOUND
        )
    if "email" in request_body:
        user_db.update(email=request_body["email"])
    if "password" in request_body:
        user_db.update(password=request_body["password"])
    if "administrator" in request_body:
        user_db.update(administrator=request_body["administrator"])
    if "active" in request_body:
        user_db.update(active=request_body["active"])
    return Response(user_db.to_dict(), status=HTTP_200_OK)
Beispiel #11
0
    def add_users(self, ls_users, username=None):
        """
        Add a list of users to a group
        Return 3 lists:
          - added for the username which were added
          - already_there for username already in the group
          - not_added for username not found

        :param ls_users: List of usernames to add to the group
        :type ls_users: List[str]
        :param username: the name of the user who made the action
        :type username: str, optional
        
        :return: 3 lists to summarize what happened
        :rtype: Tuple[List[str],List[str],List[str]]
        """
        from radon.model import User

        added = []
        not_added = []
        already_there = []
        for name in ls_users:
            user = User.find(name)
            if user:
                if self.name not in user.get_groups():
                    user.add_group(self.name, username)
                    added.append(name)
                else:
                    already_there.append(name)
            else:
                not_added.append(name)
        return added, not_added, already_there
Beispiel #12
0
    def rm_users(self, ls_users, username=False):
        """
        Remove a list of users from the group.
        Return 3 lists:
          - removed for the usernames which were removed
          - not_there for usernames who weren't in the group
          - not_exist for usernames who don't exist
        
        :param ls_users: The lists of user names to remove
        :type ls_users: List[str]
        :param username: the name of the user who made the action
        :type username: str, optional
        
        :return: 3 lists to summarize what happened
        :rtype: Tuple[List[str],List[str],List[str]]
        """
        from radon.model import User

        not_exist = []
        removed = []
        not_there = []
        for name in ls_users:
            user = User.find(name)
            if user:
                if self.name in user.get_groups():
                    user.rm_group(self.name, username)
                    removed.append(name)
                else:
                    not_there.append(name)
            else:
                not_exist.append(name)
        return removed, not_there, not_exist
Beispiel #13
0
 def mod_user(self, args):
     """Modify a user. Ask in the terminal if the value isn't provided"""
     name = args[ARG_NAME]
     user = User.find(name)
     if not user:
         self.print_error("User {} doesn't exist".format(name))
         return
     value = args["<value>"]
     if not value:
         if args["password"]:
             while not value:
                 value = getpass("Please enter the new password: "******"Please enter the new value: ")
     if args["email"]:
         user.update(email=value)
     elif args["administrator"]:
         user.update(administrator=value.lower() in ["true", "y", "yes"])
     elif args["active"]:
         user.update(active=value.lower() in ["true", "y", "yes"])
     elif args["ldap"]:
         user.update(ldap=value.lower() in ["true", "y", "yes"])
     elif args["password"]:
         user.update(password=value)
     print(MSG_USER_MODIFIED.format(name))
Beispiel #14
0
def delete_user(request, username):
    """Delete a user"""
    user_db = User.find(username)
    if not user_db:
        return Response(
            u"User {} doesn't exist".format(username), status=HTTP_404_NOT_FOUND
        )
    user_db.delete()
    return Response(u"User {} has been deleted".format(username), status=HTTP_200_OK)
Beispiel #15
0
 def list_users(self, args):
     """List all users or a specific user if the name is specified"""
     if args[ARG_NAME]:
         name = args[ARG_NAME]
         user = User.find(name)
         if user:
             user_info = user.to_dict()
             groups = ", ".join([el["name"] for el in user_info.get("groups", [])])
             if not user_info.get("ldap"):
                 print(
                     "{0.bold}User name{0.normal}: {1}".format(
                         self.terminal, user_info.get("username", name)
                     )
                 )
                 print(
                     "{0.bold}Email{0.normal}: {1}".format(
                         self.terminal, user_info.get("email", "")
                     )
                 )
                 print(
                     "{0.bold}User id{0.normal}: {1}".format(
                         self.terminal, user_info.get("uuid", "")
                     )
                 )
                 print(
                     "{0.bold}Administrator{0.normal}: {1}".format(
                         self.terminal, user_info.get("administrator", False)
                     )
                 )
                 print(
                     "{0.bold}Active{0.normal}: {1}".format(
                         self.terminal, user_info.get("active", False)
                     )
                 )
                 print("{0.bold}Groups{0.normal}: {1}".format(self.terminal, groups))
             else:
                 print(
                     "{0.bold}User name (ldap){0.normal}: {1}".format(
                         self.terminal, user_info.get("username", name)
                     )
                 )
                 print(
                     "{0.bold}Administrator{0.normal}: {1}".format(
                         self.terminal, user_info.get("administrator", False)
                     )
                 )
                 print(
                     "{0.bold}Active{0.normal}: {1}".format(
                         self.terminal, user_info.get("active", False)
                     )
                 )
                 print("{0.bold}Groups{0.normal}: {1}".format(self.terminal, groups))
         else:
             self.print_error(MSG_USER_NOT_EXIST.format(name))
     else:
         for user in User.objects.all():
             print(user.name)
Beispiel #16
0
def test_update():
    user_name = uuid.uuid4().hex
    email = uuid.uuid4().hex
    password = uuid.uuid4().hex
    administrator = True
    groups = ['grp1']
    notification_username = uuid.uuid4().hex

    # Simple create
    user = User.create(name=user_name,
                       email=email,
                       password=password,
                       administrator=administrator,
                       groups=groups)
    new_password = uuid.uuid4().hex
    new_email = uuid.uuid4().hex
    user.update(password=new_password)
    user.update(email=new_email, username=notification_username)
    user = User.find(user_name)
Beispiel #17
0
def ls_user(request, username):
    """List user info"""
    # TODO check if username is valid to test ?
    user_db = User.find(username)
    if user_db:
        return Response(user_db.to_dict(), status=HTTP_200_OK)
    else:
        return Response(
            u"User {} not found".format(username), status=HTTP_404_NOT_FOUND
        )
Beispiel #18
0
 def mk_ldap_user(self, args):
     """Create a new ldap user. Ask in the terminal for mandatory fields"""
     if not args[ARG_NAME]:
         name = input("Please enter the user's username: "******"Username {} already exists".format(name))
         return
     admin = input("Is this an administrator? [y/N] ")
     pwd = random_password(20)
     User.create(
         name=name,
         password=pwd,
         email="STORED_IN_LDAP",
         ldap=True,
         administrator=(admin.lower() in ["true", "y", "yes"]),
     )
     print(MSG_USER_CREATED.format(name))
Beispiel #19
0
def test_dict():
    user_name = uuid.uuid4().hex
    email = uuid.uuid4().hex
    password = uuid.uuid4().hex
    administrator = True
    groups = ['grp1']
    notification_username = uuid.uuid4().hex

    # Simple create
    user = User.create(name=user_name,
                       email=email,
                       password=password,
                       administrator=administrator,
                       groups=groups)
    user = User.find(user_name)

    user_dict = user.to_dict()
    assert user_dict['uuid'] == user.uuid
    assert user_dict['administrator'] == True
    user.delete()
Beispiel #20
0
def create_random_user(groups):
    user_name = uuid.uuid4().hex
    email = uuid.uuid4().hex
    password = uuid.uuid4().hex
    administrator = True

    return User.create(name=user_name,
                       email=email,
                       password=password,
                       administrator=administrator,
                       groups=groups)
Beispiel #21
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 #22
0
 def rm_user(self, args):
     """Remove a user."""
     if not args[ARG_NAME]:
         name = input(MSG_PROMPT_USER)
     else:
         name = args[ARG_NAME]
     user = User.find(name)
     if not user:
         self.print_error(MSG_USER_NOT_EXIST.format(name))
         return
     user.delete()
     print(MSG_USER_DELETED.format(name))
Beispiel #23
0
 def authenticate_credentials(self, userid, password, request=None):
     """
     Authenticate the userid and password against username and password.
     """
     cass_user = User.find(userid)
     if cass_user is None or not cass_user.is_active():
         raise exceptions.AuthenticationFailed(_("User inactive or deleted."))
     if not cass_user.authenticate(password) and not ldap_authenticate(
         cass_user.uuid, password
     ):
         raise exceptions.AuthenticationFailed(_("Invalid username/password."))
     return (cass_user, None)
def test_user_can():
    myFactory = Faker()
    content = myFactory.text()

    # Create a new resource with a random name
    do = DataObject.create(content.encode())
    resc_name = uuid.uuid4().hex
    resc = Resource.create('/',
                           resc_name,
                           url="{}{}".format(cfg.protocol_cassandra, do.uuid))

    usr1 = User.find(USR1_NAME)
    usr2 = User.find(USR2_NAME)

    # usr1 should be admin
    assert resc.user_can(usr1, "read")
    # usr2 should not be admin, on root collection, only read
    assert resc.user_can(usr2, "read")
    assert not resc.user_can(usr2, "write")

    resc.delete()
Beispiel #25
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 #26
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 #27
0
 def mk_user(self, args):
     """Create a new user. Ask in the terminal for mandatory fields"""
     if not args[ARG_NAME]:
         name = input("Please enter the user's username: "******"Username {} already exists".format(name))
         return
     admin = input("Is this an administrator? [y/N] ")
     email = ""
     while not email:
         email = input("Please enter the user's email address: ")
     pwd = ""
     while not pwd:
         pwd = getpass("Please enter the user's password: "******"true", "y", "yes"]),
     )
     print(MSG_USER_CREATED.format(name))
Beispiel #28
0
    def process_request(self, request):
        """Process a request, add the user in the cache"""

        username = request.session.get("user")
        if not username:
            return None

        # Cache the user rather than hitting the database for
        # each request.  We can also invalidate the entry if the
        # user is marked as inactive.
        user = cache.get("user_{}".format(username), None)
        if not user:
            user = User.find(username)
        request.user = user
        cache.set("user_{}".format(username), user, 60)

        return None
Beispiel #29
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 #30
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])