Guest User

Untitled

a guest
Dec 30th, 2018
178
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 6.45 KB | None | 0 0
  1. import datetime
  2. from flask import Flask, jsonify, abort, request
  3.  
  4. from flask_jwt_extended import (
  5. JWTManager, jwt_required, create_access_token,
  6. get_jwt_identity, get_current_user, verify_jwt_in_request,
  7. jwt_optional
  8. )
  9. from passlib.hash import pbkdf2_sha256
  10.  
  11. from functools import wraps
  12.  
  13. import uuid
  14.  
  15. from flask_pymongo import PyMongo
  16.  
  17. from bson.objectid import ObjectId
  18.  
  19.  
  20. app = Flask(__name__)
  21. app.config["MONGO_URI"] = "mongodb://localhost:27017/todo"
  22. mongo = PyMongo(app)
  23.  
  24. app.config['JWT_SECRET_KEY'] = 'xxxxxxxxxxxxxx' # Change this!
  25. jwt = JWTManager(app)
  26.  
  27.  
  28. tasks = []
  29.  
  30. users = []
  31.  
  32.  
  33. @app.route('/register', methods=['POST'])
  34. def register():
  35. if not request.json:
  36. abort(500)
  37.  
  38. username = request.json.get("username", None)
  39. password = request.json.get("password", None)
  40. name = request.json.get("name", None)
  41.  
  42. if username is None or password is None or name is None:
  43. abort(500)
  44.  
  45. global users
  46.  
  47. users = [user for user in users if user["username"] == username]
  48.  
  49. if len(users) > 0:
  50. return jsonify("username already exists!"), 500
  51.  
  52. id = uuid.uuid4().hex
  53. hash = pbkdf2_sha256.hash(password)
  54.  
  55. users.append({
  56. "id": id,
  57. "username": username,
  58. "password": hash,
  59. "name": name
  60. })
  61.  
  62. return jsonify(id)
  63.  
  64.  
  65. # Create a function that will be called whenever create_access_token
  66. # is used. It will take whatever object is passed into the
  67. # create_access_token method, and lets us define what custom claims
  68. # should be added to the access token.
  69.  
  70. @jwt.user_identity_loader
  71. def user_identity_lookup(user):
  72. return user["id"]
  73.  
  74.  
  75. @app.route('/login', methods=['POST'])
  76. def login():
  77. if not request.is_json:
  78. return jsonify({"msg": "Missing JSON in request"}), 500
  79.  
  80. username = request.json.get('username', None)
  81. password = request.json.get('password', None)
  82. if not username:
  83. return jsonify({"msg": "Missing username parameter"}), 500
  84. if not password:
  85. return jsonify({"msg": "Missing password parameter"}), 500
  86.  
  87. global users
  88. users = [user for user in users if user["username"] == username]
  89.  
  90. if len(users) == 0:
  91. return jsonify("username failed!"), 400
  92.  
  93. user = users[0]
  94.  
  95. if not pbkdf2_sha256.verify(password, user["password"]):
  96. return jsonify("password failed!"), 400
  97.  
  98. access_token = create_access_token(identity=user)
  99. return jsonify(access_token=access_token), 200
  100.  
  101.  
  102. @jwt.user_loader_callback_loader
  103. def user_loader_callback(identity):
  104. global users
  105. users = [user for user in users if user["id"] == identity]
  106. if len(users) > 0:
  107. if users[0]["username"] == "manish":
  108. users[0]["role"] = "admin"
  109. else:
  110. users[0]["role"] = "normal"
  111. return users[0]
  112. return {}
  113.  
  114. # Protect a view with jwt_required, which requires a valid access token
  115. # in the request to access.
  116.  
  117.  
  118. @app.route('/profile', methods=['GET'])
  119. @jwt_required
  120. def profile():
  121. # Access the identity of the current user with get_current_user
  122. current_user = get_current_user()
  123. return jsonify(logged_in_as=current_user), 200
  124.  
  125.  
  126. def admin_required(fn):
  127. @wraps(fn)
  128. def wrapper(*args, **kwargs):
  129. verify_jwt_in_request()
  130. user = get_current_user()
  131. if user["username"] == "manish":
  132. return fn(*args, **kwargs)
  133.  
  134. return jsonify(msg='Admins only!'), 403
  135. return wrapper
  136.  
  137.  
  138. @app.route("/admin_only")
  139. @jwt_required
  140. @admin_required
  141. def admin_only():
  142. return ""
  143.  
  144.  
  145. @app.route('/todo', methods=["GET"])
  146. @app.route('/todo/<string:direction>', methods=["GET"])
  147. @jwt_optional
  148. def todo(direction=None):
  149. # direction is optional
  150. current_user = get_current_user()
  151. if direction == "ASC":
  152. direction = 1
  153. else:
  154. direction = -1
  155.  
  156. if direction is not None:
  157. if current_user is not None and "id" in current_user:
  158. if current_user["role"] == "normal":
  159. ret = mongo.db.tasks.find(
  160. {"user": current_user["id"]}).sort("due", direction)
  161. else:
  162. ret = mongo.db.tasks.find({"user": ""}).sort(
  163. "due", direction).limit(5)
  164. else:
  165. if current_user is not None and "id" in current_user:
  166. ret = mongo.db.tasks.find(
  167. {"user": current_user["id"]})
  168. else:
  169. ret = mongo.db.tasks.find({"user": ""}).limit(5)
  170.  
  171. tasks = []
  172. for doc in ret:
  173. doc["_id"] = str(doc["_id"])
  174. tasks.append(doc)
  175. return jsonify(tasks)
  176.  
  177.  
  178. @app.route('/todo', methods=["POST"])
  179. @jwt_optional
  180. def add_todo():
  181. if not request.json:
  182. abort(500)
  183.  
  184. title = request.json.get("title", None)
  185. desc = request.json.get("description", "")
  186.  
  187. due = request.json.get("due", None)
  188.  
  189. if due is not None:
  190. due = datetime.datetime.strptime(due, "%d-%m-%Y")
  191. else:
  192. due = datetime.datetime.now()
  193.  
  194. current_user = get_current_user()
  195.  
  196. user_id = ""
  197. if current_user is not None and "id" in current_user:
  198. user_id = current_user["id"]
  199.  
  200. # use insert_one to do insert operations
  201. ret = mongo.db.tasks.insert_one({
  202. "title": title,
  203. "description": desc,
  204. "done": False,
  205. "due": due,
  206. "user": user_id
  207. }).inserted_id
  208.  
  209. # fetch the inserted id and convert it to string before sending it in response
  210. return jsonify(str(ret))
  211.  
  212.  
  213. @app.route("/todo/<string:id>", methods=['PUT'])
  214. @jwt_optional
  215. def update_todo(id):
  216.  
  217. if not request.json:
  218. abort(500)
  219.  
  220. title = request.json.get("title", None)
  221. desc = request.json.get("description", "")
  222.  
  223. if title is None:
  224. return jsonify(message="Invalid Request"), 500
  225.  
  226. update_json = {}
  227. if title is not None:
  228. update_json["title"] = title
  229.  
  230. if desc is not None:
  231. update_json["description"] = desc
  232.  
  233. # match with Object ID
  234. ret = mongo.db.tasks.update({
  235. "_id": ObjectId(id)
  236. }, {
  237. "$set": update_json
  238. }, upsert=False)
  239.  
  240. return jsonify(ret)
  241.  
  242.  
  243. @app.route("/todo/<string:id>", methods=["DELETE"])
  244. def delete_todo(id):
  245.  
  246. ret = mongo.db.tasks.remove({
  247. "_id" : ObjectId(id)
  248. })
  249.  
  250. return jsonify(ret)
  251.  
  252.  
  253. def mark(task, status, task_id):
  254. if task_id == task["id"]:
  255. task["done"] = status
  256.  
  257. return task
  258.  
  259.  
  260. @app.route("/todo/mark/<int:task_id>/<int:status>", methods=["PUT"])
  261. @jwt_required
  262. @admin_required
  263. def mark_task(task_id, status):
  264.  
  265. global tasks
  266. if status == 1:
  267. status = True
  268. else:
  269. status = False
  270.  
  271. tasks = [mark(task, status, task_id) for task in tasks]
  272.  
  273. return jsonify(tasks)
Add Comment
Please, Sign In to add comment