Ejemplo n.º 1
0
    def post(self):
        """
        ---
        summary: Request a new user account
        description: Creates a new pending user account.
        tags:
            - auth
        requestBody:
            description: User basic information
            content:
              application/json:
                schema: AuthRegisterRequestSchema
        responses:
            200:
                description: User login on successful registration.
                content:
                  application/json:
                    schema: UserSuccessResponseSchema
            400:
                description: When request body is invalid.
            403:
                description: When registration feature is disabled or reCAPTCHA token wasn't valid.
            409:
                description: When user login or group name already exists.
            500:
                description: When ReCAPTCHA verification service is unavailable.
        """
        if not app_config.mwdb.enable_registration:
            raise Forbidden("User registration is not enabled.")

        schema = AuthRegisterRequestSchema()
        obj = loads_schema(request.get_data(as_text=True), schema)

        login = obj["login"]

        if db.session.query(exists().where(User.login == login)).scalar():
            raise Conflict("Name already exists")

        if db.session.query(exists().where(Group.name == login)).scalar():
            raise Conflict("Name already exists")

        verify_recaptcha(obj.get("recaptcha"))

        user = User.create(login,
                           obj["email"],
                           obj["additional_info"],
                           pending=True)

        try:
            send_email_notification("pending",
                                    "Pending registration in MWDB",
                                    user.email,
                                    base_url=app_config.mwdb.base_url,
                                    login=user.login)
        except MailError:
            logger.exception("Can't send e-mail notification")

        logger.info('User registered', extra={'user': user.login})
        schema = UserSuccessResponseSchema()
        return schema.dump({"login": user.login})
Ejemplo n.º 2
0
def join_lobby(db_session, user_session, lobby_code):
    user = db_session.query(User).get(user_session["user_id"])

    if user.lobby is not None:
        raise Conflict("User is already in a lobby.")

    lobby = (
        db_session.query(Lobby)
        .filter(Lobby.code == lobby_code)
        .filter(Lobby.state == LOBBY_CONSTANTS["state"]["ready"])
    ).one_or_none()

    if lobby is None:
        raise NotFound(
            f"No lobby with code {lobby_code} was found."
        )

    if lobby.is_at_capacity():
        raise Conflict(
            f"Max number of {lobby.capacity} players exceeded."
        )

    user.lobby = lobby
    user_session["lobby_id"] = lobby.id

    return {
        "state": lobby.get_state(),
        "players": [player.name for player in lobby.players],
    }
Ejemplo n.º 3
0
def batch_tallies(election: Election) -> BatchTallies:
    # We only support one contest for batch audits
    assert len(list(election.contests)) == 1
    contest = list(election.contests)[0]

    # Validate the batch tallies files. We can't do this validation when they
    # are uploaded because we need all of the jurisdictions' files.
    total_votes_by_choice: Dict[str, int] = defaultdict(int)
    for jurisdiction in contest.jurisdictions:
        batch_tallies = typing_cast(BatchTallies, jurisdiction.batch_tallies)
        if batch_tallies is None:
            raise Conflict(
                "Some jurisdictions haven't uploaded their batch tallies files yet."
            )
        for tally in batch_tallies.values():
            for choice_id, votes in tally[contest.id].items():
                total_votes_by_choice[choice_id] += votes

    for choice in contest.choices:
        if total_votes_by_choice[choice.id] > choice.num_votes:
            raise Conflict(
                f"Total votes in batch tallies files for contest choice {choice.name}"
                f" ({total_votes_by_choice[choice.id]}) is greater than the"
                f" reported number of votes for that choice ({choice.num_votes})."
            )

    # Key each batch by jurisdiction name and batch name since batch names
    # are only guaranteed unique within a jurisdiction
    return {
        (jurisdiction.name, batch_name): tally
        for jurisdiction in contest.jurisdictions
        for batch_name, tally in jurisdiction.batch_tallies.items()  # type: ignore
    }
Ejemplo n.º 4
0
def validate_new_election(election: JSONDict):
    validate(election, ELECTION_SCHEMA)

    if Election.query.filter_by(
            audit_name=election["auditName"],
            organization_id=election["organizationId"]).first():
        raise Conflict(
            f"An audit with name '{election['auditName']}' already exists within your organization"
        )

    valid_math_types_for_audit_type = {
        AuditType.BALLOT_POLLING: [AuditMathType.BRAVO, AuditMathType.MINERVA],
        AuditType.BALLOT_COMPARISON: [AuditMathType.SUPERSIMPLE],
        AuditType.BATCH_COMPARISON: [AuditMathType.MACRO],
    }

    if (election["auditMathType"]
            not in valid_math_types_for_audit_type[election["auditType"]]):
        raise Conflict(
            f"Audit math type '{election['auditMathType']}' cannot be used with audit type '{election['auditType']}'"
        )

    # For now, disable Minerva audit math in production
    if FLASK_ENV == "production" and election[
            "auditMathType"] == AuditMathType.MINERVA:
        raise BadRequest("Invalid audit math type")
Ejemplo n.º 5
0
    def create(self, user: auth.User, **kwargs) -> int:
        if self._form is not None:
            # This is indeed an internal server error.
            raise Exception("instantiated form can't create other")

        self._validate_kwargs(**kwargs)

        creation_kwargs = self._convert_kwarg_values(**kwargs)

        with base.db.atomic() as transaction:
            try:
                try:
                    self._form = self._db_model.create(
                        user=user, type=self._structure_and_function_type)
                except peewee.IntegrityError:
                    raise Conflict("form already exists")

                _measures = list()
                for measure in creation_kwargs["measures"]:
                    try:
                        _measure = forms.StructureAndFunctionMeasure.create(
                            structure_and_function=self._form, **measure)
                    except peewee.IntegrityError:
                        raise Conflict("form measure already exists")
                    _measures.append(_measure)
                self._measures = _measures
            except Exception:
                transaction.rollback()
                raise

        return self._form.id
Ejemplo n.º 6
0
 def validate_numbers(self, data, **kwargs):
     if data.get("password") is not None and \
             data.get("confirm_password") is None:
         raise Conflict(
             description='You need to enter password confirmation')
     if data.get("password") is None and \
             data.get("confirm_password") is not None:
         raise Conflict(description='You need to enter password first')
Ejemplo n.º 7
0
 def validate_numbers(self, data, **kwargs):
     if data.get("end_date") < data.get("start_date"):
         raise Conflict(description='End date is before ' \
                                    'start date')
     if data.get('free_places') < 0:
         raise Conflict(description='Free places must be positive number')
     if data.get('price') < 0:
         raise Conflict(description='Price must be positive value')
Ejemplo n.º 8
0
 def _set_parent_folder(cls, folder, parent_id):
     parent = cls.get(parent_id)
     if parent is folder:
         raise Conflict("Cannot move folder to itself")
     for grand_parent in parent.iter_parents():
         if grand_parent is folder:
             raise Conflict("Cannot move folder to a subfolder of itself")
     folder.parent = parent
Ejemplo n.º 9
0
def validate_offline_results(
    election: Election, jurisdiction: Jurisdiction, round: Round, results: JSONDict
):
    if election.online:
        raise Conflict("Cannot record offline results for online audit.")

    current_round = get_current_round(election)
    if not current_round or round.id != current_round.id:
        raise Conflict(f"Round {round.round_num} is not the current round")

    num_audit_boards = AuditBoard.query.filter_by(
        jurisdiction_id=jurisdiction.id, round_id=round.id
    ).count()
    if num_audit_boards == 0:
        raise Conflict("Must set up audit boards before recording results")

    validate(results, OFFLINE_RESULTS_SCHEMA)

    contest_ids = {c.id for c in jurisdiction.contests}
    if set(results.keys()) != contest_ids:
        raise BadRequest("Invalid contest ids")

    choices_by_contest = dict(
        ContestChoice.query.filter(ContestChoice.contest_id.in_(contest_ids))
        .group_by(ContestChoice.contest_id)
        .values(ContestChoice.contest_id, func.array_agg(ContestChoice.id))
    )
    for contest_id, results_by_choice in results.items():
        if set(results_by_choice.keys()) != set(choices_by_contest[contest_id]):
            raise BadRequest(f"Invalid choice ids for contest {contest_id}")

    ballot_draws_by_contest = dict(
        SampledBallot.query.join(Batch)
        .filter_by(jurisdiction_id=jurisdiction.id)
        .join(SampledBallotDraw)
        .filter_by(round_id=current_round.id)
        .group_by(SampledBallotDraw.contest_id)
        .values(SampledBallotDraw.contest_id, func.count())
    )
    ballots_sampled = (
        SampledBallot.query.join(Batch)
        .filter_by(jurisdiction_id=jurisdiction.id)
        .count()
    )
    for contest in jurisdiction.contests:
        num_ballots = (
            ballot_draws_by_contest.get(contest.id, 0)
            if contest.is_targeted
            else ballots_sampled
        )
        total_results = sum(results[contest.id].values())
        allowed_results = num_ballots * contest.votes_allowed
        if total_results > allowed_results:
            raise BadRequest(
                f"Total results for contest {contest.name} should not exceed"
                f" {allowed_results} - the number of sampled ballots ({num_ballots})"
                f" times the number of votes allowed ({contest.votes_allowed}).",
            )
Ejemplo n.º 10
0
 def _check_if_date_is_invalid(first_date, second_date, flag):
     if first_date > second_date and flag:
         raise Conflict(
             description='Start date is in the past'
         )
     elif first_date > second_date:
         raise Conflict(
             description='Start date is after end date'
         )
Ejemplo n.º 11
0
 def _check_if_number_is_positive(number, flag):
     if number < 0 and flag:
         raise Conflict(
             description='Free places must be positive value'
         )
     elif number < 0:
         raise Conflict(
             description='Price must be positive value'
         )
Ejemplo n.º 12
0
def route_add_division_machine_player(division_id,division_machine_id,player_id):            
    db = db_util.app_db_handle(current_app)
    tables = db_util.app_db_tables(current_app)                            
    division_machine = fetch_entity(tables.DivisionMachine,division_machine_id)        
    player = fetch_entity(tables.Player,player_id)
    if division_machine.division.active is False:
        raise Conflict("Division is not active.")                
    if division_machine.removed is True:
        raise Conflict("Machine is not active.  You have been very naughty.")        
    if player.active is False:
        raise Conflict('Player is not active.  Please see the front desk.')        
    if division_machine.player_id or division_machine.team_id:
        raise Conflict('Machine is already being played')
    if check_player_team_can_start_game(current_app,division_machine,player) is False:
        raise BadRequest('Player can not start game - either no tickets or already on another machine')
    if len(player.teams) > 0:
        if tables.DivisionMachine.query.filter_by(team_id=player.teams[0].team_id).first():            
            raise BadRequest('Player can not start game - his team is playing on another machine')        
    set_token_start_time(current_app,player,division_machine,commit=False)    
    create_audit_log_ex(current_app, "Game Started",
                        user_id=current_user.user_id,
                        player_id=player.player_id,
                        division_machine_id=division_machine.division_machine_id,                        
                        commit=False)

    division_machine.player_id=player.player_id
    ##db.session.commit()
    queue = tables.Queue.query.filter_by(player_id=player.player_id).first()
    players_to_alert = []
    players_in_other_queue = []
    if queue:
        players_to_alert = get_player_list_to_notify(player.player_id,queue.division_machine)
        players_in_other_queue = get_players_in_queue_after_player(player.player_id)
    removed_queue = remove_player_from_queue(current_app,player,commit=True)
    if removed_queue and removed_queue is not False:
        create_audit_log_ex(current_app, "Player removed from queue",
                            user_id=current_user.user_id,
                            player_id=player.player_id,
                            division_machine_id=removed_queue.division_machine_id,
                            description="Player removed from queue %s by getting started on %s" % (removed_queue.division_machine.machine.machine_name,division_machine.machine.machine_name),
                            commit=False)

    for player_in_other_que in players_in_other_queue:
        create_audit_log_ex(current_app, "Other player removed from queue",
                            user_id=current_user.user_id,
                            player_id=player_in_other_que['player_id'],
                            division_machine_id=player_in_other_que['division_machine_id'],
                            description="Player moved up on queue %s due to removal of player %s" % (player_in_other_que['division_machine']['division_machine_name'],player.first_name+" "+player.last_name),
                            commit=False)
        
    if removed_queue is not None and removed_queue is not False and len(players_to_alert) > 0:        
        push_notification_message = "The queue for %s has changed!  Please check the queue to see your new position." % queue.division_machine.machine.machine_name
        send_push_notification(push_notification_message, players=players_to_alert)
    db.session.commit()
    return jsonify({'data':division_machine.to_dict_simple()})
Ejemplo n.º 13
0
 def delete(self):
     """ Deletes the envelope if it does not have any associated transactions """
     if len(self.transactions) > 0:
         raise Conflict("Envelope is referenced by transactions")
     if len(self.periodic_expenses) > 0:
         raise Conflict(
             "Envelope is referenced by budgeted periodic expenses")
     if len(self.annual_expenses) > 0:
         raise Conflict(
             "Envelope is referenced by budgeted annual expenses")
     super().delete()
Ejemplo n.º 14
0
    def post(self, login):
        schema = UserProfileManageInfoSchema()

        obj = schema.loads(request.get_data(as_text=True))
        if obj.errors:
            return {"errors": obj.errors}, 400

        user_login_obj = UserLoginSchemaBase().load({"login": login})
        if user_login_obj.errors:
            return {"errors": user_login_obj.errors}, 400

        if db.session.query(exists().where(User.login == login)).scalar():
            raise Conflict("User exists yet")

        if db.session.query(exists().where(Group.name == login)).scalar():
            raise Conflict("Group exists yet")

        user = User()
        user.login = login
        user.email = obj.data.get("email")
        user.additional_info = obj.data.get("additional_info")
        user.feed_quality = obj.data.get("feed_quality")
        user.disabled = False
        user.pending = False
        user.registered_by = g.auth_user.id
        user.registered_on = datetime.datetime.now()
        user.groups.append(Group.public_group())
        user.reset_sessions()
        db.session.add(user)

        group = Group()
        group.name = login
        group.private = True
        group.users.append(user)
        db.session.add(group)

        if obj.data.get("send_email", False):
            try:
                send_email_notification("register",
                                        "New account registered in Malwarecage",
                                        user.email,
                                        base_url=app_config.malwarecage.base_url,
                                        login=user.login,
                                        set_password_token=user.generate_set_password_token().decode("utf-8"))
            except MailError:
                logger.exception("Can't send e-mail notification")
                raise InternalServerError("SMTP server needed to fulfill this request is"
                                          " not configured or unavailable.")

        db.session.commit()

        logger.info('User created', extra={'user': user.login})
        schema = UserSuccessSchema()
        return schema.dump({"login": user.login})
Ejemplo n.º 15
0
def validate_cvr_upload(request: Request, election: Election,
                        jurisdiction: Jurisdiction):
    if election.audit_type != AuditType.BALLOT_COMPARISON:
        raise Conflict(
            "Can only upload CVR file for ballot comparison audits.")

    if not jurisdiction.manifest_file_id:
        raise Conflict(
            "Must upload ballot manifest before uploading CVR file.")

    if "cvrs" not in request.files:
        raise BadRequest("Missing required file parameter 'cvrs'")
Ejemplo n.º 16
0
def invitations_accept():
    invitation = _invitation_query() \
        .filter(Invitation.hash == current_request.get_json()["hash"]) \
        .one()
    if invitation.status != "open":
        raise Conflict(f"The invitation has status {invitation.status}")

    if invitation.expiry_date and invitation.expiry_date < datetime.datetime.now():
        if invitation.external_identifier:
            invitation.status = "expired"
            db.session.merge(invitation)
            db.session.commit()
        else:
            delete(Invitation, invitation.id)
        raise Conflict(f"The invitation has expired at {invitation.expiry_date}")

    collaboration = invitation.collaboration
    user_id = current_user_id()
    if collaboration.is_member(user_id):
        delete(Invitation, invitation.id)
        raise Conflict(f"User {user_id} is already a member of {collaboration.name}")

    role = invitation.intended_role if invitation.intended_role else "member"
    collaboration_membership = CollaborationMembership(user_id=user_id,
                                                       collaboration_id=collaboration.id,
                                                       role=role,
                                                       expiry_date=invitation.membership_expiry_date,
                                                       created_by=invitation.user.uid,
                                                       updated_by=invitation.user.uid)
    if invitation.external_identifier:
        collaboration_membership.invitation_id = invitation.id

    collaboration_membership = db.session.merge(collaboration_membership)
    # We need the persistent identifier of the collaboration_membership which will be generated after the delete-commit
    if invitation.external_identifier:
        invitation.status = "accepted"
        db.session.merge(invitation)
        db.session.commit()
    else:
        delete(Invitation, invitation.id)

    # ensure all authorisation group membership are added
    groups = invitation.groups + list(filter(lambda ag: ag.auto_provision_members, collaboration.groups))

    for group in set(list({ag.id: ag for ag in groups}.values())):
        group.collaboration_memberships.append(collaboration_membership)
        db.session.merge(group)

    add_user_aups(collaboration, user_id)

    res = {'collaboration_id': collaboration.id, 'user_id': user_id}
    return res, 201
Ejemplo n.º 17
0
def player_bet(player, current_round, amount):
    if current_round.current_bet > 0:
        raise Conflict("There is already a bet. Try raising or calling.")

    try:
        player.place_bet(amount, current_round.pot)
    except OutOfMoney:
        raise Conflict("User does not have sufficient money to bet.")

    player.player_status.last_action = PLAYER_STATUS_CONSTANTS["action"]["bet"]
    current_round.go_to_next_player()

    return {"message": "User has successfully bet."}
Ejemplo n.º 18
0
def route_undo_division_machine_player_team(division_id,division_machine_id):            
    db = db_util.app_db_handle(current_app)
    tables = db_util.app_db_tables(current_app)                            
    division_machine = fetch_entity(tables.DivisionMachine,division_machine_id)
    if division_machine.division.team_tournament is False and division_machine.player_id is None:
        raise Conflict('Machine is not being played')
    if division_machine.division.team_tournament and division_machine.team_id is None:
        raise Conflict('Machine is not being played')    
    token = tables.Token.query.filter_by(player_id=division_machine.player_id,division_machine_id=division_machine_id,used=False).first()
    token.division_machine_id=None
    division_machine.player_id=None
    db.session.commit()    
    return jsonify({'data':division_machine.to_dict_simple()})
Ejemplo n.º 19
0
    def _post_supply_delivery(self, resource):
        try:
            fhir = SimpleFhirR4Reader(resource)
            patient = fhir.patient
            pid = patient.identifier
            p_id = from_client_participant_id(pid.value)
            bo_id = fhir.basedOn[0].identifier.value
            _id = self.dao.get_id(
                ObjDict({
                    'participantId': p_id,
                    'order_id': int(bo_id)
                }))
            tracking_status = fhir.extension.get(
                url=DV_FHIR_URL + 'tracking-status').valueString.lower()
        except AttributeError as e:
            raise BadRequest(e.message)
        except Exception as e:
            raise BadRequest(e.message)

        if not _id:
            raise Conflict(
                'Existing SupplyRequest for order required for SupplyDelivery')
        dvo = self.dao.get(_id)
        if not dvo:
            raise Conflict(
                'Existing SupplyRequest for order required for SupplyDelivery')

        merged_resource = None
        # Note: POST tracking status should be either 'enroute/in_transit'. PUT should only be 'delivered'.
        if tracking_status in [
                'in_transit', 'enroute', 'delivered'
        ] and self._to_mayo(fhir) and not dvo.biobankOrderId:
            # Send to mayolink and create internal biobank order
            response = self.dao.send_order(resource, p_id)
            merged_resource = merge_dicts(response, resource)
            merged_resource['id'] = _id
            logging.info(
                'Sending salivary order to biobank for participant: %s', p_id)
            self.dao.insert_biobank_order(p_id, merged_resource)

        response = super(DvOrderApi, self).put(bo_id,
                                               participant_id=p_id,
                                               skip_etag=True,
                                               resource=merged_resource)
        response[2]['Location'] = '/rdr/v1/SupplyDelivery/{}'.format(bo_id)
        response[2]['auth_user'] = resource['auth_user']
        if response[1] == 200:
            created_response = list(response)
            created_response[1] = 201
            return tuple(created_response)
        return response
Ejemplo n.º 20
0
    def post(self):
        """This endpoint allows an unregistered user to sign up."""

        req_data = request.data.decode().replace("'", '"')
        if not req_data:
            raise BadRequest("Provide data in the request")
        body = json.loads(req_data)
        try:
            username = body['username']
            first_name = body['first_name'].strip()
            last_name = body['last_name'].strip()
            ek_number = body['ek_number'].strip()
            email = body['email'].strip()
            phone_number = body['phone_number'].strip()
            password = body['password'].strip()
            user_level = body['user_level']
            if not user_level:
                user_level = 1
        except (KeyError, IndexError) as e:
            raise BadRequest

        user_data = {
            "username": username,
            "first_name": first_name,
            "last_name": last_name,
            "ek_number": ek_number,
            "email": email,
            "phone_number": phone_number,
            "password": password,
            "user_level": user_level
        }
        _validate_user(user_data)
        user = UserModel(**user_data)
        if user.check_exists(table="users", field="username",
                             data=username) == True:
            raise Conflict("There is a user with such a username")
        elif user.check_exists(table="users", field="email",
                               data=email) == True:
            raise Conflict("There is a user with such an email")
        elif user.check_exists(table="users",
                               field="ek_number",
                               data=ek_number) == True:
            raise Conflict("There is a user with the same EK number")
        else:
            resp = user.save()
            e = Email([email])
            e.welcome_text(first_name + ' ' + last_name, password, username)
            respn = {"message": "Successfully added", "username": username}

        return respn, 201
Ejemplo n.º 21
0
    def insert_user(self, user_data):
        """Inserts a user into database and it returns his e-mail."""

        # just remove `password` field to log the parameter
        password = user_data.pop('password')
        logging.info(f"insert_user - user_data: {user_data}")
        user_data['password'] = password

        # check if user exists by his e-mail
        user = self.db_ps_register.select_from_user(email=user_data['email'])

        if user:
            logging.info(
                f"insert_user - E-mail has already been registered! E-mail: `{user_data['email']}`"
            )
            raise Conflict(
                f"E-mail has already been registered! E-mail: `{user_data['email']}`"
            )

        # check if user exists by his username
        user = self.db_ps_register.select_from_user(
            username=user_data['username'])

        if user:
            logging.info(
                f"insert_user - Username has already been registered! Username: `{user_data['username']}`"
            )
            raise Conflict(
                f"Username has already been registered! Username: `{user_data['username']}`"
            )

        # default value to `address_id`, if there is not an `address_id`, then insert NULL
        user_data['address_id'] = None

        # if there is 'address' field, then try to insert address
        # information in the database
        if 'address' in user_data:
            # if there are properties inside 'address' field,
            # then insert the address in the database
            if user_data['address']:
                logging.info(f"insert_user - address: {user_data['address']}")

                address_id = self.db_ps_register.insert_into_address(user_data)
                user_data['address_id'] = address_id

            # remove 'address' field from dict
            del user_data['address']

        return self.db_ps_register.insert_into_user(user_data)
Ejemplo n.º 22
0
def validate_standardized_contests_upload(request: Request,
                                          election: Election):
    if election.audit_type != AuditType.BALLOT_COMPARISON:
        raise Conflict(
            "Can only upload standardized contests file for ballot comparison audits."
        )

    if len(list(election.jurisdictions)) == 0:
        raise Conflict(
            "Must upload jurisdictions file before uploading standardized contests file."
        )

    if "standardized-contests" not in request.files:
        raise BadRequest(
            "Missing required file parameter 'standardized-contests'")
Ejemplo n.º 23
0
def validate_batch_tallies_upload(request: Request, election: Election,
                                  jurisdiction: Jurisdiction):
    if election.audit_type != AuditType.BATCH_COMPARISON:
        raise Conflict(
            "Can only upload batch tallies file for batch comparison audits.")

    if len(list(jurisdiction.contests)) == 0:
        raise Conflict("Jurisdiction does not have any contests assigned")

    if not jurisdiction.manifest_file_id:
        raise Conflict(
            "Must upload ballot manifest before uploading batch tallies.")

    if "batchTallies" not in request.files:
        raise BadRequest("Missing required file parameter 'batchTallies'")
Ejemplo n.º 24
0
    def put(self, username):
        if UserModel().check_exists("users", "username", username) == False:
            raise NotFound("No such user in our record")
        if username == g.user or UserModel().get_user_username(g.user)[4] == 0:
            req_data = request.data.decode().replace("'", '"')
            if not req_data:
                raise BadRequest("Provide data in the request")
            body = json.loads(req_data)
            _validate_user(body)
            for field, value in body.items():
                if field == "username" or field == "user_level":
                    raise Unauthorized(
                        "You are not permitted to preform this operation")
                elif field == "email":
                    if UserModel().check_exists(table="users",
                                                field="email",
                                                data=value) == True:
                        raise Conflict("There is a user with such an email")
                    else:
                        UserModel().update_item(table="users",
                                                field=field,
                                                data=value,
                                                item_field="username",
                                                item_id=username)
                elif field == "ek_number":
                    if UserModel().check_exists(table="users",
                                                field="ek_number",
                                                data=value) == True:
                        raise Conflict(
                            "There is a user with the same EK number")
                    else:
                        UserModel().update_item(table="users",
                                                field=field,
                                                data=value,
                                                item_field="username",
                                                item_id=username)
                else:
                    UserModel().update_item(table="users",
                                            field=field,
                                            data=value,
                                            item_field="username",
                                            item_id=username)

            new_user = {"message": "Successfully Updated"}
            return new_user, 200
        else:
            raise Unauthorized(
                "You are not permitted to preform this operation")
Ejemplo n.º 25
0
def validate_post(args):
    """
    Validates the POST request parameters.

    :param dict args: request parameters
    """

    # all args except Description must have a value
    for arg, value in args.items():
        if arg != JobFields.DESCRIPTION and not value:
            raise BadRequest(f"'{arg}' is required in request.")

    name = args[JobFields.NAME]

    # Make sure name has no arbitrary (unallowed) characters for the filesystem
    match = re.match('^[^*&%\/\s]+$', name)
    if not match:
        raise BadRequest(f"'name' cannot have characters *, &, /, %.")

    # make sure no other combo of name & router & provider exists
    existing_combo: Job = Job.query.filter(
        Job.name == args[JobFields.NAME],
        Job.provider == args[JobFields.PROVIDER],
        Job.router == args[JobFields.ROUTER]).first()
    if existing_combo:
        raise Conflict(
            f"Combination of 'name' & 'router' & 'provider' already exists with ID {existing_combo.id}"
        )

    _validate_common(args)
Ejemplo n.º 26
0
 def post(self):
     """
     Creates a new customer.
     """
     if not (0 <= request.json["pin"] <= 99999):
         raise UnprocessableEntity("The PIN must be of 5 digits")
     new_customer = Customer(
         customer_mail_address=request.json['mail_address'],
         customer_first_name=request.json['first_name'],
         customer_last_name=request.json['last_name'],
         customer_pin_hash=str(request.json['pin']))
     print(new_customer.customer_pin_hash)
     db.session.add(new_customer)
     try:
         db.session.commit()
     except OperationalError:
         db.session.remove()
         raise InternalServerError(
             description='Customer table does not exists.')
     except IntegrityError:
         db.session.remove()
         raise Conflict(description=new_customer.__repr__() +
                        ' already exists')
     current_app.logger.info(new_customer.__repr__() +
                             ' added to database.')
     return {'message': 'Resource created'}, 201
Ejemplo n.º 27
0
    def on_restore(self, req):
        """Entry point for restore rule"""
        account = req.args.get('acct')
        container = req.args.get('ref')

        if not account:
            raise BadRequest('Missing Account name')
        if not container:
            raise BadRequest('Missing Container name')

        if req.method not in ('PUT', 'HEAD'):
            return Response("Not supported", 405)

        try:
            self.proxy.container_get_properties(account, container)
            if not req.headers.get('range') and req.method == 'PUT':
                raise Conflict('Container already exists')
        except exc.NoSuchContainer:
            pass
        except Conflict:
            raise
        except Exception:
            raise BadRequest('Fail to verify container')

        if req.method == 'HEAD':
            return self._do_put_head(req, account, container)

        return self._do_put(req, account, container)
Ejemplo n.º 28
0
 def response(cls, data, request):
     if isinstance(request, XMLRequest):
         if isinstance(data, TrytonException):
             data = client.Fault(data.code, str(data))
         elif isinstance(data, Exception):
             data = client.Fault(255, str(data))
         else:
             data = (data,)
         return Response(client.dumps(
                 data, methodresponse=True, allow_none=True),
             content_type='text/xml')
     else:
         if isinstance(data, UserWarning):
             return Conflict(data)
         elif isinstance(data, LoginException):
             return Forbidden(data)
         elif isinstance(data, ConcurrencyException):
             return Locked(data)
         elif isinstance(data, RateLimitException):
             return TooManyRequests(data)
         elif isinstance(data, MissingDependenciesException):
             return InternalServerError(data)
         elif isinstance(data, TrytonException):
             return BadRequest(data)
         elif isinstance(data, Exception):
             return InternalServerError(data)
         return Response(data)
Ejemplo n.º 29
0
def post(memo_id: int) -> str:
    # 指定されたidがあるかどうか確認する
    is_exist: bool = exist(memo_id)

    if is_exist:
        raise Conflict(f'memo_id [{memo_id}] is already registered.')

    # リクエストから値を取得する
    memo: str = request.form["memo"]

    # DBクライアントを作成する
    conn = connector.connect(**config)
    cursor = conn.cursor()

    # memoを保存する
    query = "INSERT INTO test_table (memo_id, memo) VALUES (%s, %s)"
    cursor.execute(query, (memo_id, memo))

    # DBクライアントをcloseする
    cursor.close()
    conn.close()

    return jsonify(
        {
            "message": "saved."
        }
    )
Ejemplo n.º 30
0
 def response(cls, data, request):
     try:
         parsed_data = request.parsed_data
     except BadRequest:
         parsed_data = {}
     if (isinstance(request, JSONRequest)
             and set(parsed_data.keys()) == {'id', 'method', 'params'}):
         response = {'id': parsed_data.get('id', 0)}
         if isinstance(data, TrytonException):
             response['error'] = data.args
         elif isinstance(data, Exception):
             # report exception back to server
             response['error'] = (str(data), data.__format_traceback__)
         else:
             response['result'] = data
     else:
         if isinstance(data, UserWarning):
             return Conflict(data)
         elif isinstance(data, LoginException):
             return Forbidden(data)
         elif isinstance(data, ConcurrencyException):
             return Locked(data)
         elif isinstance(data, RateLimitException):
             return TooManyRequests(data)
         elif isinstance(data, MissingDependenciesException):
             return InternalServerError(data)
         elif isinstance(data, TrytonException):
             return BadRequest(data)
         elif isinstance(data, Exception):
             return InternalServerError(data)
         response = data
     return Response(json.dumps(response,
                                cls=JSONEncoder,
                                separators=(',', ':')),
                     content_type='application/json')