2019-12-04 00:48:30 +01:00
|
|
|
from functools import wraps
|
|
|
|
|
|
|
|
import arrow
|
|
|
|
from flask import Blueprint, request, jsonify, g
|
2020-04-24 14:06:42 +02:00
|
|
|
from flask_login import current_user
|
2020-04-25 11:30:09 +02:00
|
|
|
|
2021-10-12 14:36:47 +02:00
|
|
|
from app.db import Session
|
2019-12-04 00:48:30 +01:00
|
|
|
from app.models import ApiKey
|
2019-11-28 23:05:32 +01:00
|
|
|
|
|
|
|
api_bp = Blueprint(name="api", import_name=__name__, url_prefix="/api")
|
2019-12-04 00:48:30 +01:00
|
|
|
|
|
|
|
|
2020-04-24 14:08:00 +02:00
|
|
|
def require_api_auth(f):
|
2019-12-04 00:48:30 +01:00
|
|
|
@wraps(f)
|
|
|
|
def decorated(*args, **kwargs):
|
2020-08-01 10:14:59 +02:00
|
|
|
api_code = request.headers.get("Authentication")
|
|
|
|
api_key = ApiKey.get_by(code=api_code)
|
|
|
|
|
|
|
|
if not api_key:
|
|
|
|
# if user is authenticated, the request is authorized
|
|
|
|
if current_user.is_authenticated:
|
|
|
|
g.user = current_user
|
|
|
|
else:
|
2020-04-24 14:06:42 +02:00
|
|
|
return jsonify(error="Wrong api key"), 401
|
2020-08-01 10:14:59 +02:00
|
|
|
else:
|
2020-04-24 14:06:42 +02:00
|
|
|
# Update api key stats
|
|
|
|
api_key.last_used = arrow.now()
|
|
|
|
api_key.times += 1
|
2021-10-12 14:36:47 +02:00
|
|
|
Session.commit()
|
2019-12-04 00:48:30 +01:00
|
|
|
|
2020-04-24 14:06:42 +02:00
|
|
|
g.user = api_key.user
|
2019-12-04 00:48:30 +01:00
|
|
|
|
2022-04-27 16:24:38 +02:00
|
|
|
if g.user.disabled:
|
|
|
|
return jsonify(error="Disabled account"), 403
|
|
|
|
|
2019-12-04 00:48:30 +01:00
|
|
|
return f(*args, **kwargs)
|
|
|
|
|
|
|
|
return decorated
|