Beispiel #1
0
def login():
    """Log user in"""

    # Forget any user_id
    session.clear()

    # User reached route via POST (as by submitting a form via POST)
    if request.method == "POST":

        # Ensure username was submitted
        if not request.form.get("username"):
            raise HTTPException("must provide username", 403)

        # Ensure password was submitted
        elif not request.form.get("password"):
            raise HTTPException("must provide password", 403)

        # Query database for username
        rows = db.execute("SELECT * FROM users WHERE username = :username",
                          username=request.form.get("username"))

        # Ensure username exists and password is correct
        if len(rows) != 1 or not check_password_hash(
                rows[0]["hash"], request.form.get("password")):
            raise HTTPException("invalid username and/or password", 403)

        # Remember which user has logged in
        session["user_id"] = rows[0]["id"]

        # Redirect user to home page
        return redirect("/")

    # User reached route via GET (as by clicking a link or via redirect)
    else:
        return render_template("login.html")
Beispiel #2
0
    def __init__(self, description, locator="", code=400):
        self.code = code
        self.description = description
        self.locator = locator
        logging.exception(description)

        HTTPException.__init__(self)
Beispiel #3
0
 def exception_handling(e: Exception):
     """
     Handles any uncaught exceptions and shows an applicable error page
     :param e: The caught exception
     :return: The response to the exception
     """
     if isinstance(e, HTTPException):
         error = e
         if e.code == 401:
             flash(
                 config.STRINGS["401_message"],
                 AlertSeverity.DANGER.value
             )
             return redirect(url_for("user_management.login"))
         app.logger.warning("Caught HTTP exception: {}".format(e))
     else:
         error = HTTPException(config.STRINGS["500_message"])
         error.code = 500
         trace = "".join(traceback.format_exception(*sys.exc_info()))
         app.logger.error("Caught exception: {}\n{}".format(e, trace))
         sentry_sdk.capture_exception(e)
     return render_template(
         config.REQUIRED_TEMPLATES["error_page"],
         error=error
     )
Beispiel #4
0
 def handle_error(self, e):
     if e.__class__ in self._error_handlers:
         handler = self._error_handlers[e.__class__]
         result = handler(e)
         e = HTTPException(str(e))
         e.data, e.code = result if len(result) == 2 else (result, 500)
     return super(Api, self).handle_error(e)
Beispiel #5
0
def buy():
    """Buy shares of stock"""
    if request.method == "POST":
        symbol = lookup(request.form.get("symbol"))
        shares = request.form.get("shares")

        if symbol is None:
            raise HTTPException("must provide correct symbol", 403)

        if shares is None:
            raise HTTPException("must provide shares", 403)

        quantity = int(shares)

        if quantity < 1:
            raise HTTPException("number of shares must be 1 or greater", 403)
        cash = storage.get_cash(session["user_id"])
        stocks_cost = symbol["price"] * quantity
        if cash >= stocks_cost:
            insert_transaction(symbol, quantity)
            left = cash - stocks_cost
            storage.update_cash(session["user_id"], left)
            position_update(symbol, quantity)
        else:
            raise HTTPException("not enough cash")

        return redirect("/")

    else:
        return render_template("buy.html")
Beispiel #6
0
	def __init__(self, data, description=None):
		"""
		param: data: A dictionary containing the field errors that occured
		param: description: Optional description to send through
		"""
		HTTPException.__init__(self)
		self.data = data
Beispiel #7
0
def api_buy2():
    symbol = request.form.get("symbol")
    shares = request.form.get("shares")

    if symbol is "":
        raise HTTPException("symbol can't be empty", 403)

    if shares is "":
        raise HTTPException("must provide shares", 403)

    quantity = int(shares)
    if quantity < 1:
        raise HTTPException("number of shares must be 1 or greater", 403)

    stock = lookup(symbol)
    if stock is None:
        raise HTTPException("invalid stock symbol", 404)

    cash = storage.get_cash(session["user_id"])
    stocks_cost = stock["price"] * quantity
    if not cash >= stocks_cost:
        raise HTTPException("not enough cash")

    insert_transaction(stock, quantity)
    left = cash - stocks_cost
    storage.update_cash(session["user_id"], left)
    position_update(stock, quantity)

    return "", 200
Beispiel #8
0
def api_sell2():
    symbol = lookup(request.form.get("symbol"))
    shares = request.form.get("shares")

    if symbol is "":
        raise HTTPException("choose a symbol", 403)

    if shares is "":
        raise HTTPException("must provide shares", 403)

    quantity = int(shares)
    if quantity < 1:
        raise HTTPException("number of shares must be 1 or greater", 403)

    selling_quantity = int(shares)
    existing_quantity = storage.get_position(session["user_id"], symbol["symbol"])
    existing_quantity = int(existing_quantity["quantity"])
    if selling_quantity > existing_quantity:
        raise HTTPException("you don't have enough shares", 403)
    else:
        date = datetime.datetime.now()
        storage.add_transaction(session["user_id"], symbol["name"], selling_quantity * -1, symbol["price"], date,
                                symbol["symbol"])

        existing_cash = storage.get_cash(session["user_id"])
        cash = selling_quantity * symbol["price"] + existing_cash
        storage.update_cash(session["user_id"], cash)

        if selling_quantity < existing_quantity:
            new_quantity = existing_quantity - selling_quantity
            storage.update_position_quantity(session["user_id"], symbol["symbol"], new_quantity)
        elif selling_quantity == existing_quantity:
            storage.delete_position(session["user_id"], symbol["symbol"])
        return "", 200
Beispiel #9
0
 def handle_error(self, e):
     if e.__class__ in self._error_handlers:
         handler = self._error_handlers[e.__class__]
         result = handler(e)
         e = HTTPException(str(e))
         e.data, e.code = result if len(result) == 2 else (result, 500)
     return super(Api, self).handle_error(e)
Beispiel #10
0
    def __init__(self, description, locator="", code=400):
        self.code = code
        self.description = description
        self.locator = locator
        logging.exception(description)

        HTTPException.__init__(self)
Beispiel #11
0
 def __init__(self, code, addr, namespace):
     self.code = code
     self.data = {
         'message':
         "fail binding address %s to tenant %s " % (addr, namespace)
     }
     HTTPException.__init__(self)
Beispiel #12
0
        def wrapper(*args, **kwargs):
            if not os.environ.get('CLIENT_SECRET_KEY'):
                raise HTTPException(
                    'Set CLIENT_SECRET_KEY in environment variable')
            if not os.environ.get('CLIENT_AUDIENCE'):
                raise HTTPException(
                    'Set CLIENT_AUDIENCE in environment variable')

            try:
                token = get_token()
                payload = jwt.decode(
                    token,
                    os.environ.get('CLIENT_SECRET_KEY'),
                    verify=True,
                    algorithms=['HS512'],
                    audience=os.environ.get('CLIENT_AUDIENCE'))

                if payload.get('user_id'):
                    request.user_id = payload['user_id']
                    validate_scope(scope, payload['access'][0])
                    return func(*args, **kwargs)
                else:
                    raise Forbidden('Incomplete token. Please login!')

            except jwt.ExpiredSignatureError:
                raise Forbidden('This token has expired. Please login!')
            except jwt.InvalidTokenError:
                raise Forbidden('Invalid token. Please login!')
Beispiel #13
0
def register():
    """Register user"""
    if request.method == "POST":
        username = request.form.get("username")
        password = request.form.get("password")
        conf_passw = request.form.get("confirmation")
        if not username:
            raise HTTPException("must provide username", 403)
        elif not password:
            raise HTTPException("must provide password", 403)
        elif not conf_passw:
            raise HTTPException("must provide password confirmation", 403)

        if password != conf_passw:
            raise HTTPException("different passwords, must be the same", 403)
        else:
            hash_pass = generate_password_hash(password)
            rows = db.execute("SELECT * FROM users WHERE username = :username",
                              username=request.form.get("username"))
            if len(rows) == 0:
                db.execute(
                    f"INSERT INTO users (username, hash, cash) VALUES ('{username}', '{hash_pass}', '10000')"
                )
                return redirect("/")
            else:
                raise HTTPException("this username is already created")
    else:
        return render_template("register.html")
Beispiel #14
0
 def wrapper(*args, **kwargs):
     assert request
     url = request.base_url
     url_path = urlparse(url).path
     dashboards = Dashboard.query.filter(
         Dashboard.url.ilike(f"%{url_path}")).all()
     if not dashboards:
         log(log.WARNING, "Can not find dashboard for url:[%s]", url)
         raise HTTPException(
             description=f"Access denied for unknown dashboard URL {url}")
     for dash in dashboards:
         dash_url_path = urlparse(dash.url).path
         if dash_url_path != url_path:
             continue
     if not current_user.is_authenticated:
         if dash.available_to_unregistered_user:
             return route_method(*args, **kwargs)
         log(log.WARNING, "Access denied for unauthorized user")
         raise HTTPException(
             description="Access denied for unauthorized user")
     if current_user.authenticated:
         if dash.available_to_registered_user:
             return route_method(*args, **kwargs)
     if dash.role:
         for role in dash.role:
             for user in role.user:
                 if user.id == current_user.id:
                     return route_method(*args, **kwargs)
     else:
         return redirect(url_for("main.index"))
     log(log.WARNING, "Access denied for [%s]", current_user.role.name)
     raise HTTPException(
         description=f"Access denied for {current_user.role.name}")
Beispiel #15
0
 def __init__(self, data_request_id):
     HTTPException.__init__(self)
     self.code = 404
     self.data = dict()
     self.data[
         'message'] = "There is not an api response associated to the data request with id '{0}'".format(
             data_request_id)
Beispiel #16
0
    def __init__(self, description=None, request=None, user=None):
        if user is not None and description is None:
            description = "The requested record is locked by user : {}.".format(
                user)

        self.user = user
        HTTPException.__init__(self, description, request)
        return
Beispiel #17
0
 def __init__(self, user_id):
     HTTPException.__init__(self)
     self.code = 404
     self.data = {
         'message':
         "There is no account associated to this user_id: {} was not found."
         .format(user_id)
     }
Beispiel #18
0
def abort(response, status_code=None):
    if isinstance(response, basestring):
        response = make_response(response)
    if status_code:
        response.status_code = status_code
    e = HTTPException(response=response)
    e.code = getattr(response, 'status_code', 0)
    raise e
Beispiel #19
0
    def __init__(self, description, locator="", code=400):
        self.code = code
        self.description = description
        self.locator = locator
        msg = 'Exception: code: {}, locator: {}, description: {}'.format(self.code, self.description, self.locator)
        LOGGER.exception(msg)

        HTTPException.__init__(self)
Beispiel #20
0
 def __init__(self, account_number, amount, currency):
     HTTPException.__init__(self)
     self.code = 409
     self.data = {
         'message':
         "Insufficient funds to perform a {0} {1} withdrawal, account_number {2}."
         .format(amount, currency, account_number)
     }
Beispiel #21
0
 def __init__(self, data, description=None):
     """
     :param: data: A dictionary containing the field errors that occured
     :param: description: Optional description to send through
     """
     HTTPException.__init__(self)
     self.description = description
     self.data = data
Beispiel #22
0
 def __init__(self, account_number):
     HTTPException.__init__(self)
     self.code = 404
     self.data = {
         'message':
         "The Account whit this account_number: {} was not found.".format(
             account_number)
     }
Beispiel #23
0
 def __init__(self, user_id, pin):
     HTTPException.__init__(self)
     self.code = 401
     self.data = {
         'message':
         "The User your trying to process is not validate. [user_id: {} and pin: {}]."
         .format(user_id, pin)
     }
Beispiel #24
0
    def test_handle_error_401_sends_challege_default_realm(self, api):
        exception = HTTPException()
        exception.code = 401
        exception.data = {'foo': 'bar'}

        resp = api.handle_error(exception)
        assert resp.status_code == 401
        assert resp.headers['WWW-Authenticate'] == 'Basic realm="flask-restplus"'
Beispiel #25
0
def test_handle_http_error_pass(app):
    """Assert that the RoutingException is passed through the handler."""
    with app.app_context():
        err = HTTPException(description='description')
        err.code = 200
        response = errorhandlers.handle_http_error(err)

        assert response.status_code == 200
Beispiel #26
0
    def __init__(self, description, locator="", code=400):
        self.code = code
        self.description = description
        self.locator = locator
        msg = 'Exception: code: %s, locator: %s, description: %s' % (self.code, self.description, self.locator)
        LOGGER.exception(msg)

        HTTPException.__init__(self)
Beispiel #27
0
def abort(response, status_code=None):
    if isinstance(response, basestring):
        response = make_response(response)
    if status_code:
        response.status_code = status_code
    e = HTTPException(response=response)
    e.code = getattr(response, 'status_code', 0)
    raise e
Beispiel #28
0
 def __init__(self, user_name, password):
     HTTPException.__init__(self)
     self.code = 404
     self.data = {
         'message':
         "The User with user_name: {} and password: {} was not found.".
         format(user_name, password)
     }
Beispiel #29
0
    def test_handle_error_401_sends_challege_default_realm(self, api):
        exception = HTTPException()
        exception.code = 401
        exception.data = {"foo": "bar"}

        resp = api.handle_error(exception)
        assert resp.status_code == 401
        assert resp.headers["WWW-Authenticate"] == 'Basic realm="flask-restx"'
Beispiel #30
0
def test_handle_request_error():
    #handle_request_error(error=None,request=None,level='info')
    with app.app_context():
        from shotglass2.takeabeltof.utils import handle_request_error
        error = HTTPException()
        error.code=404
        result = handle_request_error(error,None)
        assert "Request status: 404" in result
Beispiel #31
0
 def __init__(self, user_id, pin):
     HTTPException.__init__(self)
     self.code = 404
     self.data = {
         'message':
         "The User with user_id: {} and pin: {} was not found.".format(
             user_id, pin)
     }
Beispiel #32
0
    def get(self, **kwargs):
        """Implement the GET /sru/documents."""
        operation = flask_request.args.get('operation', None)
        query = flask_request.args.get('query', None)
        version = flask_request.args.get('version', '1.1')
        start_record = max(int(flask_request.args.get('startRecord', 1)), 1)
        maximum_records = min(
            int(
                flask_request.args.get(
                    'maximumRecords',
                    current_app.config.get('RERO_SRU_NUMBER_OF_RECORDS',
                                           100))),
            current_app.config.get('RERO_SRU_MAXIMUM_RECORDS', 1000))
        # TODO: enable es query string
        # query_string = flask_request.args.get('q', None)
        if operation == 'searchRetrieve' and query:  # or query_string:
            try:
                query_string = parse(query).to_es()
            except Diagnostic as err:
                response = Response(err.xml_str())
                response.headers['content-type'] = 'application/xml'
                raise HTTPException(response=response)

            search = DocumentsSearch().query('query_string',
                                             query=query_string)
            records = []
            search = search[(start_record - 1):maximum_records +
                            (start_record - 1)]
            for hit in search.execute():
                records.append({
                    '_id': hit.meta.id,
                    '_index': hit.meta.index,
                    '_source': hit.to_dict(),
                    '_version': 0
                })

            result = {
                'hits': {
                    'hits': records,
                    'total': {
                        'value': search.count(),
                        'relation': 'eq'
                    },
                    'sru': {
                        'query': query,
                        'query_es': query_string,
                        'start_record': start_record,
                        'maximum_records': maximum_records
                    }
                }
            }
            return self.make_response(pid_fetcher=document_id_fetcher,
                                      search_result=result)

        explain = Explain('api/sru/documents')
        response = Response(str(explain))
        response.headers['content-type'] = 'application/xml'
        raise HTTPException(response=response)
Beispiel #33
0
 def __init__(self, account_number, amount, currency, workflow_messages):
     HTTPException.__init__(self)
     workflow_messages.\
         append("ERROR MESSAGE: Insufficient funds to perform a {0} {1} withdrawal, account_number {2}.".
                format(amount, currency, account_number))
     self.code = 409
     self.data = {
         'message': workflow_messages
     }
Beispiel #34
0
def http_exception_to_response(e: HTTPException):
    """Convert a werkzeug HTTP exception to a requests.Response object"""
    response = Response()
    response.status_code = e.code
    response.headers.update(dict(e.get_headers()))
    body = e.get_body()
    response.headers["Content-Length"] = str(len(str(body or "")))
    response._content = body
    return response
Beispiel #35
0
    def __init__(self, title=None, description=None, response=None):
        """
        :param title: Title of the problem.
        :type title: str
        """
        ConnexionException.__init__(self)
        HTTPException.__init__(self, description, response)

        self.title = title or self.name
Beispiel #36
0
 def __init__(self, user_id, pin, workflow_messages):
     HTTPException.__init__(self)
     workflow_messages. \
         append("ERROR MESSAGE: The User your trying to process is not validate. [user_id: {} and pin: {}].".
                format(user_id, pin))
     self.code = 401
     self.data = {
         'message': workflow_messages
     }
Beispiel #37
0
    def test_handle_error_401_sends_challege_default_realm(self):
        api = restplus.Api(self.app, serve_challenge_on_401=True)
        exception = HTTPException()
        exception.code = 401
        exception.data = {'foo': 'bar'}

        with self.app.test_request_context('/foo'):
            resp = api.handle_error(exception)
            self.assertEqual(resp.status_code, 401)
            self.assertEqual(resp.headers['WWW-Authenticate'],
                             'Basic realm="flask-restful"')
Beispiel #38
0
    def __init__(message=None, data=None, code=400, **kwargs):
        data = data or kwargs
        if instanceof(message, str):
            data, message = message, None
        if message:
            data["message"] = message

        response = jsonify(status="fail", data=data)
        response.status_code = status_code
        HTTPException.__init__(self, message, response)
        self.code = code
Beispiel #39
0
 def __init__(message, code=500, data=None, **kwargs):
     data = data or kwargs
     response_dict = {"status": "error", "message": message}
     if code != 500:
         response_dict["code"] = code
     if data:
         response_dict["data"] = data
     response = jsonify(response_dict)
     response.status_code = status_code
     HTTPException.__init__(self, message, response)
     self.code = code
Beispiel #40
0
	def __init__(self, e):
		"""
		param: e: parent exception to wrap and manipulate
		"""
		HTTPException.__init__(self)
		self.data = {"name": self.name}
		bits = e.message.split("\n")
		if len(bits) > 1:
			self.data["error"] = bits[0]
			self.data["message"] = " ".join(bits[1:]).strip()
		else:
			self.data["message"] = " ".join(bits).strip()
Beispiel #41
0
def create_app(settings_override=None, register_security_blueprint=False):
    app = factory.create_app(__name__, __path__, settings_override, register_security_blueprint)

    # Init API endpoints for models
    api_manager.init_app(app)

    # Setup security async email send
    security_ctx = app.extensions['security']

    @security_ctx.send_mail_task
    def delay_security_email(msg):  # pylint: disable=unused-variable
        tasks.send_security_email.delay(msg)

    # Register custom error handlers so they all return JSON
    if not app.debug:
        for http_exception_class in HTTPException.__subclasses__():
            app.errorhandler(http_exception_class.code)(handle_error)

    return app
Beispiel #42
0
 def __init__(self, article_name, original_link, description=None):
     HTTPException.__init__(self, description)
     self.article_name = article_name
     self.original_link = original_link
Beispiel #43
0
 def get_headers(self, environ):
     headers = HTTPException.get_headers(self, environ)
     headers.append(('WWW-Authenticate', 'Basic realm="MCM API"'))
     return headers
Beispiel #44
0
 def __init__(self, message, code=None):
     HTTPException.__init__(self, message)
     if code is not None:
         self.code = code
Beispiel #45
0
 def abort(self, response):
     e = HTTPException(response=response)
     e.code = getattr(response, 'status_code', 0)
     raise e
Beispiel #46
0
 def __init__(self, valid_methods=None, description=None):
     """Takes an optional list of valid http methods
     starting with werkzeug 0.3 the list will be mandatory."""
     HTTPException.__init__(self, description)
     self.valid_methods = valid_methods
Beispiel #47
0
def http_ensure(case, msg, code=400):
    "if not case, raise a client error exception (by default)"
    if not case:
        ex = HTTPException(msg)
        ex.code = code
        raise ex
Beispiel #48
0
def init(self, description=None, response=None, traceback=None):
    self.traceback = traceback
    HTTPException.__init__(self, description, response)
Beispiel #49
0
 def __init__(self, message="Internal Error", response=None):
     if WERKZEUG:
         HTTPException.__init__(self, message, response)
     else:
         self.description = message
         self.response = response
Beispiel #50
0
 def __init__(self, message=''):
     # HTTPException has its own custom __init__ method, but we want the
     # usual "First argument is the message" behavior.
     HTTPException.__init__(self)
     self.message = message
Beispiel #51
0
 def __init__(self, code, description):
     HTTPException.__init__(self)
     self.code = code
     self.description = description
Beispiel #52
0
 def __init__ (self, detail='not Found', status=404):
     HTTPException.__init__ (self)
     self.detail = detail
     self.status = status
Beispiel #53
0
 def __init__(self, location):
     HTTPException.__init__(self)
     self.location = location
Beispiel #54
0
 def __init__(self, msg='', code=1):
     HTTPException.__init__(self)
     self.response = jsonify(dict(error_code=code, error_msg=msg))
Beispiel #55
0
 def get_headers(self, environ):
     headers = HTTPException.get_headers(self, environ)
     if self.valid_methods:
         headers.append(('Allow', ', '.join(self.valid_methods)))
     return headers
Beispiel #56
0
 def __init__(self, _server_id, _database_name, _conn_id):
     self.sid = _server_id
     self.db = _database_name
     self.conn_id = _conn_id
     HTTPException.__init__(self)
Beispiel #57
0
 def get_headers(self):
     return HTTPException.get_headers(self) + [('Location', self.location)]
Beispiel #58
0
 def __init__(self, _tunnel_host):
     self.tunnel_host = _tunnel_host
     HTTPException.__init__(self)