Esempio n. 1
0
def download_file():
    file_name = request.args.get('file_name')
    if not file_name:
        return comm_ret(code=resp_code.PARAMETER_ERROR, msg="请求参数异常")

    # 判断文件是否存在
    if os.path.isfile(os.path.join(DOWNLOAD_FILE_PATH, file_name)):
        return send_from_directory(DOWNLOAD_FILE_PATH,
                                   file_name,
                                   as_attachment=True)
    else:
        return comm_ret(code=resp_code.FILE_NOT_FOUND, msg='no such file!')
Esempio n. 2
0
async def handle_http_exception(request: Request, exc: StarletteHTTPException):
    logger.error(exc)
    # 用户认证
    # 此处添加异常校验的原因是 project/dependencies/auth_depend.py 中自定义的
    # check_jwt 函数只能通过 raise 异常的方式返回结果
    if exc.status_code in [
            resp_code.JWT_PARSE_ERROR, resp_code.USER_NO_AUTHORITY,
            resp_code.USER_NO_LOGIN
    ]:
        return comm_ret(code=exc.status_code, msg=exc.detail)

    return comm_ret(code=resp_code.EXCEPTION_ERROR,
                    isSuccess=False,
                    msg="HTTP Exception")
Esempio n. 3
0
def refresh_token(jwt: constr(strip_whitespace=True) = Depends(_oauth2_scheme),
                  refresh_jwt: constr(strip_whitespace=True,
                                      min_length=1) = Query(
                                          ..., title="refresh_jwt")):
    decode_status, data = JWTAuth().decode_jwt_check_refresh_jwt(
        jwt, refresh_jwt)
    if decode_status is False:
        return comm_ret(code=resp_code.USER_NO_LOGIN, msg="刷新 jwt 失败,重新登录")

    status, new_jwt, new_refresh_jwt = JWTAuth().create_jwt_and_refresh_jwt(
        data)
    if status is False:
        return comm_ret(code=resp_code.JWT_CREATE_ERROR, msg="JWT 信息生成异常")

    return comm_ret(resp={'jwt': new_jwt, 'refresh_jwt': new_refresh_jwt})
Esempio n. 4
0
def user_login(login_info: OAuth2PasswordRequestForm = Depends()):
    """用户登录  
    code 返回 1200 重新登录;  
    code 返回 200 时, resp 中返回 jwt 及 refresh_jwt 信息;  
    jwt 用于验证用户登录;  
    当 访问系统所有需要认证的接口并返回 1102 时, 使用 refresh_jwt 刷新 jwt 及 refresh_jwt 信息;
    当返回 1101 时, jwt 生成异常, 再次发起请求 (基本不需要)

    即 code == 1102 , 需刷新 jwt;  
    code == 1200 , 需重新登录后跳转;  
    code == 1101 , 再次请求; (基本不需要)  
    """
    user_info = JWTBodyInfo(username="******", scopes=['info1']).dict()
    status, jwt, refresh_jwt = JWTAuth().create_jwt_and_refresh_jwt(user_info)
    if status is False:
        return comm_ret(code=resp_code.JWT_CREATE_ERROR, msg="JWT 信息生成异常")

    return JSONResponse(content=jsonable_encoder({
        "code": resp_code.SUCCESS,
        "isSuccess": True,
        "msg": "请求成功",
        "resp": {
            'jwt': jwt,
            'refresh_jwt': refresh_jwt
        },
        'access_token': jwt
    }))
Esempio n. 5
0
def opt_redis():
    red = OperateRedis()
    print(id(red))
    redis_cli = red.conn_redis()
    # print(redis_cli.hget("test", "test"))
    print(id(redis_cli))
    return comm_ret()
Esempio n. 6
0
def app_before_request():
    # 按要求拦截请求
    req_path = request.path
    if 'user/refresh_login_status' in req_path:
        jwt_str = request.headers.get('Authorization')
        if not jwt_str:
            return comm_ret(code=resp_code.USER_NO_LOGIN, msg="请登录")
    elif (  # 使用 or 判断是否需要拦截
        ('/user/' in req_path and 'login' not in req_path)
        # or ('file' in req_path)
    ):
        # 拦截器进行用户认证,认证完成后将相关数据放到 flask 当前应用环境的通用变量 g 中,
        # 后续模块可以通过 g 对象来获取设置在其中的数据,
        # 当数据不存在时出现 '_AppCtxGlobals' object has no attribute 'xxx' 异常
        jwt_str = request.headers.get('Authorization')
        decode_status, user_info = JWTAuth().decode_jwt(jwt_str)
        g.user_info = {}
        if decode_status:
            g.user_info = user_info
            # print(g.user_info)
        else:
            # 跳转到登录页面
            return comm_ret(code=resp_code.JWT_PARSE_ERROR, msg="请刷新Token信息")
Esempio n. 7
0
async def handle_request_validation_error(request: Request,
                                          exc: RequestValidationError):
    logger.error(exc)
    # 自定义异常提示
    msg = set()
    for err in exc.errors():
        if err['type'] == "value_error.paramsvalue":
            msg.add(err['msg'])
    resp = {}
    if not isFormalSystem:
        resp = exc.errors()

    return comm_ret(code=resp_code.PARAMETER_ERROR,
                    msg="\n".join(msg) or "请求参数异常",
                    resp=resp)
Esempio n. 8
0
def get_user_info(jwt_info: JWTBodyInfo = Depends(check_jwt)):
    print(jwt_info)
    return comm_ret(resp=jwt_info.dict())
Esempio n. 9
0
async def handle_all_exception(request: Request, exc: Exception):
    logger.error(exc)
    return comm_ret(code=resp_code.EXCEPTION_ERROR,
                    isSuccess=False,
                    msg="System Exception")
Esempio n. 10
0
def dep_security_2(jwtbi: JWTBodyInfo = Security(check_jwt, scopes=['info2'])):
    return comm_ret(resp=jwtbi.dict())
Esempio n. 11
0
def opt_redis_sentinel():
    print(id(redis_m), id(redis_s))
    t_now = str(int(time.time() * 1000))
    print(redis_m.hset("test", t_now, t_now))
    print(redis_s.hget("test", t_now))
    return comm_ret(resp=t_now)