This repository has been archived by the owner on Jul 8, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 3
/
app.py
411 lines (351 loc) · 13 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
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
# pylint: disable=W0613, E1101
# W0613 is about unused variable in 'def load_user(user_id):'
# E1101: because pylint can't handle db
"""Module for running flask and setting up endpoints"""
import os
import flask
from flask_login import current_user, login_user, logout_user, LoginManager
from sqlalchemy import true
from werkzeug.security import generate_password_hash, check_password_hash
from dotenv import load_dotenv, find_dotenv
from db_utils import (
create_channel,
create_offer,
get_all_accounts,
get_all_ads,
get_ads,
get_channels,
)
from models import db, Account, Ad, Channel
load_dotenv(find_dotenv())
app = flask.Flask(__name__)
app.config["SQLALCHEMY_DATABASE_URI"] = os.getenv("DATABASE_URL")
app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False
app.secret_key = os.getenv("SECRET_KEY")
db.init_app(app)
with app.app_context():
db.create_all()
login_manager = LoginManager()
login_manager.init_app(app)
@login_manager.user_loader
def load_user(user_id):
"""Stolen from some tutorial on flask-login. While it is not explicitly used
here, it is required by flask-login"""
return Account.query.get(int(user_id))
# set up a separate route to serve the index.html file generated
# by create-react-app/npm run build.
# By doing this, we make it so you can paste in all your old app routes
# from Milestone 2 without interfering with the functionality here.
bp = flask.Blueprint(
"bp",
__name__,
template_folder="./static/react",
)
# route for serving React page
@bp.route("/")
@bp.route("/ads")
@bp.route("/channels")
@bp.route("/login")
@bp.route("/signup")
@bp.route("/acount")
@bp.route("/new_add")
@bp.route("/new_channel")
@bp.route("/new_response")
@bp.route("/new_offer")
def index():
"""Root endpoint"""
# NB: DO NOT add an "index.html" file in your normal templates folder
# Flask will stop serving this React page correctly
return flask.render_template("index.html")
@bp.route("/handle_login", methods=["POST"])
def handle_login():
"""Handle login"""
if flask.request.method == "POST":
user = Account.query.filter_by(email=flask.request.json["email"]).first()
if user is not None and check_password_hash(
user.password, flask.request.json["password"]
):
is_login_successful = login_user(user)
return flask.jsonify(
{"is_login_successful": is_login_successful, "error_message": ""}
)
# if password is incorrect
if user is not None and not check_password_hash(
user.password, flask.request.json["password"]
):
return flask.jsonify(
{"is_login_successful": False, "error_message": "Incorrect password"}
)
# if the email is NOT present in the database, send a message saying
# “there is no user with this email” and give a link to sign up page
if user is None:
return flask.jsonify(
{
"is_login_successful": False,
"error_message": "No user with this email",
}
)
return flask.jsonify(
{"is_login_successful": False, "error_message": "Wrong method"}
)
@bp.route("/handle_signup", methods=["POST"])
def handle_signup():
"""Handle signup"""
if flask.request.method == "POST":
user = Account.query.filter_by(username=flask.request.json["username"]).first()
if user is None:
new_user = Account(
username=flask.request.json["username"],
email=flask.request.json["email"],
password=generate_password_hash(flask.request.json["password"]),
channel_owner=flask.request.json["channel_owner"],
)
db.session.add(new_user)
db.session.commit()
check_new_user = Account.query.filter_by(
email=flask.request.json["email"]
).first()
is_signup_successful = check_new_user is not None
return flask.jsonify(
{"is_signup_successful": is_signup_successful, "error_message": ""}
)
if (
flask.request.json["username"] == ""
or flask.request.json["email"] == ""
or flask.request.json["password"] == ""
):
return flask.jsonify(
{
"is_signup_successful": False,
"error_message": "Fill in all the required data",
}
)
if user is not None:
return flask.jsonify(
{
"is_signup_successful": False,
"error_message": "A user with such username/email already exists",
}
)
return flask.jsonify(
{
"is_signup_successful": False,
"error_message": "Wrong method",
}
)
@bp.route("/handle_logout", methods=["POST"])
def handle_logout():
"""Handles logout"""
logout_user()
return is_logged_in()
@bp.route("/channelowner", methods=["GET"])
def is_channel_owner():
"""returns true if current user is a channel owner"""
return flask.jsonify({"is_user_channel_owner": current_user.channel_owner})
@app.route("/getaccounts", methods=["GET"])
def get_accounts():
"""Returns all accounts"""
return flask.jsonify({"accounts": get_all_accounts()})
@bp.route("/is_logged_in", methods=["GET"])
def is_logged_in():
"""checks whether a user is logged in"""
return flask.jsonify({"isuserloggedin": current_user.is_authenticated})
@bp.route("/get_current_user", methods=["GET"])
def get_current_user():
"""returns current logged in user"""
return flask.jsonify({"current_user": current_user.username})
@bp.route("/account_info", methods=["GET", "POST"])
def account_info():
"""Return current user's JSON data"""
current_account = current_user.username
account = Account.query.filter_by(username=current_account).first()
ad_log = Ad.query.filter_by(account_id=account.id).all()
channel_log = Channel.query.filter_by(account_id=account.id).all()
ad_list = []
for i in ad_log:
ad_dict = {}
ad_dict["title"] = i.title
ad_dict["topics"] = i.topics
ad_dict["text"] = i.text
ad_dict["reward"] = i.reward
ad_list.append(ad_dict)
channel_list = []
for i in channel_log:
channel_dict = {}
channel_dict["channel_name"] = i.channel_name
channel_dict["subscribers"] = i.subscribers
channel_dict["topics"] = i.topics
channel_dict["preferred_reward"] = i.preferred_reward
channel_list.append(channel_dict)
return flask.jsonify(
{"account": current_account, "ads": ad_list, "channels": channel_list}
)
@bp.route("/return_ads", methods=["GET"])
def return_ads():
"""Returns JSON with ads"""
args = flask.request.args
if args.get("for") == "adsPage":
# return ads for ads page, filtered according to args
# trying to jsonify a list of channel objects gives an error
return flask.jsonify(
{
"success": True,
"adsData": get_ads(args),
}
)
return flask.jsonify({"ads": get_all_ads()})
@bp.route("/return_selected_channel", methods=["GET"])
def get_channels_by_id():
"""get channels by id"""
args = flask.request.args
channel = Channel.query.filter_by(id=args.get("id")).first()
if(channel != None):
return flask.jsonify(
{
"success": True,
"id": channel.id,
"ownerName": Account.query.filter_by(id=channel.owner_id).first().username,
"channelName": channel.channel_name,
"subscribers": channel.subscribers,
"topics": channel.topics,
"preferredReward": channel.preferred_reward,
}
)
else:
return flask.jsonify(
{
"success": False,
}
)
@bp.route("/create_channel", methods=["POST"])
def create_new_channel():
is_successful = create_channel(
channel_name=flask.request.json["channel_name"],
topics=flask.request.json["topic_list"],
subscribers=flask.request.json["sub_count"],
preferred_reward=flask.request.json["preferred_price"],
show_channel=flask.request.json["show_channel"])
return flask.jsonify({"success": is_successful})
@bp.route("/return_selected_ads", methods=["GET"])
def get_ads_by_id():
"""get channels by id"""
args = flask.request.args
advertisement = Ad.query.filter_by(owner_id=args.get("id")).first()
return flask.jsonify(
{
"creator_id": advertisement.creator_id,
"title": advertisement.title,
"topics": advertisement.topics,
"text": advertisement.text,
"reward": advertisement.reward,
"show_in_list": advertisement.show_in_list,
}
)
@bp.route("/return_channels", methods=["GET"])
def return_channels():
"""Returns JSON with channels"""
args = flask.request.args
if args.get("for") == "channelsPage":
# return channels for channels page, filtered acording to args
# trying to jsonify a list of channel objects gives an error
return flask.jsonify(
{
"success": True,
"channelsData": get_channels(args),
}
)
return flask.jsonify({"success": False})
@bp.route("/add_channel", methods=["POST"])
def add_channel():
"""Add channel info to database (in the first sprint it can be done only on signup)"""
# did we implement adding new channels?
pass
@bp.route("/add_Ad", methods=["POST"])
def add_ad():
"""Ads ad to the database"""
if flask.request.method == "POST":
advertisement = Ad.query.filter_by(title=flask.request.json["title"]).first()
if advertisement is None:
advertisement = Ad(
creator_id=current_user.id,
title=flask.request.json["title"],
topics=flask.request.json["topics"],
text=flask.request.json["text"],
reward=flask.request.json["reward"],
show_in_list=flask.request.json["show_in_list"],
)
db.session.add(advertisement)
db.session.commit()
new_ad = Ad.query.filter_by(topics=flask.request.json["topics"]).first()
add_ads_succesful = new_ad is not None
return flask.jsonify(
{"add_Ads_succesful": add_ads_succesful, "error_message": ""}
)
if (
flask.request.json["title"] == ""
or flask.request.json["topics"] == ""
or flask.request.json["text"] == ""
or flask.request.json["reward"] == ""
or flask.request.json["show_in_list"] == ""
):
return flask.jsonify(
{
"add_Ads_succesful": False,
"error_message": "Fill in all the required data",
}
)
if advertisement is not None:
return flask.jsonify(
{
"add_Ads_succesful": False,
"error_message": "An Ad with such title already exists",
}
)
return flask.jsonify(
{
"add_Ads_succesful": False,
"error_message": "Unknown error",
}
)
@bp.route("/get_Ad", methods=["GET", "POST"])
def get_ad():
"""Returns ad with the required id"""
# there is an error here, be careful
ad_log = Ad.query.filter_by(id=Ad.id).all()
ad_log_data = []
for advertisement in ad_log:
ad_log_data.append(
{
"id": advertisement.id,
"title": advertisement.title,
"topics": advertisement.topics,
"text": advertisement.text,
"reward": advertisement.reward,
"show_in_list": advertisement.show_in_list,
}
)
return flask.jsonify({"ad": ad_log_data})
@bp.route("/make_response", methods=["POST"])
def make_response():
"""Handles responses"""
is_successful =create_response(
creator_id = current_user.id,
ad_id= flask.request.json["ad_id"],
owner_id = flask.request.json["owner_id"],
accepted = flask.request.json["accepted"],
message= flask.request.json["message"]
)
flask.jsonify({"success": is_successful})
@bp.route("/ad_offers", methods=["POST"])
def ad_offers():
is_successful =create_offer(
creator_id = current_user.id,
channel_id= Channel.query.filter_by(channel_name=flask.request.json["channel_name"]).first().id,
owner_id = flask.request.json["owner_id"],
reward = flask.request.json["price"],
message= flask.request.json["message"]
)
flask.jsonify({"success": is_successful})
app.register_blueprint(bp)
if __name__ == "__main__":
app.run()