add: backend api auth by apikey/apikey gen/apikey revoke
This commit is contained in:
36
api/apikey/__init__.py
Normal file
36
api/apikey/__init__.py
Normal file
@@ -0,0 +1,36 @@
|
||||
from flask import Blueprint, request, jsonify
|
||||
from api import get_api_key, generate_api_key
|
||||
from db import get_db
|
||||
from api import require_auth
|
||||
from db.models.APIKey import APIKey
|
||||
|
||||
api_key_bp = Blueprint('apikey', __name__, url_prefix='/api/apikey')
|
||||
|
||||
@api_key_bp.route('/', methods=['POST'])
|
||||
@require_auth(roles=['admin'])
|
||||
def create_key():
|
||||
data = request.get_json()
|
||||
|
||||
if not data or 'name' not in data:
|
||||
return jsonify({"error": "Name is required"}), 400
|
||||
roles = data.get('roles', [])
|
||||
try:
|
||||
with get_db() as session:
|
||||
apikey = APIKey(key=generate_api_key(),name=data['name'], roles=roles)
|
||||
session.add(apikey);
|
||||
session.commit
|
||||
return jsonify(apikey.to_dict()), 201
|
||||
except Exception as e:
|
||||
return jsonify({"error": str(e)}), 500
|
||||
|
||||
@api_key_bp.route('/<key>', methods=['DELETE'])
|
||||
@require_auth(roles=['admin'])
|
||||
def revoke_key(key):
|
||||
|
||||
api_key = get_api_key(key)
|
||||
with get_db() as session:
|
||||
if not api_key:
|
||||
return jsonify({"error": "API key not found"}), 404
|
||||
api_key.is_active = False
|
||||
session.commit()
|
||||
return jsonify({"message": "API key revoked successfully"}), 200
|
||||
Reference in New Issue
Block a user