Exemplo n.º 1
0
    def _check_restrictions(cls):
        # If there are already users in the DB, don't bother
        if User.query.count() > 0:
            return

        if Restriction.query.count() == 0:
            if click.confirm(
                    orange('There are no permissions specified') +
                    ' - that means, that by default '
                    'users will not have access to any resources. Would you like to create '
                    'a default permission together with a default group now? (All users '
                    'would have access to every resource)',
                    default=True):
                default_group = Group(name='users')
                default_group._is_default = True
                default_group.save()

                default_restriction = Restriction(
                    name='can always use everything',
                    starts_at=datetime.utcnow(),
                    is_global=True)
                default_restriction.apply_to_group(default_group)

                click.echo(
                    green(
                        'Created a default group: {} and a permission "{}" '.
                        format(default_group.name, default_restriction.name) +
                        'allowing access to every resource '
                        'at any time.'))
            else:
                click.echo(
                    orange(
                        '[•] OK - not creating any permissions. Remember that you need to define permissions'
                        ' in order for users to be able to access the resources.'
                    ))
Exemplo n.º 2
0
def test_get_default_groups(tables, client, new_group):
    new_group.is_default = True
    new_group.save()

    another_group = Group(name='Not a default group')
    another_group.save()

    resp = client.get(ENDPOINT + '?only_default=true', headers=HEADERS)
    resp_json = json.loads(resp.data.decode('utf-8'))

    assert resp.status_code == HTTPStatus.OK
    assert len(resp_json) == 1
    assert resp_json[0]['id'] == new_group.id
Exemplo n.º 3
0
def test_set_group_as_a_default(tables, client, new_group):
    new_group.save()

    resp = client.put(ENDPOINT + '/{}'.format(new_group.id), data=json.dumps({'isDefault': True}), headers=HEADERS)

    assert resp.status_code == HTTPStatus.OK
    assert Group.get(new_group.id).is_default
Exemplo n.º 4
0
    def _add_to_default_groups(self):
        groups = Group.get_default_groups()
        for group in groups:
            group.add_user(self.new_user)

        if len(groups) > 0:
            click.echo(green('Account added to the existing default groups'))
Exemplo n.º 5
0
def update(id: GroupId,
           newValues: Dict[str, Any]) -> Tuple[Content, HttpStatusCode]:
    new_values = newValues
    allowed_fields = {'name', 'isDefault'}
    try:
        assert set(new_values.keys()).issubset(
            allowed_fields), 'invalid field is present'
        group = Group.get(id)

        for field_name, new_value in new_values.items():
            field_name = snakecase(field_name)
            assert hasattr(
                group, field_name), 'group has no {} field'.format(field_name)
            setattr(group, field_name, new_value)
        group.save()
    except NoResultFound:
        content, status = {
            'msg': GROUP['not_found']
        }, HTTPStatus.NOT_FOUND.value
    except AssertionError as e:
        content, status = {'msg': GROUP['update']['failure']['assertions'].format(reason=e)}, \
            HTTPStatus.UNPROCESSABLE_ENTITY.value
    except Exception as e:
        log.critical(e)
        content, status = {
            'msg': GENERAL['internal_error']
        }, HTTPStatus.INTERNAL_SERVER_ERROR.value
    else:
        content, status = {
            'msg': GROUP['update']['success'],
            'group': group.as_dict()
        }, HTTPStatus.OK.value
    finally:
        return content, status
Exemplo n.º 6
0
def do_create(user: Dict[str, Any]) -> Tuple[Content, HttpStatusCode]:
    try:
        new_user = User(username=user['username'],
                        email=user['email'],
                        password=user['password'],
                        roles=[Role(name='user')])
        new_user.save()

        try:
            default_groups = Group.get_default_groups()
            for group in default_groups:
                group.add_user(new_user)
        except Exception:
            log.warning(
                "User has been created, but not added to default group.")
    except AssertionError as e:
        content = {
            'msg': USER['create']['failure']['invalid'].format(reason=e)
        }
        status = 422
    except IntegrityError:
        content = {'msg': USER['create']['failure']['duplicate']}
        status = 409
    except Exception as e:
        content = {'msg': GENERAL['internal_error'] + str(e)}
        status = 500
    else:
        content = {
            'msg': USER['create']['success'],
            'user': new_user.as_dict(include_private=True)
        }
        status = 201
    finally:
        return content, status
Exemplo n.º 7
0
def delete(id: GroupId) -> Tuple[Content, HttpStatusCode]:
    try:
        group_to_destroy = Group.get(id)
        users = group_to_destroy.users
        group_to_destroy.destroy()
        for user in users:
            ReservationVerifier.update_user_reservations_statuses(
                user, have_users_permissions_increased=False)
    except AssertionError as error_message:
        content, status = {
            'msg': str(error_message)
        }, HTTPStatus.FORBIDDEN.value
    except NoResultFound:
        content, status = {
            'msg': GROUP['not_found']
        }, HTTPStatus.NOT_FOUND.value
    except Exception as e:
        content, status = {
            'msg': GENERAL['internal_error'] + str(e)
        }, HTTPStatus.INTERNAL_SERVER_ERROR.value
    else:
        content, status = {
            'msg': GROUP['delete']['success']
        }, HTTPStatus.OK.value
    finally:
        return content, status
Exemplo n.º 8
0
def test_update_group(tables, client, new_group):
    new_group.save()

    new_group_name = new_group.name + '111'
    resp = client.put(ENDPOINT + '/' + str(new_group.id), headers=HEADERS, data=json.dumps({'name': new_group_name}))
    resp_json = json.loads(resp.data.decode('utf-8'))

    assert resp.status_code == HTTPStatus.OK
    assert resp_json['group']['name'] == new_group_name
    assert Group.get(new_group.id).name == new_group_name
Exemplo n.º 9
0
def test_create_group(tables, client):
    group_name = 'TestGroup'
    data = {'name': group_name}

    resp = client.post(ENDPOINT, headers=HEADERS, data=json.dumps(data))
    resp_json = json.loads(resp.data.decode('utf-8'))

    assert resp.status_code == HTTPStatus.CREATED
    assert resp_json['group']['id'] is not None
    assert resp_json['group']['name'] == group_name
    assert Group.get(int(resp_json['group']['id'])) is not None
Exemplo n.º 10
0
def create(group: Dict[str, Any]) -> Tuple[Content, HttpStatusCode]:
    try:
        new_group = Group(
            name=group['name'],
            is_default=group['isDefault'] if 'isDefault' in group else False)
        new_group.save()
    except AssertionError as e:
        content = {
            'msg': GROUP['create']['failure']['invalid'].format(reason=e)
        }
        status = HTTPStatus.UNPROCESSABLE_ENTITY.value
    except Exception as e:
        content = {'msg': GENERAL['internal_error'] + str(e)}
        status = HTTPStatus.INTERNAL_SERVER_ERROR.value
    else:
        content = {
            'msg': GROUP['create']['success'],
            'group': new_group.as_dict()
        }
        status = HTTPStatus.CREATED.value
    finally:
        return content, status
def test_on_signup_user_gets_added_to_all_default_groups_if_there_are_more_than_one(
        tables, client, new_group):
    new_group.is_default = True
    new_group.save()

    another_default_group = Group(name='AnotherDefaultGroup', is_default=True)
    another_default_group.save()

    data = {
        'email': '*****@*****.**',
        'username': '******',
        'password': '******'
    }
    resp = client.post(ENDPOINT + '/create',
                       data=json.dumps(data),
                       headers=HEADERS)
    resp_json = json.loads(resp.data.decode('utf-8'))

    assert resp.status_code == HTTPStatus.CREATED
    assert len(resp_json['user']['groups']) == 2
    assert resp_json['user']['groups'][0]['id'] == new_group.id
    assert resp_json['user']['groups'][1]['id'] == another_default_group.id
    assert new_group in User.get(resp_json['user']['id']).groups
    assert another_default_group in User.get(resp_json['user']['id']).groups
Exemplo n.º 12
0
def get_selected(user_id: Optional[UserId], group_id: Optional[GroupId], resource_id: Optional[ResourceId],
                 schedule_id: Optional[ScheduleId], include_user_groups: Optional[bool] = False) \
        -> Tuple[Union[List[Any], Content], HttpStatusCode]:
    try:
        # If a specific group is selected then groups are not included in the restriction information in response
        # The same applies to users and resources
        include_groups = group_id is None
        include_users = user_id is None
        include_resources = schedule_id is None

        restrictions = []  # type: List[Restriction]
        if user_id is not None:
            user = User.get(user_id)
            restrictions.extend(
                user.get_restrictions(include_group=include_user_groups))
        if group_id is not None:
            group = Group.get(group_id)
            restrictions.extend(group.get_restrictions())
        if resource_id is not None:
            resource = Resource.get(resource_id)
            restrictions.extend(resource.get_restrictions())
        if schedule_id is not None:
            schedule = RestrictionSchedule.get(schedule_id)
            restrictions.extend(schedule.restrictions)

        # Take unique restrictions
        result = set(restrictions)
    except NoResultFound as e:
        log.warning(e)
        content, status = {
            'msg': GENERAL['bad_request']
        }, HTTPStatus.BAD_REQUEST.value
    except Exception as e:
        log.critical(e)
        content, status = {
            'msg': GENERAL['internal_error']
        }, HTTPStatus.INTERNAL_SERVER_ERROR.value
    else:
        content = [
            restriction.as_dict(
                include_groups=include_groups,
                include_users=include_users,  # type: ignore
                include_resources=include_resources) for restriction in result
        ]
        status = HTTPStatus.OK.value
    finally:
        return content, status
Exemplo n.º 13
0
def test_more_than_one_default_group(tables, new_group):
    new_group.is_default = True
    new_group.save()

    another_group = Group(name='AnotherGroup')
    another_group.is_default = True
    another_group.save()

    defaults = Group.get_default_groups()
    assert new_group in defaults
    assert another_group in defaults
Exemplo n.º 14
0
def remove_from_group(restriction_id: RestrictionId,
                      group_id: GroupId) -> Tuple[Content, HttpStatusCode]:
    restriction = None
    try:
        restriction = Restriction.get(restriction_id)
        group = Group.get(group_id)
        restriction.remove_from_group(group)
        for user in group.users:
            ReservationVerifier.update_user_reservations_statuses(
                user, have_users_permissions_increased=False)
    except NoResultFound:
        if restriction is None:
            content, status = {
                'msg': RESTRICTION['not_found']
            }, HTTPStatus.NOT_FOUND.value
        else:
            content, status = {
                'msg': GENERAL['not_found']
            }, HTTPStatus.NOT_FOUND.value
    except InvalidRequestException:
        content, status = {
            'msg': RESTRICTION['groups']['remove']['failure']['not_found']
        }, HTTPStatus.NOT_FOUND.value
    except AssertionError as e:
        content, status = {'msg': RESTRICTION['groups']['remove']['failure']['assertions'].format(reason=e)}, \
            HTTPStatus.UNPROCESSABLE_ENTITY.value
    except Exception as e:
        log.critical(e)
        content, status = {
            'msg': GENERAL['internal_error']
        }, HTTPStatus.INTERNAL_SERVER_ERROR.value
    else:
        content, status = {
            'msg':
            RESTRICTION['groups']['remove']['success'],
            'restriction':
            restriction.as_dict(include_groups=True,
                                include_users=True,
                                include_resources=True)
        }, HTTPStatus.OK.value
    finally:
        return content, status
Exemplo n.º 15
0
def get_by_id(id: GroupId) -> Tuple[Content, HttpStatusCode]:
    try:
        group = Group.get(id)
    except NoResultFound as e:
        log.warning(e)
        content, status = {
            'msg': GROUP['not_found']
        }, HTTPStatus.NOT_FOUND.value
    except Exception as e:
        log.critical(e)
        content, status = {
            'msg': GENERAL['internal_error']
        }, HTTPStatus.INTERNAL_SERVER_ERROR.value
    else:
        content, status = {
            'msg': GROUP['get']['success'],
            'group': group.as_dict()
        }, HTTPStatus.OK.value
    finally:
        return content, status
Exemplo n.º 16
0
def remove_user(group_id: GroupId,
                user_id: UserId) -> Tuple[Content, HttpStatusCode]:
    group = None
    try:
        group = Group.get(group_id)
        user = User.get(user_id)
        group.remove_user(user)
        ReservationVerifier.update_user_reservations_statuses(
            user, have_users_permissions_increased=False)
    except NoResultFound:
        if group is None:
            content, status = {
                'msg': GROUP['not_found']
            }, HTTPStatus.NOT_FOUND.value
        else:
            content, status = {
                'msg': USER['not_found']
            }, HTTPStatus.NOT_FOUND.value
    except InvalidRequestException:
        content, status = {
            'msg': GROUP['users']['remove']['failure']['not_found']
        }, HTTPStatus.NOT_FOUND.value
    except AssertionError as e:
        content, status = {'msg': GROUP['users']['remove']['failure']['assertions'].format(reason=e)}, \
            HTTPStatus.UNPROCESSABLE_ENTITY.value
    except Exception as e:
        log.critical(e)
        content, status = {
            'msg': GENERAL['internal_error']
        }, HTTPStatus.INTERNAL_SERVER_ERROR.value
    else:
        content, status = {
            'msg': GROUP['users']['remove']['success'],
            'group': group.as_dict()
        }, HTTPStatus.OK.value
    finally:
        return content, status
Exemplo n.º 17
0
def new_group_with_member(new_user):
    group = Group(name='TestGroup1')
    group.save()
    group.add_user(new_user)
    return group
Exemplo n.º 18
0
def new_group():
    return Group(name='TestGroup1')
Exemplo n.º 19
0
def test_group_creation(tables):
    new_group = Group(name='test').save()
    assert new_group.id is not None
Exemplo n.º 20
0
def test_get_default_without_default_group(tables, new_group):
    new_group.save()

    assert len(Group.get_default_groups()) == 0
Exemplo n.º 21
0
def test_get_default_group(tables, new_group):
    new_group.is_default = True
    new_group.save()

    assert new_group in Group.get_default_groups()
Exemplo n.º 22
0
def test_marking_group_as_a_default(tables, new_group):
    new_group.is_default = True
    new_group.save()

    assert Group.get(new_group.id).is_default
    assert new_group in Group.get_default_groups()
Exemplo n.º 23
0
def get(only_default: bool = False) -> Tuple[List[Any], HttpStatusCode]:
    if only_default:
        groups = Group.get_default_groups()
    else:
        groups = Group.all()
    return [group.as_dict() for group in groups], HTTPStatus.OK.value