def check_authorization():
    if 'remote_oauth' in session and 'client_id' in session:
        # resp = app.remote_oauth.get('me')
        bidder_data = get_bidder_id(app, session)
        if bidder_data:
            grant_timeout = iso8601.parse_date(
                bidder_data[u'expires']) - datetime.now(tzlocal())
            if grant_timeout > INVALIDATE_GRANT:
                app.logger.info(
                    "Bidder {} with client_id {} pass check_authorization".
                    format(
                        bidder_data['bidder_id'],
                        session['client_id'],
                    ),
                    extra=prepare_extra_journal_fields(request.headers))
                return jsonify({'status': 'ok'})
            else:
                app.logger.info(
                    "Grant will end in a short time. Activate re-login functionality",
                    extra=prepare_extra_journal_fields(request.headers))
        else:
            app.logger.warning(
                "Client_id {} didn't passed check_authorization".format(
                    session['client_id']),
                extra=prepare_extra_journal_fields(request.headers))
    abort(401)
예제 #2
0
def form_handler():
    auction = app.config['auction']
    with auction.bids_actions:
        form = app.bids_form.from_json(request.json)
        form.auction = auction
        form.document = auction.db.get(auction.auction_doc_id)
        current_time = datetime.now(timezone('Europe/Kiev'))
        if form.validate():
            # write data
            auction.add_bid(form.document['current_stage'],
                            {'amount': form.data['bid'],
                             'bidder_id': form.data['bidder_id'],
                             'time': current_time.isoformat()})
            if form.data['bid'] == -1.0:
                app.logger.info("Bidder {} with client_id {} canceled bids in stage {} in {}".format(
                    form.data['bidder_id'], session['client_id'],
                    form.document['current_stage'], current_time.isoformat()
                ), extra=prepare_extra_journal_fields(request.headers))
            else:
                app.logger.info("Bidder {} with client_id {} placed bid {} in {}".format(
                    form.data['bidder_id'], session['client_id'],
                    form.data['bid'], current_time.isoformat()
                ), extra=prepare_extra_journal_fields(request.headers))
            return {'status': 'ok', 'data': form.data}
        else:
            app.logger.info("Bidder {} with client_id {} wants place bid {} in {} with errors {}".format(
                request.json.get('bidder_id', 'None'), session['client_id'],
                request.json.get('bid', 'None'), current_time.isoformat(),
                repr(form.errors)
            ), extra=prepare_extra_journal_fields(request.headers))
            return {'status': 'failed', 'errors': form.errors}
def form_handler():
    form = app.bids_form.from_json(request.json)
    form.document = app.context['auction_document']
    current_time = datetime.now(TIMEZONE)
    if form.validate():
        with lock_server(app.context['server_actions']):
            app.bids_handler.add_bid(
                form.document['current_stage'], {
                    'amount': form.data['bid'],
                    'bidder_id': form.data['bidder_id'],
                    'time': current_time.isoformat()
                })
            app.logger.info(
                "Bidder {} with client_id {} placed bid {} in {}".format(
                    form.data['bidder_id'], session['client_id'],
                    form.data['bid'], current_time.isoformat()),
                extra=prepare_extra_journal_fields(request.headers))
            return {'status': 'ok', 'data': form.data}
    else:
        app.logger.info("Bidder {} with client_id {} wants place "
                        "bid {} in {} with errors {}".format(
                            request.json.get('bidder_id', 'None'),
                            session['client_id'],
                            request.json.get('bid', 'None'),
                            current_time.isoformat(), repr(form.errors)),
                        extra=prepare_extra_journal_fields(request.headers))
        return {'status': 'failed', 'errors': form.errors}
예제 #4
0
def post_bid():
    auction = app.config['auction']
    if 'remote_oauth' in session and 'client_id' in session:
        bidder_data = get_bidder_id(app, session)
        if bidder_data and bidder_data['bidder_id'] == request.json[
                'bidder_id']:
            with auction.bids_actions:
                form = BidsForm.from_json(request.json)
                form.auction = auction
                form.document = auction.db.get(auction.auction_doc_id)
                current_time = datetime.now(timezone('Europe/Kiev'))
                if form.validate():
                    # write data
                    auction.add_bid(
                        form.document['current_stage'], {
                            'amount': form.data['bid'],
                            'bidder_id': form.data['bidder_id'],
                            'time': current_time.isoformat()
                        })
                    if form.data['bid'] == -1.0:
                        app.logger.info(
                            "Bidder {} with client_id {} canceled bids in stage {} in {}"
                            .format(form.data['bidder_id'],
                                    session['client_id'],
                                    form.document['current_stage'],
                                    current_time.isoformat()),
                            extra=prepare_extra_journal_fields(
                                request.headers))
                    else:
                        app.logger.info(
                            "Bidder {} with client_id {} placed bid {} in {}".
                            format(form.data['bidder_id'],
                                   session['client_id'], form.data['bid'],
                                   current_time.isoformat()),
                            extra=prepare_extra_journal_fields(
                                request.headers))
                    response = {'status': 'ok', 'data': form.data}
                else:
                    response = {'status': 'failed', 'errors': form.errors}
                    app.logger.info(
                        "Bidder {} with client_id {} wants place bid {} in {} with errors {}"
                        .format(request.json.get('bidder_id', 'None'),
                                session['client_id'],
                                request.json.get('bid', 'None'),
                                current_time.isoformat(), repr(form.errors)),
                        extra=prepare_extra_journal_fields(request.headers))
                return jsonify(response)
        else:
            app.logger.warning(
                "Client with client id: {} and bidder_id {} wants post bid but response status from Oauth"
                .format(session.get('client_id', 'None'),
                        request.json.get('bidder_id', 'None')))
    abort(401)
def authorized():
    if not ('error' in request.args
            and request.args['error'] == 'access_denied'):
        resp = app.remote_oauth.authorized_response()
        if resp is None or hasattr(resp, 'data'):
            app.logger.info("Error Response from Oauth: {}".format(resp))
            return abort(403, 'Access denied')
        app.logger.info("Get response from Oauth: {}".format(repr(resp)))
        session['remote_oauth'] = (resp['access_token'], '')
        session['client_id'] = os.urandom(16).encode('hex')
    bidder_data = get_bidder_id(app, session)
    app.logger.info("Bidder {} with client_id {} authorized".format(
        bidder_data['bidder_id'],
        session['client_id'],
    ),
                    extra=prepare_extra_journal_fields(request.headers))

    app.logger.debug("Session: {}".format(repr(session)))
    response = redirect(
        urljoin(request.headers['X-Forwarded-Path'], '.').rstrip('/'))
    response.set_cookie('auctions_loggedin',
                        '1',
                        path=app.config['SESSION_COOKIE_PATH'],
                        secure=False,
                        httponly=False,
                        max_age=36000)
    return response
예제 #6
0
def check_authorization():
    if 'remote_oauth' in session and 'client_id' in session:
        # resp = app.remote_oauth.get('me')
        bidder_data = get_bidder_id(app, session)
        if bidder_data:
            grant_timeout = iso8601.parse_date(bidder_data[u'expires']) - datetime.now(tzlocal())
            if grant_timeout > INVALIDATE_GRANT:
                app.logger.info("Bidder {} with client_id {} pass check_authorization".format(
                                bidder_data['bidder_id'], session['client_id'],
                                ), extra=prepare_extra_journal_fields(request.headers))
                return jsonify({'status': 'ok'})
            else:
                app.logger.info(
                    "Grant will end in a short time. Activate re-login functionality",
                    extra=prepare_extra_journal_fields(request.headers)
                )
        else:
            app.logger.warning("Client_id {} didn't passed check_authorization".format(session['client_id']),
                               extra=prepare_extra_journal_fields(request.headers))
    abort(401)
def set_sse_timeout():
    current_app.logger.info(
        'Handle set_sse_timeout request with session {}'.format(repr(dict(session))),
        extra=prepare_extra_journal_fields(request.headers)
    )
    if 'remote_oauth' in session and 'client_id' in session:
        bidder_data = get_bidder_id(current_app, session)
        if bidder_data:
            current_app.logger.info("Bidder {} with client_id {} set sse_timeout".format(
                                    bidder_data['bidder_id'], session['client_id'],
                                    ), extra=prepare_extra_journal_fields(request.headers))
            bidder = bidder_data['bidder_id']
            if 'timeout' in request.json:
                session["sse_timeout"] = int(request.json['timeout'])
                send_event_to_client(
                    bidder, session['client_id'], '',
                    event='StopSSE'
                )
                return jsonify({'timeout': session["sse_timeout"]})

    return abort(401)
예제 #8
0
def post_bid():
    auction = app.config['auction']
    if 'remote_oauth' in session and 'client_id' in session:
        bidder_data = get_bidder_id(app, session)
        if bidder_data and bidder_data['bidder_id'] == request.json['bidder_id']:
            with auction.bids_actions:
                form = BidsForm.from_json(request.json)
                form.auction = auction
                form.document = auction.db.get(auction.auction_doc_id)
                current_time = datetime.now(timezone('Europe/Kiev'))
                if form.validate():
                    # write data
                    auction.add_bid(form.document['current_stage'],
                                    {'amount': form.data['bid'],
                                     'bidder_id': form.data['bidder_id'],
                                     'time': current_time.isoformat()})
                    if form.data['bid'] == -1.0:
                        app.logger.info("Bidder {} with client_id {} canceled bids in stage {} in {}".format(
                            form.data['bidder_id'], session['client_id'],
                            form.document['current_stage'], current_time.isoformat()
                        ), extra=prepare_extra_journal_fields(request.headers))
                    else:
                        app.logger.info("Bidder {} with client_id {} placed bid {} in {}".format(
                            form.data['bidder_id'], session['client_id'],
                            form.data['bid'], current_time.isoformat()
                        ), extra=prepare_extra_journal_fields(request.headers))
                    response = {'status': 'ok', 'data': form.data}
                else:
                    response = {'status': 'failed', 'errors': form.errors}
                    app.logger.info("Bidder {} with client_id {} wants place bid {} in {} with errors {}".format(
                        request.json.get('bidder_id', 'None'), session['client_id'],
                        request.json.get('bid', 'None'), current_time.isoformat(),
                        repr(form.errors)
                    ), extra=prepare_extra_journal_fields(request.headers))
                return jsonify(response)
        else:
            app.logger.warning("Client with client id: {} and bidder_id {} wants post bid but response status from Oauth".format(
                session.get('client_id', 'None'), request.json.get('bidder_id', 'None')
            ))
    abort(401)
    def log_request(self):
        log = self.server.log
        if log:
            extra = prepare_extra_journal_fields(self.headers)
            real_ip = self.environ.get('HTTP_X_REAL_IP', '')
            if real_ip.startswith('172.'):
                real_ip = ''
            extra['JOURNAL_REMOTE_ADDR'] = ','.join(
                [self.environ.get('HTTP_X_FORWARDED_FOR', ''), real_ip])
            extra['JOURNAL_USER_AGENT'] = self.environ.get(
                'HTTP_USER_AGENT', '')

            log.write(self.format_request(), extra=extra)
예제 #10
0
    def log_request(self):
        log = self.server.log
        if log:
            extra = prepare_extra_journal_fields(self.headers)
            real_ip = self.environ.get('HTTP_X_REAL_IP', '')
            if real_ip.startswith('172.'):
                real_ip = ''
            extra['JOURNAL_REMOTE_ADDR'] = ','.join(
                [self.environ.get('HTTP_X_FORWARDED_FOR', ''), real_ip]
            )
            extra['JOURNAL_USER_AGENT'] = self.environ.get('HTTP_USER_AGENT', '')

            log.write(self.format_request(), extra=extra)
def set_sse_timeout():
    current_app.logger.info(
        'Handle set_sse_timeout request with session {}'.format(
            repr(dict(session))),
        extra=prepare_extra_journal_fields(request.headers))
    if 'remote_oauth' in session and 'client_id' in session:
        bidder_data = get_bidder_id(current_app, session)
        if bidder_data:
            current_app.logger.info(
                "Bidder {} with client_id {} set sse_timeout".format(
                    bidder_data['bidder_id'],
                    session['client_id'],
                ),
                extra=prepare_extra_journal_fields(request.headers))
            bidder = bidder_data['bidder_id']
            if 'timeout' in request.json:
                session["sse_timeout"] = int(request.json['timeout'])
                send_event_to_client(bidder,
                                     session['client_id'],
                                     '',
                                     event='StopSSE')
                return jsonify({'timeout': session["sse_timeout"]})
    return abort(401)
예제 #12
0
def relogin():
    if (all([key in session
             for key in ['login_callback', 'login_bidder_id', 'login_hash']])):
        if 'amount' in request.args:
            session['amount'] = request.args['amount']
        app.logger.debug("Session: {}".format(repr(session)))
        app.logger.info("Bidder {} with login_hash {} start re-login".format(
                        session['login_bidder_id'], session['login_hash'],
                        ), extra=prepare_extra_journal_fields(request.headers))
        return app.remote_oauth.authorize(
            callback=session['login_callback'],
            bidder_id=session['login_bidder_id'],
            hash=session['login_hash'],
            auto_allow='1'
        )
    return redirect(
        urljoin(request.headers['X-Forwarded-Path'], '.').rstrip('/')
    )
def relogin():
    if (all([key in session
             for key in ['login_callback', 'login_bidder_id', 'signature']])):
        if 'amount' in request.args:
            session['amount'] = request.args['amount']
        app.logger.debug("Session: {}".format(repr(session)))
        app.logger.info("Bidder {} with login_hash {} start re-login".format(
                        session['login_bidder_id'], session['signature'],
                        ), extra=prepare_extra_journal_fields(request.headers))
        return app.remote_oauth.authorize(
            callback=session['login_callback'],
            bidder_id=session['login_bidder_id'],
            signature=session['signature'],
            auto_allow='1'
        )
    return redirect(
        urljoin(request.headers['X-Forwarded-Path'], '.').rstrip('/')
    )
예제 #14
0
def authorized():
    if not('error' in request.args and request.args['error'] == 'access_denied'):
        resp = app.remote_oauth.authorized_response()
        if resp is None or hasattr(resp, 'data'):
            app.logger.info("Error Response from Oauth: {}".format(resp))
            return abort(403, 'Access denied')
        app.logger.info("Get response from Oauth: {}".format(repr(resp)))
        session['remote_oauth'] = (resp['access_token'], '')
        session['client_id'] = os.urandom(16).encode('hex')
    bidder_data = get_bidder_id(app, session)
    app.logger.info("Bidder {} with client_id {} authorized".format(
                    bidder_data['bidder_id'], session['client_id'],
                    ), extra=prepare_extra_journal_fields(request.headers))

    app.logger.debug("Session: {}".format(repr(session)))
    response = redirect(
        urljoin(request.headers['X-Forwarded-Path'], '.').rstrip('/')
    )
    response.set_cookie('auctions_loggedin', '1',
                        path=app.config['SESSION_COOKIE_PATH'],
                        secure=False, httponly=False, max_age=36000
                        )
    return response
def event_source():
    current_app.logger.debug(
        'Handle event_source request with session {}'.format(
            repr(dict(session))),
        extra=prepare_extra_journal_fields(request.headers))
    if 'remote_oauth' in session and 'client_id' in session:
        bidder_data = get_bidder_id(current_app, session)
        if bidder_data:
            valid_bidder = False
            client_hash = session['client_id']
            bidder = bidder_data['bidder_id']
            for bidder_info in current_app.config['auction'].bidders_data:
                if bidder_info['id'] == bidder:
                    valid_bidder = True
                    break
            if current_app.config['auction'].auction_document.get(
                    'current_phase',
                    '') in ['dutch', 'pre-started', 'pre-sealedbid']:
                valid_bidder = True
            if valid_bidder:
                if bidder not in current_app.auction_bidders:
                    current_app.auction_bidders[bidder] = {
                        "clients": {},
                        "channels": {}
                    }

                if client_hash not in current_app.auction_bidders[bidder]:
                    real_ip = request.environ.get('HTTP_X_REAL_IP', '')
                    if real_ip.startswith('172.'):
                        real_ip = ''
                    current_app.auction_bidders[bidder]["clients"][
                        client_hash] = {
                            'ip':
                            ','.join([
                                request.headers.get('X-Forwarded-For', ''),
                                real_ip
                            ]),
                            'User-Agent':
                            request.headers.get('User-Agent'),
                        }
                    current_app.auction_bidders[bidder]["channels"][
                        client_hash] = Queue()

                current_app.logger.info(
                    'Send identification for bidder: {} with client_hash {}'.
                    format(bidder, client_hash),
                    extra=prepare_extra_journal_fields(request.headers))
                identification_data = {
                    "bidder_id": bidder,
                    "client_id": client_hash,
                    "return_url": session.get('return_url', '')
                }
                if current_app.config['auction'].features:
                    identification_data["coeficient"] = str(
                        current_app.config['auction'].
                        bidders_coeficient[bidder])

                send_event_to_client(bidder, client_hash, identification_data,
                                     "Identification")
                if 'amount' in session:
                    send_event_to_client(bidder, client_hash,
                                         {"last_amount": session['amount']},
                                         "RestoreBidAmount")
                    current_app.logger.debug('Send RestoreBidAmount')
                    del session['amount']

                if not session.get("sse_timeout", 0):
                    current_app.logger.debug('Send ClientsList')
                    send_event(bidder,
                               current_app.auction_bidders[bidder]["clients"],
                               "ClientsList")
                response = Response(
                    SseStream(current_app.auction_bidders[bidder]["channels"]
                              [client_hash],
                              bidder_id=bidder,
                              client_id=client_hash,
                              timeout=session.get("sse_timeout", 0)),
                    direct_passthrough=True,
                    mimetype='text/event-stream',
                    content_type='text/event-stream')
                response.headers['Cache-Control'] = 'no-cache'
                response.headers['X-Accel-Buffering'] = 'no'
                return response
            else:
                current_app.logger.info(
                    'Not valid bidder: bidder_id {} with client_hash {}'.
                    format(bidder, client_hash),
                    extra=prepare_extra_journal_fields(request.headers))

    current_app.logger.debug('Disable event_source for unauthorized user.',
                             extra=prepare_extra_journal_fields(
                                 request.headers))
    events_close = PySse()
    events_close.add_message("Close", "Disable")
    response = Response(iter(
        [bytearray(''.join([x for x in events_close]), 'UTF-8')]),
                        direct_passthrough=True,
                        mimetype='text/event-stream',
                        content_type='text/event-stream')
    response.headers['Cache-Control'] = 'no-cache'
    response.headers['X-Accel-Buffering'] = 'no'
    return response
def form_handler():
    auction = app.config['auction']
    raw_data = request.json
    if 'bid' in raw_data:
        raw_data['bid'] = str(raw_data['bid'])
    form = app.bids_form.from_json(raw_data)
    form.auction = auction
    form.document = auction.auction_document
    current_time = datetime.now(timezone('Europe/Kiev'))
    current_phase = form.document.get('current_phase')
    current_stage = form.document.get('current_stage')
    if not form.validate():
        app.logger.info(
            "Bidder {} with client_id {} wants place bid {} in {} on phase {} "
            "with errors {}".format(request.json.get('bidder_id', 'None'),
                                    session.get('client_id', ''),
                                    request.json.get('bid', 'None'),
                                    current_time.isoformat(), current_phase,
                                    repr(form.errors)),
            extra=prepare_extra_journal_fields(request.headers))
        return {'status': 'failed', 'errors': form.errors}
    if current_phase == DUTCH:
        with lock_bids(auction):
            bidder_id = form.data['bidder_id']
            if bidder_id not in auction.mapping:
                auction.get_auction_info()
                if bidder_id not in auction.mapping:
                    app.logger.fatal(
                        "CRITICAL! Bad bidder, that not registered in API"
                    )  # XXX TODO create a way to ban this user
                    return {"status": "failed", "errors": [["Bad bidder!"]]}
            ok = auction.add_dutch_winner({
                'amount': form.data['bid'],
                'time': current_time.isoformat(),
                'bidder_id': form.data['bidder_id'],
                'current_stage': current_stage
            })
            if not isinstance(ok, Exception):
                app.logger.info("Bidder {} with client {} has won"
                                " dutch on value {}".format(
                                    form.data['bidder_id'],
                                    session.get('client_id'),
                                    form.data['bid']))
                return {"status": "ok", "data": form.data}
            else:
                app.logger.info("Bidder {} with client_id {} wants place"
                                " bid {} in {} on dutch "
                                "with errors {}".format(
                                    request.json.get('bidder_id', 'None'),
                                    session.get('client_id'),
                                    request.json.get('bid', 'None'),
                                    current_time.isoformat(), repr(ok)),
                                extra=prepare_extra_journal_fields(
                                    request.headers))
                return {"status": "failed", "errors": [[repr(ok)]]}

    elif current_phase == SEALEDBID:
        try:
            if hasattr(auction, '_end_sealedbid'):
                if not auction._end_sealedbid.is_set():
                    auction.bids_queue.put({
                        'amount': form.data['bid'],
                        'time': current_time.isoformat(),
                        'bidder_id': form.data['bidder_id']
                    })
                    return {"status": "ok", "data": form.data}
            return {"status": "failed", "errors": ['Forbidden']}
        except Exception as e:
            return {"status": "failed", "errors": [repr(e)]}
    elif current_phase == BESTBID:
        ok = auction.add_bestbid({
            'amount': form.data['bid'],
            'time': current_time.isoformat(),
            'bidder_id': form.data['bidder_id']
        })
        if not isinstance(ok, Exception):
            app.logger.info(
                "Bidder {} with client {} has won dutch on value {}".format(
                    form.data['bidder_id'], session.get('client_id'),
                    form.data['bid']))
            return {"status": "ok", "data": form.data}
        else:
            app.logger.info(
                "Bidder {} with client_id {} wants place"
                " bid {} in {} on dutch "
                "with errors {}".format(request.json.get('bidder_id', 'None'),
                                        session.get('client_id'),
                                        request.json.get('bid', 'None'),
                                        current_time.isoformat(), repr(ok)),
                extra=prepare_extra_journal_fields(request.headers))
            return {"status": "failed", "errors": [repr(ok)]}
    else:
        return {
            'status': 'failed',
            'errors': {
                'form': ['Bids period expired.']
            }
        }
예제 #17
0
def form_handler():
    auction = app.config['auction']
    form = app.bids_form.from_json(request.json)
    form.auction = auction
    form.document = auction.auction_document
    current_time = datetime.now(timezone('Europe/Kiev'))
    current_phase = form.document.get('current_phase')
    if not form.validate():
        app.logger.info(
            "Bidder {} with client_id {} wants place bid {} in {} on phase {} "
            "with errors {}".format(request.json.get('bidder_id', 'None'),
                                    session.get('client_id', ''),
                                    request.json.get('bid', 'None'),
                                    current_time.isoformat(), current_phase,
                                    repr(form.errors)),
            extra=prepare_extra_journal_fields(request.headers))
        return {'status': 'failed', 'errors': form.errors}
    if current_phase == DUTCH:
        with lock_bids(auction):
            ok = auction.add_dutch_winner({
                'amount': str(form.data['bid']),
                'time': current_time.isoformat(),
                'bidder_id': form.data['bidder_id']
            })
            if not isinstance(ok, Exception):
                app.logger.info("Bidder {} with client {} has won"
                                " dutch on value {}".format(
                                    form.data['bidder_id'],
                                    session.get('client_id'),
                                    form.data['bid']))
                return {"status": "ok", "data": form.data}
            else:
                app.logger.info("Bidder {} with client_id {} wants place"
                                " bid {} in {} on dutch "
                                "with errors {}".format(
                                    request.json.get('bidder_id', 'None'),
                                    session.get('client_id'),
                                    request.json.get('bid', 'None'),
                                    current_time.isoformat(), repr(ok)),
                                extra=prepare_extra_journal_fields(
                                    request.headers))
                return {"status": "failed", "errors": [repr(ok)]}

    elif current_phase == SEALEDBID:
        try:
            auction.bids_queue.put({
                'amount': str(form.data['bid']),
                'time': current_time.isoformat(),
                'bidder_id': form.data['bidder_id']
            })
            return {"status": "ok", "data": form.data}
        except Exception as e:
            return {"status": "failed", "errors": [repr(e)]}
    elif current_phase == BESTBID:
        ok = auction.add_bestbid({
            'amount': str(form.data['bid']),
            'time': current_time.isoformat(),
            'bidder_id': form.data['bidder_id']
        })
        if not isinstance(ok, Exception):
            app.logger.info(
                "Bidder {} with client {} has won dutch on value {}".format(
                    form.data['bidder_id'], session.get('client_id'),
                    form.data['bid']))
            return {"status": "ok", "data": form.data}
        else:
            app.logger.info(
                "Bidder {} with client_id {} wants place"
                " bid {} in {} on dutch "
                "with errors {}".format(request.json.get('bidder_id', 'None'),
                                        session.get('client_id'),
                                        request.json.get('bid', 'None'),
                                        current_time.isoformat(), repr(ok)),
                extra=prepare_extra_journal_fields(request.headers))
            return {"status": "failed", "errors": [repr(ok)]}
    else:
        return {
            'status': 'failed',
            'errors': {
                'form': ['Bids period expired.']
            }
        }
예제 #18
0
def form_handler():
    auction = app.config['auction']
    raw_data = {field: str(data) for field, data in request.json.items()}
    with auction.bids_actions:
        form = app.bids_form.from_json(raw_data)
        form.auction = auction
        form.document = auction.db.get(auction.auction_doc_id)
        current_time = datetime.now(timezone('Europe/Kiev'))
        total_amount = form.validate()
        if total_amount:
            # write data
            auction.add_bid(
                form.document['current_stage'], {
                    'bidder_id':
                    form.data['bidder_id'],
                    'amount':
                    total_amount,
                    'contractDurationYears':
                    form.data['contractDuration'],
                    'contractDurationDays':
                    form.data['contractDurationDays'],
                    'yearlyPaymentsPercentage':
                    float(form.data['yearlyPaymentsPercentage']),
                    'time':
                    current_time.isoformat()
                })
            if total_amount == -1:
                app.logger.info(
                    "Bidder {} with client_id {} canceled bids in "
                    "stage {} in {}".format(form.data['bidder_id'],
                                            session['client_id'],
                                            form.document['current_stage'],
                                            current_time.isoformat()),
                    extra=prepare_extra_journal_fields(request.headers))
            else:
                app.logger.info(
                    "Bidder {bidder_id} with client_id {client_id} placed bid with "
                    "total amount {amount}, "
                    "yearly payments percentage = {yearlyPaymentsPercentage}, "
                    "contract duraction years = {contractDurationYears}, "
                    "contract duration days = {contractDurationDays} "
                    "in {time}".format(
                        **dict(bidder_id=form.data['bidder_id'],
                               client_id=session['client_id'],
                               time=current_time.isoformat(),
                               amount=total_amount,
                               yearlyPaymentsPercentage=form.data.get(
                                   'yearlyPaymentsPercentage'),
                               contractDurationYears=form.data.get(
                                   'contractDuration'),
                               contractDurationDays=form.data.get(
                                   'contractDurationDays'))),
                    extra=prepare_extra_journal_fields(request.headers))
            return {'status': 'ok', 'data': form.data}
        else:
            app.logger.info(
                "Bidder {} with client_id {} wants place bid {} in {} with errors {}"
                .format(request.json.get('bidder_id', 'None'),
                        session['client_id'], request.json.get('bid', 'None'),
                        current_time.isoformat(), repr(form.errors)),
                extra=prepare_extra_journal_fields(request.headers))
            return {'status': 'failed', 'errors': form.errors}
def event_source():
    current_app.logger.debug(
        'Handle event_source request with session {}'.format(repr(dict(session))),
        extra=prepare_extra_journal_fields(request.headers)
    )
    if 'remote_oauth' in session and 'client_id' in session:
        bidder_data = get_bidder_id(current_app, session)
        if bidder_data:
            valid_bidder = False
            client_hash = session['client_id']
            bidder = bidder_data['bidder_id']
            for bidder_info in current_app.config['auction'].bidders_data:
                if bidder_info['id'] == bidder:
                    valid_bidder = True
                    break
            if valid_bidder:
                if bidder not in current_app.auction_bidders:
                    current_app.auction_bidders[bidder] = {
                        "clients": {},
                        "channels": {}
                    }

                if client_hash not in current_app.auction_bidders[bidder]:
                    real_ip = request.environ.get('HTTP_X_REAL_IP', '')
                    if real_ip.startswith('172.'):
                        real_ip = ''
                    current_app.auction_bidders[bidder]["clients"][client_hash] = {
                        'ip': ','.join(
                            [request.headers.get('X-Forwarded-For', ''), real_ip]
                        ),
                        'User-Agent': request.headers.get('User-Agent'),
                    }
                    current_app.auction_bidders[bidder]["channels"][client_hash] = Queue()

                current_app.logger.info(
                    'Send identification for bidder: {} with client_hash {}'.format(bidder, client_hash),
                    extra=prepare_extra_journal_fields(request.headers)
                )
                identification_data = {"bidder_id": bidder,
                                       "client_id": client_hash,
                                       "return_url": session.get('return_url', '')}
                if current_app.config['auction'].features:
                    identification_data["coeficient"] = str(current_app.config['auction'].bidders_coeficient[bidder])

                send_event_to_client(bidder, client_hash, identification_data,
                                     "Identification")
                if 'amount' in session:
                    send_event_to_client(bidder, client_hash,
                                         {"last_amount": session['amount']},
                                         "RestoreBidAmount")
                    current_app.logger.debug('Send RestoreBidAmount')
                    del session['amount']

                if not session.get("sse_timeout", 0):
                    current_app.logger.debug('Send ClientsList')
                    send_event(
                        bidder,
                        current_app.auction_bidders[bidder]["clients"],
                        "ClientsList"
                    )
                response = Response(
                    SseStream(
                        current_app.auction_bidders[bidder]["channels"][client_hash],
                        bidder_id=bidder,
                        client_id=client_hash,
                        timeout=session.get("sse_timeout", 0)
                    ),
                    direct_passthrough=True,
                    mimetype='text/event-stream',
                    content_type='text/event-stream'
                )
                response.headers['Cache-Control'] = 'no-cache'
                response.headers['X-Accel-Buffering'] = 'no'
                return response
            else:
                current_app.logger.info(
                    'Not valid bidder: bidder_id {} with client_hash {}'.format(bidder, client_hash),
                    extra=prepare_extra_journal_fields(request.headers)
                )

    current_app.logger.debug(
        'Disable event_source for unauthorized user.',
        extra=prepare_extra_journal_fields(request.headers)
    )
    events_close = PySse()
    events_close.add_message("Close", "Disable")
    response = Response(
        iter([bytearray(''.join([x for x in events_close]), 'UTF-8')]),
        direct_passthrough=True,
        mimetype='text/event-stream',
        content_type='text/event-stream'
    )
    response.headers['Cache-Control'] = 'no-cache'
    response.headers['X-Accel-Buffering'] = 'no'
    return response