Example #1
0
def groups_resource_permissions_list(request):
    """
    Get list of permissions assigned to specific resources
    """
    group = GroupService.by_id(request.matchdict.get("group_id"))
    if not group:
        return HTTPNotFound()
    return [
        permission_tuple_to_dict(perm)
        for perm in GroupService.resources_with_possible_perms(group)
    ]
Example #2
0
def groups_users_add(request):
    """
    Get list of permissions assigned to specific resources
    """
    group = GroupService.by_id(request.matchdict.get("group_id"))
    user = UserService.by_user_name(request.unsafe_json_body.get("user_name"))
    if not user:
        user = UserService.by_email(request.unsafe_json_body.get("user_name"))

    if not group or not user:
        return HTTPNotFound()
    if user not in group.users:
        group.users.append(user)
        group.member_count = group.users_dynamic.count()
    props = [
        "user_name",
        "id",
        "first_name",
        "last_name",
        "email",
        "last_login_date",
        "status",
    ]
    u_dict = user.get_dict(include_keys=props)
    u_dict["gravatar_url"] = UserService.gravatar_url(user, s=20)
    return u_dict
Example #3
0
def groups_DELETE(request):
    """
    Removes a groups permanently from db
    """
    msg = _("You cannot remove administrator group from the system")
    group = GroupService.by_id(request.matchdict.get("group_id"))
    if group:
        if group.id == 1:
            request.session.flash(msg, "warning")
        else:
            DBSession.delete(group)
            request.session.flash(_("Group removed"))
            return True
    request.response.status = 422
    return False
Example #4
0
def groups_users_remove(request):
    """
    Get list of permissions assigned to specific resources
    """
    group = GroupService.by_id(request.matchdict.get("group_id"))
    user = UserService.by_user_name(request.GET.get("user_name"))
    if not group or not user:
        return HTTPNotFound()
    if len(group.users) > 1:
        group.users.remove(user)
        msg = "User removed from group"
        request.session.flash(msg)
        group.member_count = group.users_dynamic.count()
        return True
    msg = "Administrator group needs to contain at least one user"
    request.session.flash(msg, "warning")
    return False
Example #5
0
def group_update(request):
    """
    Updates group object
    """
    group = GroupService.by_id(request.matchdict.get("group_id"))
    if not group:
        return HTTPNotFound()

    if request.method == "PATCH":
        form = forms.GroupCreateForm(MultiDict(request.unsafe_json_body),
                                     csrf_context=request)
        form._modified_group = group
        if form.validate():
            form.populate_obj(group)
        else:
            return HTTPUnprocessableEntity(body=form.errors_json)
    return group.get_dict(include_perms=True)
Example #6
0
def groups_users_list(request):
    """
    Get list of permissions assigned to specific resources
    """
    group = GroupService.by_id(request.matchdict.get('group_id'))
    if not group:
        return HTTPNotFound()
    props = [
        'user_name', 'id', 'first_name', 'last_name', 'email',
        'last_login_date', 'status'
    ]
    users_dicts = []
    for user in group.users:
        u_dict = user.get_dict(include_keys=props)
        u_dict['gravatar_url'] = user.gravatar_url(s=20)
        users_dicts.append(u_dict)
    return users_dicts
Example #7
0
def groups_users_add(request):
    """
    Get list of permissions assigned to specific resources
    """
    group = GroupService.by_id(request.matchdict.get('group_id'))
    user = User.by_user_name(request.unsafe_json_body.get('user_name'))
    if not user:
        user = User.by_email(request.unsafe_json_body.get('user_name'))

    if not group or not user:
        return HTTPNotFound()
    if user not in group.users:
        group.users.append(user)
        group.member_count = group.users_dynamic.count()
    props = [
        'user_name', 'id', 'first_name', 'last_name', 'email',
        'last_login_date', 'status'
    ]
    u_dict = user.get_dict(include_keys=props)
    u_dict['gravatar_url'] = user.gravatar_url(s=20)
    return u_dict
Example #8
0
def groups_users_list(request):
    """
    Get list of permissions assigned to specific resources
    """
    group = GroupService.by_id(request.matchdict.get("group_id"))
    if not group:
        return HTTPNotFound()
    props = [
        "user_name",
        "id",
        "first_name",
        "last_name",
        "email",
        "last_login_date",
        "status",
    ]
    users_dicts = []
    for user in group.users:
        u_dict = user.get_dict(include_keys=props)
        u_dict["gravatar_url"] = UserService.gravatar_url(user, s=20)
        users_dicts.append(u_dict)
    return users_dicts
Example #9
0
def group_resource_permission_delete(request):
    """
    Removes group permission from specific resource
    """
    form = forms.ReactorForm(request.POST, csrf_context=request)
    form.validate()
    resource = request.context.resource
    group = GroupService.by_id(request.GET.get('group_id'))
    if not group:
        return False

    for perm_name in request.GET.getall('permissions'):
        permission = GroupResourcePermissionService.by_resource_group_and_perm(
            group.id, perm_name, resource.resource_id)
        resource.group_permissions.remove(permission)
    DBSession.flush()
    perm_tuples = resource.groups_for_perm(ANY_PERMISSION,
                                           limit_group_permissions=True,
                                           group_ids=[group.id])
    perms = [p.perm_name for p in perm_tuples if p.type == 'group']
    result = {'group': group.get_dict(), 'permissions': list(set(perms))}
    return result
Example #10
0
def group_resource_permission_create(request):
    """
    Set new permissions for group for a resource
    """
    resource = request.context.resource
    group = GroupService.by_id(request.unsafe_json_body.get("group_id"))
    if not group:
        return False

    for perm_name in request.unsafe_json_body.get("permissions", []):
        permission = GroupResourcePermissionService.by_resource_group_and_perm(
            group.id, perm_name, resource.resource_id
        )
        if not permission:
            permission = GroupResourcePermission(perm_name=perm_name, group_id=group.id)
            resource.group_permissions.append(permission)
    DBSession.flush()
    perm_tuples = ResourceService.groups_for_perm(
        resource, ANY_PERMISSION, limit_group_permissions=True, group_ids=[group.id]
    )
    perms = [p.perm_name for p in perm_tuples if p.type == "group"]
    result = {"group": group.get_dict(), "permissions": list(set(perms))}
    return result
Example #11
0
def main():
    parser = argparse.ArgumentParser(
        description="Populate AppEnlight database", add_help=False
    )
    parser.add_argument(
        "-c", "--config", required=True, help="Configuration ini file of application"
    )
    parser.add_argument("--username", default=None, help="User  to create")
    parser.add_argument("--password", default=None, help="Password for created user")
    parser.add_argument("--email", default=None, help="Email for created user")
    parser.add_argument(
        "--auth-token", default=None, help="Auth token for created user"
    )
    args = parser.parse_args()
    config_uri = args.config

    setup_logging(config_uri)
    env = bootstrap(config_uri)
    request = env["request"]
    with get_current_request().tm:
        group = GroupService.by_id(1)
        if not group:
            group = Group(
                id=1,
                group_name="Administrators",
                description="Top level permission owners",
            )
            DBSession.add(group)
            permission = GroupPermission(perm_name="root_administration")
            group.permissions.append(permission)

    create_user = True if args.username else None
    while create_user is None:
        response = input("Do you want to create a new admin? (n)\n").lower()

        if is_yes(response or "n"):
            create_user = True
        elif is_no(response or "n"):
            create_user = False

    if create_user:
        csrf_token = request.session.get_csrf_token()
        user_name = args.username
        print("*********************************************************")
        while user_name is None:
            response = input("What is the username of new admin?\n")
            form = UserRegisterForm(
                user_name=response, csrf_token=csrf_token, csrf_context=request
            )
            form.validate()
            if form.user_name.errors:
                print(form.user_name.errors[0])
            else:
                user_name = response
                print('The admin username is "{}"\n'.format(user_name))
        print("*********************************************************")
        email = args.email
        while email is None:
            response = input("What is the email of admin account?\n")
            form = UserRegisterForm(
                email=response, csrf_token=csrf_token, csrf_context=request
            )
            form.validate()
            if form.email.errors:
                print(form.email.errors[0])
            else:
                email = response
                print('The admin email is "{}"\n'.format(email))
        print("*********************************************************")
        user_password = args.password
        confirmed_password = args.password
        while user_password is None or confirmed_password is None:
            response = getpass.getpass("What is the password for admin account?\n")
            form = UserRegisterForm(
                user_password=response, csrf_token=csrf_token, csrf_context=request
            )
            form.validate()
            if form.user_password.errors:
                print(form.user_password.errors[0])
            else:
                user_password = response

            response = getpass.getpass("Please confirm the password.\n")
            if user_password == response:
                confirmed_password = response
            else:
                print("Passwords do not match. Please try again")
        print("*********************************************************")

    with get_current_request().tm:
        if create_user:
            group = GroupService.by_id(1)
            user = User(user_name=user_name, email=email, status=1)
            UserService.regenerate_security_code(user)
            UserService.set_password(user, user_password)
            DBSession.add(user)
            token = AuthToken(description="Uptime monitoring token")
            if args.auth_token:
                token.token = args.auth_token
            user.auth_tokens.append(token)
            group.users.append(user)
            print("USER CREATED")
            print(json.dumps(user.get_dict()))
            print("*********************************************************")
            print("AUTH TOKEN")
            print(json.dumps(user.auth_tokens[0].get_dict()))