def buy(): """Buy share of stock""" if request.method == "GET": return render_template("buy.html") # User reached route via POST (as by submitting a form via POST) shares = int(request.form.get("shares")) symbol = request.form.get("symbol") quote = lookup(symbol) if not quote: return apology("invalid symbol", 404) price = quote['price'] value = round(shares * price, 2) user = Users.query.get(session.get("user_id")) if value > user.cash: return apology("You don't have enough cash", 406) record = Records(symbol=quote['symbol'], company_name=quote['name'], transact_type="buy", shares=shares, price=price, user_id=user.id) user.cash -= value db.session.add(record) db.session.commit() flash("Bought") return redirect(url_for('index'))
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"): return apology("must provide username", 403) # Ensure password was submitted elif not request.form.get("password"): return apology("must provide password", 403) # Query database for username user = Users.query.filter_by( username=request.form.get("username").lower()).first() # Ensure username exists and password is correct if user is None or not user.check_password( request.form.get("password")): return apology("invalid username and/or password", 403) # Remember which user loggen in session["user_id"] = user.id # Redirect user to home page return redirect(url_for('index')) # User reached route via GET (as by clicking a link or via redirect) else: return render_template("login.html")
def register(): """Register user""" # Forget any user_id session.clear() # User reached route via POST (as by submitting a form via POST) if request.method == "POST": # check password confirmation if not request.form.get('password') == request.form.get('confirmation'): return apology("passwords don't match", 403) # Ensure username was submitted if not request.form.get("username"): return apology("must provide username", 403) # Ensure password was submitted elif not request.form.get("password"): return apology("must provide password", 403) user=request.form.to_dict() alreadyExists = mongo.db.users.find_one({"username": user['username']}) del user['confirmation'] plain = request.form.get("password") user['password'] = generate_password_hash(plain, method='pbkdf2:sha256', salt_length=8) if alreadyExists: return apology("Username already exists", 400) if not alreadyExists: mongo.db.users.insert_one(user) # log user in ''' rows = db.execute("SELECT * FROM users WHERE username = :username", username=request.form.get("username"))''' #db.users.find_one({"username": session['user']}) # Remember which user has logged in #session["user_id"] = rows[0]["id"] session['user_id'] = (mongo.db.users.find_one({"username": user['username']}))['_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("register.html")
def send(): # Access database db = sqlite3.connect("boxedin.db", isolation_level=None).cursor() # Access current user's name username = db.execute("SELECT username FROM users WHERE id = ?", [session["user_id"]]).fetchall() userId = session["user_id"] if request.method == "POST": zoomlife = request.form.get("zoomText") video = request.form.get("shareVideo") meditation = request.form.get("selectMed") message = request.form.get("messageText") # Insert into database if zoomlife: packingBox("zoomlife", zoomlife) # Verify that request contains files, i.e. meme elif request.files: imgHTML = saveImage() packingBox("meme", imgHTML) elif video: video = video.replace("watch?v=", "embed/") # Save path to image videoHTML = ("<iframe width='560' height='315' src='" + video + "' frameborder='0' allowfullscreen></iframe>") packingBox("video", videoHTML) elif meditation: packingBox("meditation", meditation) elif message: packingBox("message", message) else: return apology("You don't seem to have entered anything to add...") return redirect("/send") else: # Access items from row boxList = db.execute( "SELECT zoomlife, meme, video, meditation, message FROM packages WHERE senderId = ? AND status = 0", [userId], ).fetchall() if not boxList: boxList = [()] newBox = checkNewBox() return render_template("send.html", username=username[0][0], boxList=boxList[0], newBox=newBox)
def login(): # Access database db = sqlite3.connect("boxedin.db", isolation_level=None).cursor() # User registers in form if request.method == "POST": usernameInput = request.form.get("username") passwordInput = request.form.get("password") confirmPass = request.form.get("confirmation") # Ensure username was submitted if not request.form.get("username"): return apology("Please provide a username.") # Ensure password was submitted elif not request.form.get("password"): return apology("Please provide a password.") # Query database for username userMatches = db.execute("SELECT * FROM users WHERE username = ?", [str(usernameInput)]).fetchall() # Ensure username exists and password is correct if len(userMatches) != 1 or not check_password_hash( userMatches[0][3], passwordInput): return apology("Invalid username and/or password.") # Remember which user has logged in session["user_id"] = userMatches[0][0] # Redirect user to home page return redirect("/zoomlife") else: return render_template("login.html")
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"): return apology("must provide username", 403) # Ensure password was submitted elif not request.form.get("password"): return apology("must provide password", 403) # Query database for username '''rows = db.execute("SELECT * FROM users WHERE username = :username", username=request.form.get("username"))''' userinfo=request.form.to_dict() #user = db.users.find_one({"username": user['username']}) user = mongo.db.users.find_one({"username": userinfo['username']}) # Ensure username exists and password is correct if not check_password_hash(user["password"], request.form.get("password")): return apology("invalid username and/or password", 403) # Remember which user has logged in #session["user_id"] = rows[0]["id"] session['user_id'] = (mongo.db.users.find_one({"username": user['username']}))['_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")
def quote(): """Get stock quote.""" if request.method == "GET": return render_template("quote.html") symbol = request.form.get("symbol") quote = lookup(symbol) if not quote: return apology("invalid symbol", 404) name = quote['name'] price = quote['price'] symbol = quote['symbol'] return render_template("quoted.html", name=name, price=price, symbol=symbol)
def register(): """Register user""" if request.method == "GET": return render_template("register.html") username = request.form.get("username").lower() password = request.form.get("password") check = Users.query.filter_by(username=username).first() if check is not None: return apology("Please use a different username", 400) user = Users(username=username) user.set_password(password) db.session.add(user) db.session.flush() session["user_id"] = user.id db.session.commit() flash('Registered!') return redirect(url_for('index'))
def sell(): """Sell shares of stock""" if request.method == "GET": symbols = Records.query.with_entities(Records.symbol).\ distinct().filter_by(user_id=session.get("user_id")).all() return render_template("sell.html", symbols=symbols) symbol = request.form.get("symbol") shares = int(request.form.get("shares")) record = db.session.query(db.func.sum(Records.shares).label("shares")).\ group_by(Records.user_id).filter_by(symbol=symbol, user_id=session.get('user_id')).one() if shares > record.shares: return apology( f"You can only sell { record.shares } shares or less than", 400) quote = lookup(symbol) price = quote['price'] value = round(shares * price, 2) user = Users.query.get(session.get('user_id')) user.cash += value record = Records(symbol=quote['symbol'], company_name=quote['name'], transact_type="sell", shares=int('-' + str(shares)), price=price, user_id=user.id) db.session.add(record) db.session.commit() flash('Sold') return redirect(url_for('index'))
def register(): # Access database db = sqlite3.connect("boxedin.db", isolation_level=None).cursor() # User registers in form if request.method == "POST": usernameInput = request.form.get("username") email = request.form.get("email") passwordInput = request.form.get("password") confirmPass = request.form.get("confirmation") # Query database for username userMatches = db.execute("SELECT * FROM users WHERE username = ?", [str(usernameInput)]).fetchall() # Check for existing users if len(userMatches) > 0: return apology("That username already exists.") # If username field is blank if not usernameInput: return apology("Please enter a username.") # If email field is blank if not email: return apology("Please enter an email address.") # Check if email is school email domain = re.search("@[\w.-]+", email) domain = str(domain.group()) if domain != "@sec.ycis-hk.com" and domain != "@hk.ycef.com": return apology("Please enter a YCIS HK school email address.") # If password fields are blank if not passwordInput or not confirmPass: return apology("Please enter your password twice.") # If confirmation does not match if passwordInput != confirmPass: return apology("Your password and confirmation do not match.") # Count characters and letters in password passwordLetters = sum(c.isalpha() for c in passwordInput) passwordNumbers = sum(c.isdigit() for c in passwordInput) # Match conditions if len(passwordInput ) < 8 or passwordLetters < 3 or passwordNumbers < 3: return apology("Your password is not secure.") # Insert the new user into users, storing a hash of the user’s password, not the password itself passwordHash = generate_password_hash(passwordInput) insertDataUsers = [str(usernameInput), str(email), str(passwordHash)] db.execute( "INSERT INTO users (username, email, passhash) VALUES (?, ?, ?)", insertDataUsers) # Introduce Boxed In return render_template("introduction.html") else: return render_template("register.html")
def errorhandler(e): """Handle error""" if not isinstance(e, HTTPException): e = InternalServerError() return apology(e.name, e.code)
def page_not_found(error): app.logger.error('Page not found: %s', (request.path)) return apology("Sorry, there was a server error."), 500
def page_not_found(error): app.logger.error('Page not found: %s', (request.path)) return apology("Sorry, we couldn't find that page."), 404