app-MAIL-temp/app/api/base.py

35 lines
864 B
Python
Raw Normal View History

2019-12-04 00:48:30 +01:00
from functools import wraps
import arrow
from flask import Blueprint, request, jsonify, g
from flask_login import current_user
2020-04-25 11:30:09 +02:00
2019-12-04 00:48:30 +01:00
from app.extensions import db
from app.models import ApiKey
api_bp = Blueprint(name="api", import_name=__name__, url_prefix="/api")
2019-12-04 00:48:30 +01:00
def require_api_auth(f):
2019-12-04 00:48:30 +01:00
@wraps(f)
def decorated(*args, **kwargs):
if current_user.is_authenticated:
g.user = current_user
else:
api_code = request.headers.get("Authentication")
api_key = ApiKey.get_by(code=api_code)
2019-12-04 00:48:30 +01:00
if not api_key:
return jsonify(error="Wrong api key"), 401
2019-12-04 00:48:30 +01:00
# Update api key stats
api_key.last_used = arrow.now()
api_key.times += 1
db.session.commit()
2019-12-04 00:48:30 +01:00
g.user = api_key.user
2019-12-04 00:48:30 +01:00
return f(*args, **kwargs)
return decorated