easyctf-2017/server/api/decorators.py

68 lines
2 KiB
Python
Raw Normal View History

2016-01-08 03:25:50 +00:00
from functools import wraps
from flask import abort, request, session, make_response
2015-12-31 02:56:00 +00:00
import json
import traceback
2016-01-08 03:25:50 +00:00
import utils
2015-12-23 01:45:50 +00:00
2015-12-31 02:56:00 +00:00
class WebException(Exception): pass
2016-01-08 03:25:50 +00:00
response_header = { "Content-Type": "application/json; charset=utf-8" }
2015-12-31 02:56:00 +00:00
2015-12-27 00:19:31 +00:00
def api_wrapper(f):
2016-01-08 03:25:50 +00:00
@wraps(f)
def wrapper(*args, **kwds):
if request.method == "POST":
2016-01-12 03:54:26 +00:00
try:
token = str(session.pop("csrf_token"))
provided_token = str(request.form.get("csrf_token"))
if not token or token != provided_token:
raise Exception
except Exception, e:
response = make_response(json.dumps({ "success": 0, "message": "Token has been tampered with." }), 403, response_header)
token = utils.generate_string()
response.set_cookie("csrf_token", token)
session["csrf_token"] = token
return response
2016-01-08 03:25:50 +00:00
web_result = {}
response = 200
try:
web_result = f(*args, **kwds)
except WebException as error:
response = 200
web_result = { "success": 0, "message": str(error) }
except Exception as error:
response = 200
traceback.print_exc()
web_result = { "success": 0, "message": "Something went wrong! Please notify us about this immediately.", "error": [ str(error), traceback.format_exc() ] }
result = (json.dumps(web_result), response, response_header)
2016-01-12 03:54:26 +00:00
response = make_response(result)
2016-01-08 03:25:50 +00:00
# Setting CSRF token
2016-01-17 02:19:02 +00:00
if "csrf_token" not in session:
2016-01-08 03:25:50 +00:00
token = utils.generate_string()
response.set_cookie("csrf_token", token)
session["csrf_token"] = token
2016-01-16 22:36:30 +00:00
2016-01-08 03:25:50 +00:00
return response
return wrapper
def login_required(f):
2016-01-08 03:25:50 +00:00
@wraps(f)
def decorated_function(*args, **kwargs):
if not user.is_logged_in():
return { "success": 0, "message": "Not logged in." }
return f(*args, **kwargs)
return decorated_function
2016-01-16 06:53:35 +00:00
import user # Must go below api_wrapper to prevent import loops
def admins_only(f):
2016-01-08 03:25:50 +00:00
@wraps(f)
def decorated_function(*args, **kwargs):
if not user.is_admin():
return { "success": 0, "message": "Not authorized." }
return f(*args, **kwargs)
return decorated_function