diff --git a/backend/app.py b/backend/app.py index 60bf373..385b9c4 100644 --- a/backend/app.py +++ b/backend/app.py @@ -2,10 +2,12 @@ import os import flask import flask_cors +import flask_login import flask_restful import flask_restful.fields import flask_restful.reqparse import flask_sqlalchemy +import itsdangerous import sqlalchemy @@ -20,9 +22,26 @@ db.create_all() api = flask_restful.Api(app) +login_manager = flask_login.LoginManager() +login_manager.init_app(app) + flask_cors.CORS(app) +@login_manager.request_loader +def load_user(request): + key = request.headers.get('X-Quotes-API-Key') + if not key: + return None + s = itsdangerous.TimedJSONWebSignatureSerializer(app.config['SECRET_KEY']) + try: + user = flask_login.UserMixin() + user.id = s.loads(key) + return user + except (itsdangerous.SignatureExpired, itsdangerous.BadSignature): + return None + + class Quote(db.Model): __tablename__ = 'quotes' @@ -71,6 +90,7 @@ class QuoteResource(flask_restful.Resource): flask_restful.abort(404, message='Quote {0} does not exist'.format(id)) return quote, 200 + @flask_login.login_required @flask_restful.marshal_with(quote_fields) def put(self, id): args = quote_parser.parse_args() @@ -88,6 +108,7 @@ class QuoteResource(flask_restful.Resource): db.session.commit() return quote, 200 + @flask_login.login_required def delete(self, id): q = db.session.query(Quote).filter(Quote.id == id) quote = q.first() @@ -122,6 +143,7 @@ class QuotesResource(flask_restful.Resource): quotes = q.all() return quotes, 200, {'X-Total-Count': count} + @flask_login.login_required @flask_restful.marshal_with(quote_fields) def post(self): args = quote_parser.parse_args()