forked from celestekilgore/friender-backend
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.py
233 lines (175 loc) · 6.44 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
from forms import LoginForm, RegisterForm, RelationshipForm
from models import db, connect_db, User, Relationship
from api import add_image, get_zip_codes_around_radius, form_errors_to_list
import os
from dotenv import load_dotenv
from flask import Flask, jsonify, request
from flask_cors import CORS
from functools import wraps
from sqlalchemy import and_, or_
from sqlalchemy.exc import IntegrityError
import jwt
from jwt.exceptions import DecodeError
load_dotenv()
app = Flask(__name__)
CORS(app)
app.config['SQLALCHEMY_DATABASE_URI'] = os.environ['DATABASE_URL']
app.config['SQLALCHEMY_ECHO'] = False
app.config['DEBUG_TB_INTERCEPT_REDIRECTS'] = False
app.config['SECRET_KEY'] = os.environ['SECRET_KEY']
connect_db(app)
def token_required(f):
"""Decorator for protecting routes."""
@wraps(f)
def decorator(*args, **kwargs):
token = None
# ensure the jwt-token is passed with the headers
if 'x-access-token' in request.headers:
token = request.headers['x-access-token']
if not token: # throw error if no token provided
return (jsonify({"message": "Unauthorized"}), 401)
try:
# decode the token to obtain user public_id
data = jwt.decode(
token, app.config['SECRET_KEY'], algorithms=['HS256'])
except DecodeError:
return (jsonify({"message": "Unauthorized"}), 401)
current_user = User.query.filter_by(username=data['username']).first()
if current_user is None:
return (jsonify({"message": "Unauthorized"}), 401)
# Return the user information attached to the token
return f(current_user, *args, **kwargs)
return decorator
@app.post("/login")
def login():
"""Authenticates username and password and returns JWT token."""
form = LoginForm(data=request.json, meta={"csrf": False})
if not form.validate():
return (jsonify({"errors": form_errors_to_list(form.errors)}), 400)
token = User.authenticate(
form.username.data,
form.password.data,
)
if not token:
return (jsonify({"errors": ["Invalid username/password."]}), 400)
return jsonify({"token": token})
@app.post("/register")
def register():
"""Validates register data, creates new user, and returns JWT token."""
form = RegisterForm(data=request.form, meta={"csrf": False})
if not form.validate():
return (jsonify({"errors": form_errors_to_list(form.errors)}), 400)
image_url = add_image(form.image.data) if form.image.data else None
try:
token = User.signup(
form.username.data,
form.password.data,
form.zip_code.data,
form.friend_radius.data,
form.hobbies.data,
form.interests.data,
image_url
)
db.session.commit()
except IntegrityError:
return (jsonify({"errors": ["Username already taken."]}), 400)
return jsonify({"token": token})
@app.get("/users/<string:username>")
@token_required
def get_user(current_user, username):
"""Takes username and returns user."""
user = User.query.filter_by(username=username).first()
if not user:
return (jsonify({"errors": ["User not found."]}), 400)
return jsonify({
"user": {
"username": user.username,
"zip_code": user.zip_code,
"friend_radius": user.friend_radius,
"hobbies": user.hobbies,
"interests": user.interests,
"image": user.image
}
})
@app.get("/users/<string:username>/get-potential-friend")
@token_required
def get_potential_friend(current_user, username):
"""Returns potential friend user within friend radius."""
zip_codes = get_zip_codes_around_radius(
current_user.zip_code,
current_user.friend_radius
)
user = User.query.outerjoin(
Relationship,
or_(
(Relationship.owner_id == User.id) & (
Relationship.target_id == current_user.id),
(Relationship.owner_id == current_user.id) & (
Relationship.target_id == User.id),
)
).filter(
User.id != current_user.id,
User.zip_code.in_(zip_codes),
or_(
Relationship.status.is_(None),
and_(
Relationship.owner_id != current_user.id,
Relationship.status == 'pending',
),
)
).first()
if not user:
return jsonify({"user": None})
return jsonify({
"user": {
"username": user.username,
"zip_code": user.zip_code,
"friend_radius": user.friend_radius,
"hobbies": user.hobbies,
"interests": user.interests,
"image": user.image
}
})
@app.post("/users/<string:username>/establish-relationship")
@token_required
def establish_relationship(current_user, username):
"""
Takes username and establishes relationship with current user based on
current user response.
"""
form = RelationshipForm(data=request.json, meta={"csrf": False})
if not form.validate():
return (jsonify({"errors": form_errors_to_list(form.errors)}), 400)
target_user = User.query.filter_by(username=username).first()
relationship = Relationship.query.get((target_user.id, current_user.id))
status = "friends" if form.response.data else "not-friends"
if relationship:
relationship.status = status
else:
status = status if status == "not-friends" else "pending"
new_relationship = Relationship(
owner_id=current_user.id,
target_id=target_user.id,
status=status
)
db.session.add(new_relationship)
db.session.commit()
return jsonify({"status": status})
@app.get("/users/<string:username>/get-friends")
@token_required
def get_friends(current_user, username):
"""Takes username and returns list of friends."""
target_user = User.query.filter_by(username=username).first()
friends = User.query.join(
Relationship,
or_(
(Relationship.owner_id == User.id) & (
Relationship.target_id == target_user.id),
(Relationship.owner_id == target_user.id) & (
Relationship.target_id == User.id),
)
).filter(
Relationship.status == "friends"
).all()
friends = [{"username": f.username, "image": f.image} for f in friends]
return jsonify({"friends": friends})