-
Notifications
You must be signed in to change notification settings - Fork 0
/
api.py
254 lines (187 loc) · 8.03 KB
/
api.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
from flask import Flask, request, jsonify, make_response
from flask_sqlalchemy import SQLAlchemy # Flask - SQLAlchemy interface
import uuid # Universally Unique Identifier
from werkzeug.security import generate_password_hash, check_password_hash # for password hashing and validation
import jwt # JSON Web Token
import datetime
from functools import wraps # decorator factory
# instantiate the flask app
app = Flask(__name__)
# secret key
app.config['SECRET_KEY'] = 'secretkey'
# DB
# format - 'sqlite:////{file_location}/{db_name}'
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:////mnt/c/Users/Priyanka/ToDo-Flask-Application/todo.db'
# instantiate the DB
db = SQLAlchemy(app)
# User Model
class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
public_id = db.Column(db.String(50), unique=True)
name = db.Column(db.String(50))
password = db.Column(db.String(80))
admin = db.Column(db.Boolean)
# ToDo task Model
class Todo(db.Model):
id = db.Column(db.Integer, primary_key=True)
text = db.Column(db.String(50))
complete = db.Column(db.Boolean)
user_id = db.Column(db.Integer)
def token_required(f):
@wraps(f) # decorator factory
def decorated(*args, **kwargs): # pass positional and keyword arguments
token = None
# check the header for x-access-token
if 'x-access-token' in request.headers:
token = request.headers['x-access-token']
# if no token found, return error message with status code - 401
if not token:
return jsonify({'message' : 'Token is missing!'}), 401
try:
# if JWT is valid, try this excerpt
data = jwt.decode(token, app.config['SECRET_KEY'])
current_user = User.query.filter_by(public_id=data['public_id']).first()
except:
# return JWT invalid message along with status code - 401
return jsonify({'message' : 'Token is invalid!'}), 401
return f(current_user, *args, **kwargs)
return decorated
@app.route('/user', methods=['GET'])
@token_required
def get_all_users(current_user):
# if user is not admin, get_all_users can't be performed
if not current_user.admin:
return jsonify({'message' : 'Cannot perform that function!'})
# select all enteries(users) from DB table 'User'
users = User.query.all()
output = []
for user in users:
user_data = {}
user_data['public_id'] = user.public_id
user_data['name'] = user.name
user_data['password'] = user.password
user_data['admin'] = user.admin
output.append(user_data)
return jsonify({'users' : output})
@app.route('/user/<public_id>', methods=['GET'])
@token_required
def get_one_user(current_user, public_id):
# if user is not admin, get_one_user can't be performed
if not current_user.admin:
return jsonify({'message' : 'Cannot perform that function!'})
# select the entry(user) with specific public ID in DB table 'User'
user = User.query.filter_by(public_id=public_id).first()
if not user:
return jsonify({'message' : 'No user found!'})
user_data = {}
user_data['public_id'] = user.public_id
user_data['name'] = user.name
user_data['password'] = user.password
user_data['admin'] = user.admin
return jsonify({'user' : user_data})
@app.route('/user', methods=['POST'])
@token_required
def create_user(current_user):
# if user is not admin, create_user can't be performed
if not current_user.admin:
return jsonify({'message' : 'Cannot perform that function!'})
# get input from user via request
data = request.get_json()
# hash the password
hashed_password = generate_password_hash(data['password'], method='sha256')
# create new user
new_user = User(public_id=str(uuid.uuid4()), name=data['name'], password=hashed_password, admin=False)
# add new user(entry) to DB
db.session.add(new_user)
db.session.commit()
return jsonify({'message' : 'New user created!'})
@app.route('/user/<public_id>', methods=['PUT'])
@token_required
def promote_user(current_user, public_id):
# if user is not admin, promote_user can't be performed
if not current_user.admin:
return jsonify({'message' : 'Cannot perform that function!'})
# select the entry(user) with specific public ID in DB table 'User'
user = User.query.filter_by(public_id=public_id).first()
if not user:
return jsonify({'message' : 'No user found!'})
# set the user to be an admin
user.admin = True
db.session.commit()
return jsonify({'message' : 'The user has been promoted!'})
@app.route('/user/<public_id>', methods=['DELETE'])
@token_required
def delete_user(current_user, public_id):
if not current_user.admin:
return jsonify({'message' : 'Cannot perform that function!'})
# select the entry(user) with specific public ID in DB table 'User'
user = User.query.filter_by(public_id=public_id).first()
if not user:
return jsonify({'message' : 'No user found!'})
# delete entry from DB
db.session.delete(user)
db.session.commit()
return jsonify({'message' : 'The user has been deleted!'})
@app.route('/login')
def login():
auth = request.authorization
if not auth or not auth.username or not auth.password:
return make_response('Could not verify', 401, {'WWW-Authenticate' : 'Basic realm="Login required!"'})
user = User.query.filter_by(name=auth.username).first()
if not user:
return make_response('Could not verify', 401, {'WWW-Authenticate' : 'Basic realm="Login required!"'})
if check_password_hash(user.password, auth.password):
token = jwt.encode({'public_id' : user.public_id, 'exp' : datetime.datetime.utcnow() + datetime.timedelta(minutes=30)}, app.config['SECRET_KEY'])
return jsonify({'token' : token.decode('UTF-8')})
return make_response('Could not verify', 401, {'WWW-Authenticate' : 'Basic realm="Login required!"'})
@app.route('/todo', methods=['GET'])
@token_required
def get_all_todos(current_user):
todos = Todo.query.filter_by(user_id=current_user.id).all()
output = []
for todo in todos:
todo_data = {}
todo_data['id'] = todo.id
todo_data['text'] = todo.text
todo_data['complete'] = todo.complete
output.append(todo_data)
return jsonify({'todos' : output})
@app.route('/todo/<todo_id>', methods=['GET'])
@token_required
def get_one_todo(current_user, todo_id):
todo = Todo.query.filter_by(id=todo_id, user_id=current_user.id).first()
if not todo:
return jsonify({'message' : 'No todo found!'})
todo_data = {}
todo_data['id'] = todo.id
todo_data['text'] = todo.text
todo_data['complete'] = todo.complete
return jsonify(todo_data)
@app.route('/todo', methods=['POST'])
@token_required
def create_todo(current_user):
data = request.get_json()
new_todo = Todo(text=data['text'], complete=False, user_id=current_user.id)
db.session.add(new_todo)
db.session.commit()
return jsonify({'message' : "Todo created!"})
@app.route('/todo/<todo_id>', methods=['PUT'])
@token_required
def complete_todo(current_user, todo_id):
todo = Todo.query.filter_by(id=todo_id, user_id=current_user.id).first()
if not todo:
return jsonify({'message' : 'No todo found!'})
todo.complete = True
db.session.commit()
return jsonify({'message' : 'Todo item has been completed!'})
@app.route('/todo/<todo_id>', methods=['DELETE'])
@token_required
def delete_todo(current_user, todo_id):
todo = Todo.query.filter_by(id=todo_id, user_id=current_user.id).first()
if not todo:
return jsonify({'message' : 'No todo found!'})
db.session.delete(todo)
db.session.commit()
return jsonify({'message' : 'Todo item deleted!'})
if __name__ == '__main__':
app.run(debug=True)