2023-05-15 08:51:32 +08:00
|
|
|
# -*- coding:utf-8 -*-
|
|
|
|
from functools import wraps
|
|
|
|
|
2023-07-11 15:21:20 +08:00
|
|
|
from flask import request
|
2023-05-15 08:51:32 +08:00
|
|
|
from flask_restful import Resource
|
|
|
|
from werkzeug.exceptions import NotFound, Unauthorized
|
|
|
|
|
|
|
|
from extensions.ext_database import db
|
2023-08-13 17:32:23 +08:00
|
|
|
from models.model import App, EndUser, Site
|
2023-07-11 15:21:20 +08:00
|
|
|
from libs.passport import PassportService
|
2023-05-15 08:51:32 +08:00
|
|
|
|
2023-07-11 15:21:20 +08:00
|
|
|
def validate_jwt_token(view=None):
|
2023-05-15 08:51:32 +08:00
|
|
|
def decorator(view):
|
|
|
|
@wraps(view)
|
|
|
|
def decorated(*args, **kwargs):
|
2023-07-11 15:21:20 +08:00
|
|
|
app_model, end_user = decode_jwt_token()
|
2023-05-15 08:51:32 +08:00
|
|
|
|
|
|
|
return view(app_model, end_user, *args, **kwargs)
|
|
|
|
return decorated
|
|
|
|
if view:
|
|
|
|
return decorator(view)
|
|
|
|
return decorator
|
|
|
|
|
2023-07-11 15:21:20 +08:00
|
|
|
def decode_jwt_token():
|
2023-05-15 08:51:32 +08:00
|
|
|
auth_header = request.headers.get('Authorization')
|
|
|
|
if auth_header is None:
|
2023-05-25 15:54:45 +08:00
|
|
|
raise Unauthorized('Authorization header is missing.')
|
|
|
|
|
|
|
|
if ' ' not in auth_header:
|
|
|
|
raise Unauthorized('Invalid Authorization header format. Expected \'Bearer <api-key>\' format.')
|
2023-07-11 15:21:20 +08:00
|
|
|
|
|
|
|
auth_scheme, tk = auth_header.split(None, 1)
|
2023-05-15 08:51:32 +08:00
|
|
|
auth_scheme = auth_scheme.lower()
|
|
|
|
|
|
|
|
if auth_scheme != 'bearer':
|
2023-05-25 15:54:45 +08:00
|
|
|
raise Unauthorized('Invalid Authorization header format. Expected \'Bearer <api-key>\' format.')
|
2023-07-11 15:21:20 +08:00
|
|
|
decoded = PassportService().verify(tk)
|
2023-08-13 17:32:23 +08:00
|
|
|
app_code = decoded.get('app_code')
|
2023-07-11 15:21:20 +08:00
|
|
|
app_model = db.session.query(App).filter(App.id == decoded['app_id']).first()
|
2023-08-13 17:32:23 +08:00
|
|
|
site = db.session.query(Site).filter(Site.code == app_code).first()
|
2023-07-11 15:21:20 +08:00
|
|
|
if not app_model:
|
|
|
|
raise NotFound()
|
2023-08-13 17:32:23 +08:00
|
|
|
if not app_code and not site:
|
|
|
|
raise Unauthorized('Site URL is no longer valid.')
|
2023-07-26 11:11:09 +08:00
|
|
|
if app_model.enable_site is False:
|
|
|
|
raise Unauthorized('Site is disabled.')
|
2023-07-11 15:21:20 +08:00
|
|
|
end_user = db.session.query(EndUser).filter(EndUser.id == decoded['end_user_id']).first()
|
|
|
|
if not end_user:
|
2023-05-15 08:51:32 +08:00
|
|
|
raise NotFound()
|
|
|
|
|
2023-07-11 15:21:20 +08:00
|
|
|
return app_model, end_user
|
2023-05-15 08:51:32 +08:00
|
|
|
|
|
|
|
class WebApiResource(Resource):
|
2023-07-11 15:21:20 +08:00
|
|
|
method_decorators = [validate_jwt_token]
|