-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.py
307 lines (281 loc) · 11.9 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
305
306
from pymongo import MongoClient
from bson.objectid import ObjectId
from flask import Flask, render_template, request, redirect, session, url_for, escape, flash
from datetime import datetime
import pytz
from tzlocal import get_localzone
from werkzeug.security import generate_password_hash, check_password_hash
from functools import wraps
import math
import database
app = Flask(__name__)
#mongo stuff
client = MongoClient('mongodb://Citronnade:Citronnade@ds031271.mongolab.com:31271/softdev2015')
db = client['softdev2015'] #database in softdev2015
locations = db['locations'] #collection
comments = db['comments'] #collection
users = db['users'] #collection
app.secret_key = "c~9%1.p4IUDj2I*QYHivZ73/407E]7<f1o_5b1(QzNdr00m7Tit)[T>C;2]5"
#timezone stuff
tz = get_localzone()
def get_timestamp(loc_id):
date = ObjectId(loc_id).generation_time
date = date.astimezone(tz)
date = date.strftime("%b %d, %Y at %I:%M %p")
return date
#for pages that require login
def login_required(f):
@wraps(f)
def inner(*args, **kwargs):
if "username" in session:
return f(*args, **kwargs)
return redirect(url_for("login")) #maybe need this to be sth else
return inner
#for pages that cannot use login
def nologin(f):
@wraps(f)
def inner(*args, **kwargs):
if "username" in session:
flash(session['username'] + " is logged in!")
return redirect(url_for("index")) # I have no idea what it is yet
return f(*args, **kwargs)
return inner
def rated():
if request.method == "POST":
if "username" in session:
user = database.get_user(session['username'])
if "upvote" in request.form:
_id = request.form['upvote']
loc = database.get_location(_id)
locations.update(loc,{'$pull':{'downvotes':user['_id']},'$push':{'upvotes':user['_id']}},upsert=False,multi=False)
#locations.update(loc,{'$push':{'upvotes':user['_id']}},upsert=False,multi=False)
elif "downvote" in request.form:
_id = request.form['downvote']
loc = database.get_location(_id)
locations.update(loc,{'$pull':{'upvotes':user['_id']},'$push':{'downvotes':user['_id']}},upsert=False,multi=False)
#locations.update(loc,{'$push':{'downvotes':user['_id']}},upsert=False,multi=False)
@app.route('/', methods=['GET','POST'])
#@app.route('/index')
#@app.route('/home')
def index():
rated()
locs = database.get_locations()
locs = database.sort_votes(locs)
paginator = range(1, int(math.ceil(len(locs)/10.0))+1)
page=1
if request.method=="GET":
page = request.args.get('page')
if page==None:
page=1
page = int(page)
locs = database.paginate(locs, page)
if 'username' in session:
user = database.get_user(session['username']);
return render_template("front.html", session=session,users=users,locations=locs,get_timestamp=get_timestamp, get_votes=database.get_votes_pst,user=user, page=page, paginator=paginator)
return render_template("front.html", session=session,users=users,locations=locs,get_timestamp=get_timestamp, get_votes=database.get_votes_pst, page=page,paginator=paginator)
@app.route('/account', methods=["GET", "POST"])
@login_required
def account():
error=""
isError=False
success=""
isSuccess=False
if request.method == "POST":
newPass = request.form['newPass']
confirmNewPass = request.form['confirmNewPass']
oldPass = request.form['oldPass']
if newPass == "" or confirmNewPass == "" or oldPass == "":
error = "Did you remember to fill out the entire form? (no)"
isError=True
elif newPass!= confirmNewPass:
error = "Your passwords don't match. Please try again!"
isError=True
elif not database.check_login(session['username'], oldPass):
error = "You typed in the wrong password..."
isError=True
else:
success = "Okay! Your password has now been successfully changed."
isSuccess=True
database.set_password(session['username'], newPass)
print newPass
return render_template("account.html", error=error, success=success, isError=isError, isSuccess=isSuccess)
@app.route('/about')
def about():
return render_template("about.html")
@app.route('/users/<username>')
@login_required
def myposts(username=None):
user = database.get_user(username)
ids = user['bizcuits'];
print ids
#locs = database.get_locations()
locs = [database.get_location(i) for i in ids]
locs = [x for x in locs if x != None]
print locs
#locs = [x for x in locs if x['author'] == user]
#print locs
#print user['username']
return render_template("myposts.html",locations=locs, session=session,get_timestamp=get_timestamp, username=username)
@app.route('/post/<postid>', methods=["GET","POST"])
def post(postid=None):
isError = False
error = ""
curr_loc = database.get_location(postid)
print curr_loc
curr_comments = database.get_comments(postid)
if request.method == "GET":
if 'username' in session:
user = database.get_user(session['username']);
return render_template("post.html", location=curr_loc,get_timestamp=get_timestamp, comments=curr_comments, get_votes=database.get_votes_pst,postid=postid,session=session,user=user)
return render_template("post.html", location=curr_loc,get_timestamp=get_timestamp, comments=curr_comments, get_votes=database.get_votes_pst,postid=postid,session=session)
else:
if 'username' in session:
user=database.get_user(session['username']);
rated()
postid = postid
if "content" in request.form:
content = request.form['content']
if content == "":
error = "You didn't write anything!"
isError=True
return render_template("post.html", error=error, isError=isError, location=curr_loc, get_timestamp=get_timestamp, comments=curr_comments, get_votes=database.get_votes, postid=postid, session=session, user=user)
elif "username" in session:
author = session['username']
user = database.get_user(author)
database.add_comment(None, content, postid, author)
users.update(
user,
{'$push':{'comments':postid}}
)
#return redirect(url_for("post",postid=postid,session=session))
#return redirect(url_for("post",postid=postid))
return redirect(url_for("post",postid=postid,session=session, isError=isError, error=error))
@app.route('/search', methods = ['GET','POST'])
def search():
error = ""
isError=False
if request.method == "POST":
#location = request.form['query']
#response = database.search(location)
zipcode = request.form['zipcode']
keywords = request.form['keyword']
if zipcode == "" and keywords == "":
error = "You forgot to enter values!"
isError=True
return render_template("results.html", error=error, isError=isError)
if keywords != None:
keywords = keywords.split()
response = database.search(keywords, zipcode)
#print '~~~~~~~~~~~~~~~~~~~~~'
#print response
if response != []:
sortedlocs = database.sort_votes(response)
return render_template("results.html", session=session, users=users, locations=sortedlocs, get_timestamp=get_timestamp, get_votes=database.get_votes_pst, isError=isError)
else:
error = "There aren't any Bizcuits in this location yet."
isError=True
return render_template("results.html", error=error, isError=isError)
@app.route('/submit', methods= ["GET", "POST"])
@login_required
def submit():
error = ""
isError = False
if request.method == "POST":
name = request.form['locationName']
address = request.form['streetAddress']
zipcode = request.form['zipcode']
desc = request.form['desc']
if name == "" or address == "" or zipcode == "" or desc == "":
error = "You forgot to fill out something!"
return render_template("submit.html", error=error, isError=True)
postid = database.add_location(None, name, address, session['username'], zipcode, desc)
if postid:
#submission should work here
user = database.get_user(session['username'])
users.update(user,{'$push':{'bizcuits':postid}})
return redirect(url_for('post', postid=postid))
print "The location already exists."
return redirect(url_for("submit"))
elif request.method == "GET":
return render_template("submit.html", error=error, isError=isError)
@app.route('/login', methods = ["GET", "POST"])
@nologin
def login():
isError=False
error=""
if request.method == "POST":
username = request.form['loginUsername'] #assuming SSL connection so this is okay
password = request.form['loginPassword'] #jk SSL certs cost money
if database.check_login(username,password):
session['username'] = username
return redirect(url_for('index'))
else: #invalid
print "invalid login"
isError=True
error="Wrong username or password. Please try again!"
return render_template("login.html", error=error, isError=isError)
@app.route('/logout')
@login_required
def logout():
session.pop('username',None)
return redirect(url_for('index'))
@app.route('/register', methods=["GET","POST"])
@nologin
def register():
isSuccess=False
isError=False
success=""
error=""
if request.method == "POST":
username = request.form['registerUsername']
password = request.form['registerPassword']
confirmPassword = request.form['confirmPassword']
if username=="" or password=="" or confirmPassword=="":
isError=True
error="You forgot to fill out some required things..."
elif database.check_username(username):
if not password == confirmPassword: #passwords do not match
isError=True
error="Passwords do not match!"
else:
database.register_user(username,password)
isSuccess=True
success="Great! You have now successfully registered, "
success=success+username
else:
#username is taken
isError=True
error="Sorry, your username is already in use!"
return render_template("register.html", isError=isError, isSuccess=isSuccess, success=success, error=error)
@app.route('/control',methods=["GET","POST"])
def control():
if request.method == 'POST':
if 'clear-users' in request.form:
users.remove()
elif 'delete-user' in request.form:
_id = request.form['delete-user']
users.remove({'_id':ObjectId(_id)})
elif 'delete-location' in request.form:
print "OK=================================="
_id = request.form['delete-location']
print _id
print locations.remove({'_id':ObjectId(_id)})
locationsf = locations.find()
usersf = users.find()
return render_template("control.html",session=session,locations=locationsf,users=usersf)
locationsf = locations.find()
usersf = users.find()
#return render_template("control.html",session=session,locations=locations,users=users)
return render_template("control.html",session=session,locations=locationsf,users=usersf)
@app.errorhandler(400)
def error400(e):
return render_template('400.html'), 400
@app.errorhandler(404)
def error404(e):
return render_template('404.html'), 404
if __name__ == "__main__":
app.debug = True
#print client
#print db
#users.remove({'username':'CleverBot'})
app.run(port=5005)