· 5 years ago · Aug 04, 2020, 10:46 PM
1import os
2
3# https://pypi.org/project/flask-googlemaps/
4
5# Import the modules that we will want to use
6from cs50 import SQL
7from flask import Flask, flash, jsonify, redirect, render_template, request, session
8from flask_session import Session
9from flask_googlemaps import GoogleMaps
10from tempfile import mkdtemp
11from werkzeug.exceptions import default_exceptions, HTTPException, InternalServerError
12from werkzeug.security import check_password_hash, generate_password_hash
13
14from helpers import login_required
15
16# Configure application
17app = Flask(__name__)
18# Ensure that user sessions when they are logged in are not perm
19app.config["SESSION_PERMANENT"] = False
20# Ensure the location that we want to store the data for user sessions is going to be in the file system of the webserver we'll be running this application from (CS50 IDE)
21app.config["SESSION_TYPE"] = "filesystem"
22# We would like to enable sessions for this particular flask web app
23Session(app)
24
25# Ensure templates are auto-reloaded when sent and recieved
26app.config["TEMPLATES_AUTO_RELOAD"] = True
27
28# set the maps api key as config
29app.config['GOOGLEMAPS_KEY'] = "8JZ7i18MjFuM35dJHq70n3Hx4"
30
31# Initialize the extension
32GoogleMaps(app)
33
34# Make sure API key is set
35if not os.environ.get("API_KEY"):
36 raise RuntimeError("API_KEY not set")
37
38# Ensure responses aren't cached
39@app.after_request
40def after_request(response):
41 response.headers["Cache-Control"] = "no-cache, no-store, must-revalidate"
42 response.headers["Expires"] = 0
43 response.headers["Pragma"] = "no-cache"
44 return response
45
46# Configure CS50 Library to use SQLite database
47db = SQL("sqlite:///parks.db")
48
49# app route to map out 1 park
50@app.route("/")
51@login_required
52def index():
53 """Homepage with Park locator"""
54 return render_template("index.html")
55
56# app route to search all parks
57@app.route("/allparks", methods=["GET", "POST"])
58@login_required
59def allparks():
60 """Page with all parks"""
61 if request.method == "GET":
62 return render_template("allparks.html")
63
64# app route to see your saved parks
65@app.route("/myparks", methods=["GET", "POST"])
66@login_required
67def myparks():
68 """Page with all parks"""
69 if request.method == "GET":
70 return render_template("myparks.html")
71
72# app route to see all reviews of parks
73@app.route("/reviews", methods=["GET", "POST"])
74@login_required
75def reviews():
76 """Page with all parks"""
77 if request.method == "GET":
78 return render_template("reviews.html")
79
80
81# app route to register an account
82@app.route("/register", methods=["GET", "POST"])
83def register():
84 """Register user"""
85
86 if request.method == "GET":
87 return render_template("register.html")
88
89 else:
90 errors = ["Must provide username", "Must provide password", "Password and confirmation must match", "Username is taken"]
91
92 if not request.form.get("username"):
93 return render_template("register.html", errors=errors[0])
94
95 elif not request.form.get("password"):
96 return render_template("register.html", errors=errors[1])
97
98 elif request.form.get("password") != request.form.get("confirmation"):
99 return render_template("register.html", errors=errors[2])
100
101 rows = db.execute("SELECT username FROM users WHERE username = :username;",
102 username=request.form.get("username"))
103
104 if len(rows) != 0:
105 return render_template("register.html", errors=errors[3])
106
107 password_var = request.form.get("password")
108 hash_pw = generate_password_hash(password_var)
109 user_name = request.form.get("username")
110
111 db.execute("INSERT INTO users(username,hash) VALUES (?,?);",
112 user_name, hash_pw)
113
114 success_login = ["Registered!"]
115
116 # select the username from our db as the current session and store it as the current users logged in session, it's the first index in the list of dicts returned
117 session["user_id"] = db.execute("SELECT id FROM users WHERE username = :username;",
118 username=user_name) [0]["id"]
119
120 return render_template("index.html", success_login=success_login[0])
121
122@app.route("/logout")
123def logout():
124 """Log user out"""
125
126 # Forget any user_id
127 session.clear()
128
129 # Redirect user to login form
130 return redirect("/")
131
132@app.route("/login", methods=["GET", "POST"])
133def login():
134 """Log user in"""
135
136 # Forget any user_id
137 session.clear()
138
139 # User reached route via POST (as by submitting a form via POST)
140 if request.method == "POST":
141
142 # list of all potential errors that can be rendered on the buy html
143 errors = ["Must provide a username", "Must provide password", "Invalid username and/or password"]
144
145 # Ensure username was submitted
146 if not request.form.get("username"):
147 return render_template("login.html", errors=errors[0])
148
149 # Ensure password was submitted
150 elif not request.form.get("password"):
151 return render_template("login.html", errors=errors[1])
152
153 # Query database for username
154 rows = db.execute("SELECT * FROM users WHERE username = :username",
155 username=request.form.get("username"))
156
157 # Ensure username exists and password is correct
158 if len(rows) != 1 or not check_password_hash(rows[0]["hash"], request.form.get("password")):
159 return render_template("login.html", errors=errors[2])
160
161 # Remember which user has logged in
162 session["user_id"] = rows[0]["id"]
163
164 # Redirect user to home page
165 return redirect("/")
166
167 # User reached route via GET (as by clicking a link or via redirect)
168 else:
169 return render_template("login.html")
170