0

I ran my finance application via Check50 but got following error regarding sell function in application.

check50 error detail

The code of my sell() function is as follows:

@app.route("/sell", methods=["GET", "POST"])
@login_required
def sell():
    """Sell shares of stock"""
    if request.method == "POST":
        symbol = request.form.get("symbol")
        shares = request.form.get("shares")

        if not shares.isdigit():
            return apology("Shares must be positive number", 400)

        q = lookup(symbol)

        db.execute("UPDATE users SET cash = cash + :amount WHERE id = :userID", amount=int(shares) * q["price"], userID=session["user_id"])
        db.execute("INSERT INTO transactions (userID, transType, symbol, shares, amount, sharePrice) VALUES (:userID, 0, :symbol, :shares, :amount, :sharePrice)", userID=session["user_id"], symbol=symbol, shares=shares, amount=int(shares) * q["price"], sharePrice=q["price"])
        db.execute("UPDATE portfolios SET shares = shares - :shares WHERE userID = :userID AND symbol = :symbol", shares=shares, userID=session["user_id"], symbol=symbol)

        return redirect("/")
    else:
        res = db.execute("SELECT * FROM portfolios WHERE userID=:userID AND shares>0", userID=session["user_id"])
        lenRes = len(res)

        if lenRes > 0:
            symbols = []

            for row in res:
                symbols.append(row["symbol"])
        else:
            return apology("No stock available to sell")

        return render_template("sell.html", symbols=symbols)

I am confused that why check50 is giving error despite of status code 400 which is expected according to check50. Kindly help

2

What happens if the number of shares sold is negative? Or higher than the owned shares? Both are not returning an HTTP status 400 with your function.

Selling a stock you don't own also should be caught in the backend, not just by restricting your form (an attacker might not use your form to create the POST request). Imagine I sold 1000 shares of AAPL without owning them. I get the money, the transaction is created, my portfolio isn't changed (as there's no entry for me and AAPL).

4
  • Thank you Blauelf. I missed the validation for number of shares owned by the user. Sep 14 '18 at 15:01
  • Just realized a negative number would have a non-digit character. But rest still applies, and you got it, so I guess that's fine... :)
    – Blauelf
    Sep 14 '18 at 15:12
  • 1
    Yes, isdigit() function validate for the negative numbers also. Sep 14 '18 at 18:00
  • I used a try:/except ValueError: block instead, because there can be strange things. Like "¹".isdigit() is True, but int("¹") crashes. In that case, I had to have an extra check for negative numbers.
    – Blauelf
    Sep 17 '18 at 15:26

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .