feat: add api auth

This commit is contained in:
BryantHe 2023-08-11 16:36:56 +08:00
parent 99cc82b9e7
commit fb46ba4395
5 changed files with 68 additions and 1 deletions

View File

@ -40,5 +40,5 @@ def create_app():
app = APIFlask(__name__) app = APIFlask(__name__)
load_app_config(app) load_app_config(app)
register_blueprints(app) register_blueprints(app)
# load_rpc_client(app) load_rpc_client(app)
return app return app

View File

@ -1,11 +1,13 @@
from apiflask import APIBlueprint from apiflask import APIBlueprint
from app.api.v1.api import api from app.api.v1.api import api
from app.api.v1.auth import auth
def create_v1(): def create_v1():
bp_v1 = APIBlueprint('v1', __name__) bp_v1 = APIBlueprint('v1', __name__)
bp_v1.register_blueprint(api, url_prefix='/api') bp_v1.register_blueprint(api, url_prefix='/api')
bp_v1.register_blueprint(auth, url_prefix='/auth')
return bp_v1 return bp_v1

22
app/api/v1/auth.py Normal file
View File

@ -0,0 +1,22 @@
from apiflask import APIBlueprint
from app import rpc
from app.api.v1.schema.auth import WechatLoginIn, WechatLoginOut, RefreshTokenIn, RefreshTokenOut
auth = APIBlueprint('auth', __name__)
@auth.post('/wechat_login')
@auth.input(WechatLoginIn)
@auth.output(WechatLoginOut)
def wechat_login(data):
result = rpc.admin.wechat_login(data['code'])
return result
@auth.get('/refresh_token')
@auth.input(RefreshTokenIn, location='query')
@auth.output(RefreshTokenOut)
def refresh_token(data):
result = rpc.admin.refresh_token(data['refresh_token'])
return result

20
app/api/v1/schema/auth.py Normal file
View File

@ -0,0 +1,20 @@
from apiflask import Schema
from apiflask.fields import String
class WechatLoginIn(Schema):
code = String(required=True)
class WechatLoginOut(Schema):
access_token = String()
refresh_token = String()
class RefreshTokenIn(Schema):
refresh_token = String(required=True)
class RefreshTokenOut(Schema):
access_token = String()
refresh_token = String()

View File

@ -1,6 +1,11 @@
import os import os
from itertools import groupby from itertools import groupby
from operator import itemgetter from operator import itemgetter
from functools import wraps
from flask import request, session
from app import rpc
def split_group(dict_list, key): def split_group(dict_list, key):
@ -13,3 +18,21 @@ def split_group(dict_list, key):
basedir = os.getcwd() basedir = os.getcwd()
def login_required(f):
"""
登陆保护验证用户是否登陆
"""
@wraps(f)
def wrapper(*args, **kwargs):
token = request.headers.get("Authorization", default=None)
if not token:
return '请登陆'
user_id = rpc.admin.identify(token)
if not user_id:
return '请登陆'
session['user_id'] = user_id
return f(*args, **kwargs)
return wrapper