-
Notifications
You must be signed in to change notification settings - Fork 1
/
app.py
executable file
·269 lines (234 loc) · 8.1 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
#!/usr/bin/env python
import os
from datetime import datetime
from flask import Flask, abort, request, jsonify, g, url_for, make_response, request
from flask_sqlalchemy import SQLAlchemy
from passlib.apps import custom_app_context as pwd_context
from itsdangerous import (TimedJSONWebSignatureSerializer
as Serializer, BadSignature, SignatureExpired)
from sqlalchemy import and_
from functools import wraps
from flask_cors import CORS, cross_origin
# initialization
app = Flask(__name__)
cors = CORS(app)
app.config['SECRET_KEY'] = os.getenv('SECRET_KEY')
app.config['SQLALCHEMY_DATABASE_URI'] = os.getenv('DATABASE_URI')
app.config['SQLALCHEMY_COMMIT_ON_TEARDOWN'] = True
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
@app.after_request
def after_request(response):
response.headers.add('Access-Control-Allow-Credentials', 'true')
return response
# extensions
db = SQLAlchemy(app)
# models + tables
follows_table = db.Table('user_follows', db.Model.metadata,
db.Column('subscriber_id', db.Integer, db.ForeignKey('users.id'), nullable=False),
db.Column('publisher_id', db.Integer, db.ForeignKey('users.id'), nullable=False)
)
class Post(db.Model):
__tablename__ = 'posts'
id = db.Column(db.Integer, primary_key=True)
author_id = db.Column(db.Integer, db.ForeignKey('users.id'))
created_on = db.Column(db.DateTime, default=datetime.utcnow)
body_text = db.Column(db.Text)
author = db.relationship('User')
@property
def serialize(self):
"""Return object data in easily serializeable format"""
return {
'id' : self.id,
'body_text' : self.body_text,
'created_on' : str(self.created_on),
'author' : self.author.serialize
}
class User(db.Model):
__tablename__ = 'users'
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(32), index=True)
member_since = db.Column(db.DateTime, default=datetime.utcnow)
hashed_pw = db.Column(db.String(200))
follows = db.relationship(
'User', lambda: follows_table,
primaryjoin=lambda: User.id == follows_table.c.subscriber_id,
secondaryjoin=lambda: User.id == follows_table.c.publisher_id,
backref='followers'
)
posts = db.relationship('Post')
@property
def serialize(self):
"""Return object data in easily serializeable format"""
return {
'id' : self.id,
'username' : self.username
}
def hash_password(password):
return pwd_context.encrypt(password)
def verify_password(password, hashed):
return pwd_context.verify(password, hashed)
def generate_auth_token(user_id, expiration=6000):
s = Serializer(app.config['SECRET_KEY'], expires_in=expiration)
return s.dumps({'id': user_id})
def verify_auth_token(token):
s = Serializer(app.config['SECRET_KEY'])
try:
data = s.loads(token)
except SignatureExpired:
return None # valid token, but expired
except BadSignature:
return None # invalid token
user = User.query.get(data['id'])
return user
def login_required(f):
@wraps(f)
def decorated_function(*args, **kwargs):
if not request.method is 'OPTIONS' and not auth():
return abort(401)
return f(*args, **kwargs)
return decorated_function
def auth():
token = request.cookies.get('login_token')
if not token:
token = request.args.get('auth')
if not token:
return False
user = verify_auth_token(token)
if not user:
return False
g.user = user
return True
@app.route('/api/posts', methods=['POST'])
@login_required
def new_post():
body_text = request.json.get('body_text')
author_id = g.user.id
if body_text is None:
abort(400) # missing arguments
if User.query.filter_by(id=author_id).first() is None:
abort(400) # user doesn't exist
post = Post(body_text=body_text, author_id=author_id)
db.session.add(post)
db.session.commit()
return (jsonify({'post': post.id}), 201)
@app.route('/api/posts/<int:id>', methods=['DELETE'])
@login_required
def remove_post(id):
post = Post.query.get(id)
if post is None:
abort(400) #post doesn't exists
if not post.author_id is g.user.id:
abort(401)
db.session.delete(post)
db.session.commit()
return (jsonify({'deleted': True}))
@app.route('/api/posts', methods=['GET'])
@login_required
def get_posts():
id = g.user.id
posts = Post.query.filter(Post.author_id==id);
return (jsonify({'posts': [i.serialize for i in posts ]}))
@app.route('/api/me', methods=['GET'])
@login_required
def get_me():
user = g.user
return (jsonify({'user': user.serialize}))
@app.route('/api/users')
@login_required
def get_all_users():
users = User.query.all()
return jsonify({
'users': [i.serialize for i in users],
'count': len(users)
})
@app.route('/api/users/<int:id>')
@login_required
def get_user(id):
user = User.query.get(id)
if not user:
abort(400)
return jsonify(user.serialize)
@app.route('/api/follows', methods=['POST'])
@login_required
def follow():
id = g.user.id
publisher_id=request.json.get('publisher_id')
subscriber_id=id
if publisher_id is None or publisher_id == subscriber_id:
abort(400)
statement = follows_table.insert().values(publisher_id=publisher_id, subscriber_id=subscriber_id)
db.session.execute(statement)
db.session.commit()
return jsonify({'message': 'Follow successful.'})
@app.route('/api/follows', methods=['GET'])
@login_required
def get_follows():
id = g.user.id
user = User.query.get(id)
if not user:
abort(400)
return jsonify({'follows': [i.serialize for i in user.follows]})
@app.route('/api/followers', methods=['GET'])
@login_required
def get_followers():
id = g.user.id
user = User.query.get(id)
if not user:
abort(400)
return jsonify({'followers': [i.serialize for i in user.followers]})
@app.route('/api/follows/<int:publisher_id>', methods=['DELETE'])
@login_required
def stop_following(publisher_id):
id = g.user.id
statement = follows_table.delete().where(
and_(follows_table.c.publisher_id==publisher_id, follows_table.c.subscriber_id==id))
db.session.execute(statement)
db.session.commit()
return jsonify({'message': 'Unfollow successful.'})
@app.route('/api/feed', methods=['GET'])
@login_required
def get_feed():
id = g.user.id
user = User.query.get(id)
if not user:
abort(400)
follow_ids = [i.id for i in user.follows]
follow_ids.append(id)
posts = Post.query.filter(Post.author_id.in_(follow_ids)).order_by(Post.created_on.desc()).all()
return jsonify({'feed': [i.serialize for i in posts] })
@app.route('/api/login', methods=['POST'])
def app_login():
username = request.json.get('username')
password = request.json.get('password')
# try to authenticate with username/password
user = User.query.filter_by(username=username).first()
if not user or not verify_password(password, user.hashed_pw):
abort(401)
token = generate_auth_token(user.id, 6000)
resp = make_response(jsonify({'auth' : str(token)}))
resp.set_cookie('login_token', token);
return resp
@app.route('/api/logout')
@login_required
def app_logout():
resp = make_response(jsonify({'success' : True}))
resp.set_cookie('login_token', '', expires=0);
return resp
@app.route('/api/register', methods=['POST'])
def new_user():
username = request.json.get('username')
password = request.json.get('password')
if username is None or password is None:
abort(400) # missing arguments
if User.query.filter_by(username=username).first() is not None:
abort(400) # existing user
user = User(username=username, hashed_pw=hash_password(password))
db.session.add(user)
db.session.commit()
return (jsonify({'username': user.username, 'message': 'User created.'}), 201)
@app.route('/')
def inded():
return jsonify({'message': 'It lives!'})
if __name__ == '__main__':
db.create_all()
app.run()