Skip to content

Commit 30d2306

Browse files
committed
update application.py. add sentry error logging integration. add redis configuration for user sessions. add error catching for login. update host.
1 parent af61e16 commit 30d2306

File tree

1 file changed

+50
-18
lines changed

1 file changed

+50
-18
lines changed

application.py

Lines changed: 50 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,6 @@
11
import os
2+
import sentry_sdk
3+
import redis
24
from datetime import datetime
35
from flask import Flask, flash, jsonify, redirect, render_template, request, session
46
from flask_session import Session
@@ -7,9 +9,20 @@
79
from tempfile import mkdtemp
810
from werkzeug.exceptions import default_exceptions, HTTPException, InternalServerError
911
from werkzeug.security import check_password_hash, generate_password_hash
10-
12+
from sentry_sdk.integrations.flask import FlaskIntegration
1113
from helpers import badRequest, noData, unauthorized, forbidden, notFound, login_required, lookup, usd
1214

15+
# Configure error and performance logging with Sentry
16+
sentry_sdk.init(
17+
dsn="https://4c4bfcc7d0a444089fd34b8e12a890eb@o958423.ingest.sentry.io/5907180",
18+
integrations=[FlaskIntegration()],
19+
20+
# Set traces_sample_rate to 1.0 to capture 100%
21+
# of transactions for performance monitoring.
22+
# We recommend adjusting this value in production.
23+
traces_sample_rate=0.5
24+
)
25+
1326
# Configure application
1427
application = Flask(__name__)
1528
basedir = os.path.abspath(os.path.dirname(__file__))
@@ -28,11 +41,14 @@ def after_request(response):
2841
# Custom filter
2942
application.jinja_env.filters["usd"] = usd
3043

31-
# Configure session to use filesystem (instead of signed cookies)
32-
application.config["SESSION_FILE_DIR"] = mkdtemp()
33-
application.config["SESSION_PERMANENT"] = False
34-
application.config["SESSION_TYPE"] = "filesystem"
35-
Session(application)
44+
# Configure Redis for storing the session data on the server-side
45+
application.secret_key = 'BAD_SECRET_KEY'
46+
application.config['SESSION_TYPE'] = 'redis'
47+
application.config['SESSION_PERMANENT'] = False
48+
application.config['SESSION_USE_SIGNER'] = True
49+
application.config['SESSION_REDIS'] = redis.from_url('redis://localhost:6379')
50+
# Create and initialize the Flask-Session object AFTER `app` has been configured
51+
server_session = Session(application)
3652

3753
# Configure deployemnt to use AWS RDS database
3854
if 'RDS_HOSTNAME' in os.environ:
@@ -341,15 +357,25 @@ def login():
341357
rows = Users.query.filter_by(username=request.form.get("username")).first()
342358
#("SELECT * FROM users WHERE username = :username", username=request.form.get("username"))
343359

344-
# Ensure username exists and password is correct
345-
if rows.username != request.form.get("username") or not check_password_hash(rows.hash, request.form.get("password")):
346-
return unauthorized("invalid username and/or password")
360+
# Ensure user exists
361+
try:
362+
rows.username
347363

348-
# Remember which user has logged in
349-
session["user_id"] = rows.id
364+
# NoneType is returned and therefore username does't exist in database
365+
except AttributeError:
366+
return noData("User doesn't exist")
350367

351-
# Redirect user to home page
352-
return redirect("/home")
368+
# Finish logging user in
369+
else:
370+
# Ensure username and password is correct
371+
if rows.username != request.form.get("username") or not check_password_hash(rows.hash, request.form.get("password")):
372+
return unauthorized("invalid username and/or password")
373+
374+
# Remember which user has logged in
375+
session["user_id"] = rows.id
376+
377+
# Redirect user to home page
378+
return redirect("/home")
353379

354380
# User reached route via GET (as by clicking a link or via redirect)
355381
else:
@@ -394,10 +420,12 @@ def register():
394420
# User error handling: stop empty username and password fields, stop usernames already taken, stop non-matching passwords
395421
if not username:
396422
return noData("Please enter a username")
397-
existing = Users.query.filter_by(username=username)
398423

424+
existing = Users.query.filter_by(username=username)
425+
print("EXISTING USER: ", existing)
399426
#("SELECT * FROM users WHERE username = :username", username=username)
400427
if existing == username:
428+
print("EXISTING USER ALREADY!: ", existing)
401429
return forbidden("Username already taken")
402430
password = request.form.get("password")
403431
if not password:
@@ -415,8 +443,12 @@ def register():
415443
db.session.commit()
416444
#("INSERT INTO users (username, hash) VALUES (:username, :hash)", username=username, hash=hashed)
417445

418-
# Bring user to login page
419-
return redirect("/login")
446+
# Automatically sign in after creating account
447+
rows = Users.query.filter_by(username=request.form.get("username")).first()
448+
session["user_id"] = rows.id
449+
450+
# Redirect user to home page
451+
return redirect("/home")
420452

421453

422454
@application.route("/sell", methods=["GET", "POST"])
@@ -528,6 +560,6 @@ def page_not_found(e):
528560
return render_template('404.html'), 404
529561

530562
# Run Server
563+
# Run the following in the command line: python application.py
531564
if __name__ == '__main__':
532-
application.run(debug = True)
533-
# Run the following in the command line: python application.py
565+
application.run(host='0.0.0.0') # Production server

0 commit comments

Comments
 (0)