-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathapp.py
304 lines (232 loc) · 10.4 KB
/
app.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
#imports
import os
from flask import Flask, render_template, request, redirect, url_for, flash, session, jsonify
from pymongo import MongoClient
from werkzeug.security import generate_password_hash, check_password_hash
from flask_wtf import FlaskForm
from wtforms import StringField, PasswordField, SelectField, RadioField
from wtforms.validators import DataRequired, EqualTo
from bson.objectid import ObjectId
from datetime import datetime, timezone
import requests
import json
import sys
app = Flask(__name__)
app.config['SECRET_KEY'] = os.urandom(24)
MONGO_URI = "mongodb+srv://laylashihab60:[email protected]/?retryWrites=true&w=majority&appName=HelpHive"
client = MongoClient(MONGO_URI)
db = client["HelpHive"]
users_collection = db.loginInfo
reports_collection = db.reports
class LoginForm(FlaskForm):
username = StringField('Username', validators=[DataRequired()])
password = PasswordField('Password', validators=[DataRequired()])
class RegistrationForm(FlaskForm):
username = StringField('Username', validators=[DataRequired()])
password = PasswordField('Password', validators=[DataRequired()])
confirm_password = PasswordField('Confirm Password', validators=[DataRequired(), EqualTo('password', message='Passwords must match')])
class UpdateProfileForm(FlaskForm):
username = StringField('Username')
password = PasswordField('Password')
confirm_password = PasswordField('Confirm Password', validators=[EqualTo('password', message='Passwords must match')])
class IncidentReportForm(FlaskForm):
category = SelectField("Category", choices=[('1', 'Snowstorm'),
('2', 'Fire'),
('3', 'Drought'),
('4', 'Accident'),
('5', 'Tornado'),
('6', 'Icy'),
('7', 'Available Resources')
],
validators=[DataRequired()])
resources = RadioField("Resources Needed", choices=[('1', 'Yes'), ('2', 'No')], validators=[DataRequired()])
severity = RadioField("Severity", choices=[('1', 'Low'), ('2', 'Medium'), ('3', 'High')], validators=[DataRequired()])
streetAddress = StringField('Street Address', validators=[DataRequired()])
class DeleteReport(FlaskForm):
report = SelectField("Report",validators=[DataRequired()])
@app.route('/', methods=['GET', 'POST'])
def index():
form = LoginForm()
if form.validate_on_submit():
username = form.username.data
password = form.password.data
# Check if the user exists and verify password
user = users_collection.find_one({"username": username})
if user and check_password_hash(user['password'], password):
#if the login is successful, stores username
session['loggedInUser'] = username
flash('Login successful!', 'success')
return redirect(url_for('dashboard'))
else:
flash('Invalid username or password', 'danger')
return render_template('login.html', form=form)
@app.route('/register', methods=['GET', 'POST'])
def register():
form = RegistrationForm()
if form.validate_on_submit():
username = form.username.data
password = form.password.data
hashed_password = generate_password_hash(password)
# Check if the username already exists
if users_collection.find_one({"username": username}):
flash('Username already exists', 'danger')
return redirect(url_for('register'))
session['loggedInUser'] = username
# Insert the new user into the database
users_collection.insert_one({
"username": username,
"password": hashed_password
})
flash('Registration successful!', 'success')
return redirect(url_for('dashboard'))
return render_template('register.html', form=form)
def escape_special_chars(value):
if isinstance(value, str):
return value.replace('"', '\\"').replace("'", "\\'")
return value
@app.route('/dashboard')
def dashboard():
locations = reports_collection.find()
location_data = []
for location in locations:
location_info = {
"category": escape_special_chars(location.get('category')),
"resources": escape_special_chars(location.get('resources')),
"severity": escape_special_chars(location.get("severity")),
"address": escape_special_chars(location.get("address")),
"lat": escape_special_chars(location.get("lat")),
"lng": escape_special_chars(location.get("lng")),
}
location_data.append(location_info)
locations_json = json.dumps(location_data)
print(locations_json, file=sys.stderr)
return render_template('dashboard.html', locations_json=locations_json)
@app.route('/userReports', methods=["GET", "POST"])
def userReports():
form = DeleteReport()
loggedInUser = session.get('loggedInUser')
if loggedInUser:
# finds user's report documents
loggedInUser = session.get('loggedInUser')
reports_docs = reports_collection.find({"username":loggedInUser})
docs_list = []
#iterates through report documents
for doc in reports_docs:
docs_list.append(doc)
reports = docs_list
CATEGORY_MAPPING = {
'1': 'Snowstorm',
'2': 'Fire',
'3': 'Drought',
'4': 'Accident',
'5': 'Tornado',
'6': 'Icy',
'7': 'Available Resources'
}
choiceList = {}
# translates all categories into words
count = 1
for report in reports:
report['category'] = CATEGORY_MAPPING[report['category']]
choiceList[report["_id"]] = str(count) + ":\t" + str(report["category"]) + ":\t" + str(report["address"])
count += 1
form.report.choices = [(key, value) for key, value in choiceList.items()]
if form.validate_on_submit():
toDeleteValue = request.form['report'] # Get the selected report
reports_collection.delete_one({"_id": ObjectId(toDeleteValue)}) # Use `toDelete` to delete
flash('Report Deleted!', 'success')
return redirect(url_for('userReports'))
return render_template('userReports.html', form =form)
@app.route('/profile', methods=['GET', 'POST'])
def profile():
form = UpdateProfileForm()
session.pop('_flashes', None)
if form.validate_on_submit():
username = form.username.data
password = form.password.data
# finds user document
loggedInUser = session.get('loggedInUser')
document = users_collection.find_one({"username": loggedInUser})
if document:
stored_password = document["password"]
if form.password.data == "":
hashed_password = stored_password
else:
hashed_password = generate_password_hash(password)
oldvalues = {"username":loggedInUser, "password":document["password"]}
newvalues = { "$set": { "username": username, "password":hashed_password } }
# Check if the username already exists
if users_collection.find_one({"username": username}):
flash('Username already exists', 'danger')
return redirect(url_for('profile'))
else:
# updates the new values
users_collection.update_one(oldvalues,newvalues)
flash('Changes Saved!', 'success')
loggedInUser = username
return render_template('profile.html', form=form)
@app.route('/incidentReport', methods=['GET', 'POST'])
def incidentReport():
form = IncidentReportForm()
loggedInUser = session.get('loggedInUser')
if loggedInUser:
if form.validate_on_submit():
category = request.form['category']
resources = request.form['resources']
severity = request.form['severity']
timestamp = datetime.now(timezone.utc)
result = is_valid_address(request.form['streetAddress'])
check = result[0]
lat = result[1]
lng = result[2]
if check:
address = request.form['streetAddress']
elif not check:
flash('Invalid Address', 'danger')
return redirect(url_for('incidentReport'))
report = {
"username":loggedInUser,
"category": category,
"resources": resources,
"severity": severity,
"timestamp": timestamp,
"address": address,
"lat":lat,
"lng":lng
}
reports_collection.insert_one(report)
flash("Report Submitted!", 'success')
return redirect(url_for('incidentReport'))
return render_template('incidentReport.html', form=form)
def is_valid_address(address):
api_key = "8757fcae3af24a7e88298e5841a4ddaf"
url = f"https://api.opencagedata.com/geocode/v1/json?q={address}&key={api_key}"
response = requests.get(url)
data = response.json()
# Check if the API returned results
if data['results']:
# Get the first result
result = data['results'][0]
# Check confidence level (e.g., minimum threshold of 8)
confidence = result.get('confidence', 0)
components = result.get('components', {})
if confidence >= 3.5 and 'road' in components:
fulladdress = address + ", West Lafayette, IN, 47907"
lat,lng = get_geocode(fulladdress, api_key)
if (lng < -86.7014 and lng > -87.0067) and (lat > 40.3008 and lat < 40.5102):
return (True, lat, lng)
# No results indicate an invalid address
res = (False, 1,1)
return res
def get_geocode(address, api_key):
url = f"https://api.opencagedata.com/geocode/v1/json?q={address}&key={api_key}"
response = requests.get(url)
data = response.json()
if data['results']:
lat = data['results'][0]['geometry']['lat']
lng = data['results'][0]['geometry']['lng']
return lat, lng
else:
return 1, 1
if __name__ == '__main__':
app.run(debug=True)