def delete(id: RestrictionId) -> Tuple[Content, HttpStatusCode]: try: restriction_to_destroy = Restriction.get(id) users = restriction_to_destroy.get_all_affected_users() restriction_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': RESTRICTION['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': RESTRICTION['delete']['success'] }, HTTPStatus.OK.value finally: return content, status
def create(reservation: Dict[str, Any]) -> Tuple[Content, HttpStatusCode]: try: new_reservation = Reservation(title=reservation['title'], description=reservation['description'], resource_id=reservation['resourceId'], user_id=reservation['userId'], start=reservation['start'], end=reservation['end']) user = User.get(get_jwt_identity()) if (is_admin() or __is_reservation_owner(new_reservation)) \ and ReservationVerifier.is_reservation_allowed(user, new_reservation): new_reservation.save() content = { 'msg': RESERVATION['create']['success'], 'reservation': new_reservation.as_dict() } status = 201 else: content = {'msg': RESERVATION['create']['failure']['forbidden']} status = 403 except AssertionError as e: content = { 'msg': RESERVATION['create']['failure']['invalid'].format(reason=e) } status = 422 except Exception as e: print(e) content = {'msg': GENERAL['internal_error'] + str(e)} status = 500 finally: return content, status
def add_schedule(restriction_id: RestrictionId, schedule_id: ScheduleId) -> Tuple[Content, HttpStatusCode]: restriction = None try: restriction = Restriction.get(restriction_id) schedule = RestrictionSchedule.get(schedule_id) restriction.add_schedule(schedule) have_users_permissions_increased = len( restriction.schedules) > 1 # if added another schedule for user in restriction.get_all_affected_users(): ReservationVerifier.update_user_reservations_statuses( user, have_users_permissions_increased) except NoResultFound: if restriction is None: content, status = { 'msg': RESTRICTION['not_found'] }, HTTPStatus.NOT_FOUND.value else: content, status = { 'msg': SCHEDULE['not_found'] }, HTTPStatus.NOT_FOUND.value except InvalidRequestException: content, status = { 'msg': RESTRICTION['schedules']['add']['failure']['duplicate'] }, HTTPStatus.CONFLICT.value except AssertionError as e: content, status = {'msg': RESTRICTION['schedules']['add']['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['schedules']['add']['success'], 'restriction': restriction.as_dict(include_groups=True, include_users=True, include_resources=True) }, HTTPStatus.OK.value finally: return content, status
def delete(id: ScheduleId) -> Tuple[Content, HttpStatusCode]: try: schedule_to_destroy = RestrictionSchedule.get(id) restrictions = schedule_to_destroy.restrictions schedule_to_destroy.destroy() for restriction in restrictions: have_users_permissions_increased = len(restriction.schedules) == 0 # if deleted last schedule for user in restriction.get_all_affected_users(): ReservationVerifier.update_user_reservations_statuses(user, have_users_permissions_increased) except AssertionError as error_message: content, status = {'msg': str(error_message)}, HTTPStatus.FORBIDDEN.value except NoResultFound: content, status = {'msg': SCHEDULE['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': SCHEDULE['delete']['success']}, HTTPStatus.OK.value finally: return content, status
def update(id: RestrictionId, newValues: Dict[str, Any]) -> Tuple[Content, HttpStatusCode]: new_values = newValues allowed_fields = {'name', 'startsAt', 'endsAt', 'isGlobal'} try: assert set(new_values.keys()).issubset( allowed_fields), 'invalid field is present' restriction = Restriction.get(id) for field_name, new_value in new_values.items(): field_name = snakecase(field_name) assert (field_name is not None) and hasattr(restriction, field_name), \ 'restriction has no {} field'.format(field_name) setattr(restriction, field_name, new_value) restriction.save() for user in restriction.get_all_affected_users(): ReservationVerifier.update_user_reservations_statuses( user, have_users_permissions_increased=True) ReservationVerifier.update_user_reservations_statuses( user, have_users_permissions_increased=False) except NoResultFound: content, status = { 'msg': RESTRICTION['not_found'] }, HTTPStatus.NOT_FOUND.value except AssertionError as e: content, status = {'msg': RESTRICTION['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': RESTRICTION['update']['success'], 'restriction': restriction.as_dict(include_groups=True, include_users=True, include_resources=True) }, HTTPStatus.OK.value finally: return content, status
def remove_from_resources_by_hostname( restriction_id: RestrictionId, hostname: str) -> Tuple[Content, HttpStatusCode]: restriction = None try: restriction = Restriction.get(restriction_id) resources = Resource.get_by_hostname(hostname) if resources: restriction.remove_from_resources(resources) for user in restriction.get_all_affected_users(): ReservationVerifier.update_user_reservations_statuses( user, have_users_permissions_increased=False) else: raise NoResultFound except NoResultFound: if restriction is None: content, status = { 'msg': RESTRICTION['not_found'] }, HTTPStatus.NOT_FOUND.value else: content, status = { 'msg': NODES['hostname']['not_found'] }, HTTPStatus.NOT_FOUND.value except AssertionError as e: content, status = {'msg': RESTRICTION['hosts']['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['hosts']['remove']['success'], 'restriction': restriction.as_dict(include_groups=True, include_users=True, include_resources=True) }, HTTPStatus.OK.value finally: return content, status
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
def apply_to_user(restriction_id: RestrictionId, user_id: UserId) -> Tuple[Content, HttpStatusCode]: restriction = None try: restriction = Restriction.get(restriction_id) user = User.get(user_id) restriction.apply_to_user(user) ReservationVerifier.update_user_reservations_statuses( user, have_users_permissions_increased=True) except NoResultFound: if restriction is None: content, status = { 'msg': RESTRICTION['not_found'] }, HTTPStatus.NOT_FOUND.value else: content, status = { 'msg': USER['not_found'] }, HTTPStatus.NOT_FOUND.value except InvalidRequestException: content, status = { 'msg': RESTRICTION['users']['apply']['failure']['duplicate'] }, HTTPStatus.CONFLICT.value except AssertionError as e: content, status = {'msg': RESTRICTION['users']['apply']['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['users']['apply']['success'], 'restriction': restriction.as_dict(include_groups=True, include_users=True, include_resources=True) }, HTTPStatus.OK.value finally: return content, status
def update(id: ReservationId, newValues: Dict[str, Any]) -> Tuple[Content, HttpStatusCode]: new_values = newValues allowed_fields = {'title', 'description', 'resourceId', 'end'} try: reservation = Reservation.get(id) if reservation.end < datetime.utcnow() and not is_admin(): raise ForbiddenException('reservation already finished') if reservation.start > datetime.utcnow() or is_admin(): allowed_fields.add('start') if not set(new_values.keys()).issubset(allowed_fields): raise ForbiddenException('invalid field is present') for field_name, new_value in new_values.items(): field_name = snakecase(field_name) assert (field_name is not None) and hasattr(reservation, field_name), \ 'reservation has no {} field'.format(field_name) setattr(reservation, field_name, new_value) user = User.get(get_jwt_identity()) if not (is_admin() or __is_reservation_owner(reservation)) or not \ ReservationVerifier.is_reservation_allowed(user, reservation): raise ForbiddenException("reservation not allowed") reservation.is_cancelled = False reservation.save() content, status = { 'msg': RESERVATION['update']['success'], 'reservation': reservation.as_dict() }, 201 except ForbiddenException as fe: content, status = { 'msg': RESERVATION['update']['failure']['forbidden'].format(reason=fe) }, 403 except NoResultFound: content, status = {'msg': RESERVATION['not_found']}, 404 except AssertionError as e: content, status = { 'msg': RESERVATION['update']['failure']['assertions'].format(reason=e) }, 422 except Exception as e: log.critical(e) content, status = {'msg': GENERAL['internal_error'] + str(e)}, 500 finally: return content, status
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
def update(id, newValues: Dict[str, Any]) -> Tuple[Content, HttpStatusCode]: new_values = newValues allowed_fields = {'scheduleDays', 'hourStart', 'hourEnd'} try: assert set(new_values.keys()).issubset(allowed_fields), 'invalid field is present' schedule = RestrictionSchedule.get(id) for field_name, new_value in new_values.items(): if field_name == 'scheduleDays': new_value = [Weekday[day] for day in new_value] if field_name in ['hourStart', 'hourEnd']: new_value = datetime.strptime(new_value, "%H:%M").time() field_name = snakecase(field_name) assert (field_name is not None) and hasattr(schedule, field_name), \ 'schedule has no {} field'.format(field_name) setattr(schedule, field_name, new_value) schedule.save() for restriction in schedule.restrictions: for user in restriction.get_all_affected_users(): ReservationVerifier.update_user_reservations_statuses(user, have_users_permissions_increased=True) ReservationVerifier.update_user_reservations_statuses(user, have_users_permissions_increased=False) except NoResultFound: content, status = {'msg': SCHEDULE['not_found']}, HTTPStatus.NOT_FOUND.value except KeyError: # Invalid day content, status = {'msg': GENERAL['bad_request']}, HTTPStatus.UNPROCESSABLE_ENTITY.value except AssertionError as e: content, status = {'msg': SCHEDULE['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': SCHEDULE['update']['success'], 'schedule': schedule.as_dict()}, HTTPStatus.OK.value finally: return content, status
def create(reservation: Dict[str, Any]) -> Tuple[Content, HttpStatusCode]: try: new_reservation = Reservation(title=reservation['title'], description=reservation['description'], resource_id=reservation['resourceId'], user_id=reservation['userId'], start=reservation['start'], end=reservation['end']) if not is_admin() and not __is_reservation_owner(new_reservation): raise ForbiddenException( "Cannot reserve resources in another user's name") reservation_start = DateUtils.try_parse_string(new_reservation.start) request_time_limit = timedelta(minutes=1) starts_in_the_future = (reservation_start + request_time_limit) >= datetime.utcnow() if not is_admin() and not starts_in_the_future: raise ForbiddenException("Cannot reserve resources in the past") user = User.get(get_jwt_identity()) if not ReservationVerifier.is_reservation_allowed( user, new_reservation): raise ForbiddenException("Reservation not allowed") new_reservation.save() content = { 'msg': RESERVATION['create']['success'], 'reservation': new_reservation.as_dict() } status = 201 except ForbiddenException as e: content = { 'msg': RESERVATION['create']['failure']['forbidden'].format(reason=e) } status = 403 except AssertionError as e: content = { 'msg': RESERVATION['create']['failure']['invalid'].format(reason=e) } status = 422 except Exception as e: print(e) content = {'msg': GENERAL['internal_error'] + str(e)} status = 500 finally: return content, status