Secure POST, PUT and DELETE API methods

master
Nikola Forró 7 years ago
parent 6d3a47dbae
commit 42cbc714f0

@ -2,10 +2,12 @@ import os
import flask import flask
import flask_cors import flask_cors
import flask_login
import flask_restful import flask_restful
import flask_restful.fields import flask_restful.fields
import flask_restful.reqparse import flask_restful.reqparse
import flask_sqlalchemy import flask_sqlalchemy
import itsdangerous
import sqlalchemy import sqlalchemy
@ -20,9 +22,26 @@ db.create_all()
api = flask_restful.Api(app) api = flask_restful.Api(app)
login_manager = flask_login.LoginManager()
login_manager.init_app(app)
flask_cors.CORS(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): class Quote(db.Model):
__tablename__ = 'quotes' __tablename__ = 'quotes'
@ -71,6 +90,7 @@ class QuoteResource(flask_restful.Resource):
flask_restful.abort(404, message='Quote {0} does not exist'.format(id)) flask_restful.abort(404, message='Quote {0} does not exist'.format(id))
return quote, 200 return quote, 200
@flask_login.login_required
@flask_restful.marshal_with(quote_fields) @flask_restful.marshal_with(quote_fields)
def put(self, id): def put(self, id):
args = quote_parser.parse_args() args = quote_parser.parse_args()
@ -88,6 +108,7 @@ class QuoteResource(flask_restful.Resource):
db.session.commit() db.session.commit()
return quote, 200 return quote, 200
@flask_login.login_required
def delete(self, id): def delete(self, id):
q = db.session.query(Quote).filter(Quote.id == id) q = db.session.query(Quote).filter(Quote.id == id)
quote = q.first() quote = q.first()
@ -122,6 +143,7 @@ class QuotesResource(flask_restful.Resource):
quotes = q.all() quotes = q.all()
return quotes, 200, {'X-Total-Count': count} return quotes, 200, {'X-Total-Count': count}
@flask_login.login_required
@flask_restful.marshal_with(quote_fields) @flask_restful.marshal_with(quote_fields)
def post(self): def post(self):
args = quote_parser.parse_args() args = quote_parser.parse_args()

Loading…
Cancel
Save