diff --git a/Context/common.py b/Context/common.py index ef893ca..8eec7b1 100644 --- a/Context/common.py +++ b/Context/common.py @@ -6,3 +6,5 @@ class ctx: common_conf = None # token工具 token_util = None + # 运行环境 + env = None diff --git a/Router/UserRegisterRouter.py b/Router/UserRegisterRouter.py index 2dfdb2b..5561728 100644 --- a/Router/UserRegisterRouter.py +++ b/Router/UserRegisterRouter.py @@ -3,9 +3,11 @@ import base64 from fastapi import APIRouter, Depends, HTTPException from sqlalchemy.orm import Session +from Context.common import ctx from Crud.UserCrud import get_user_by_email, create_user, rest_user_password from Crud import AppCrud from Schemas import UserSchemas +from Schemas.ApiCommonSchemas import CommonRes from Utils.AuthUtils import Token, token_data_depend, create_token from Utils.EncyptUtil import get_encrypt_password from Utils.SqlAlchemyUtils import get_db @@ -20,17 +22,23 @@ router = APIRouter( @router.get("/get_image_captcha", summary="获取图片验证码", response_model=UserSchemas.ImageCaptchaRes) def get_image_captcha(): # 是否加上时间对ip的时间验证 - captcha_id, image_bytes = ImageCaptchaVerify.make_captcha_image() + captcha_id, image_bytes, captcha_code = ImageCaptchaVerify.make_captcha_image() img_data = "data:image/png;base64," + base64.b64encode(image_bytes).decode() - - return UserSchemas.ImageCaptchaRes(captcha_id=captcha_id, img_data=img_data) + # 注意,测试时才传入captcha_code + if ctx.env == 'test': + return UserSchemas.ImageCaptchaRes(captcha_id=captcha_id, img_data=img_data, captcha_code=captcha_code) + else: + return UserSchemas.ImageCaptchaRes(captcha_id=captcha_id, img_data=img_data) -@router.post("/get_register_email_verify_code", summary="获取邮箱验证码") +# return UserSchemas.ImageCaptchaRes(captcha_id=captcha_id, img_data=img_data) + + +@router.post("/get_register_email_verify_code", summary="获取邮箱验证码", response_model=CommonRes) def get_register_email_verify_code(body: UserSchemas.EmailSendReqBody): email = body.email EmailVerifyCode.send_register_code(email) - return {"msg": "验证码已发送至邮箱,请查看"} + return {"msg": "验证码已发送至邮箱,请查看", "state": 1} @router.post("/login", summary="登录", response_model=UserSchemas.LoginResBody) @@ -84,7 +92,7 @@ def login(body: UserSchemas.LoginReqBody, db: Session = Depends(get_db)): return UserSchemas.LoginResBody(**user_info, access_token=token, token_type='bearer', app_id=app.id) -@router.post("/register", summary="注册") +@router.post("/register", summary="注册", response_model=CommonRes) def register(body: UserSchemas.RegisterReqBody, db: Session = Depends(get_db)): # 用户是否存在 user_obj = get_user_by_email(db, body.email) @@ -98,7 +106,7 @@ def register(body: UserSchemas.RegisterReqBody, db: Session = Depends(get_db)): return {"state": 1, "msg": "注册成功"} -@router.post("/rest_password", summary="密码重置") +@router.post("/rest_password", summary="密码重置", response_model=CommonRes) def rest_password(body: UserSchemas.RestPasswordReqBody, db: Session = Depends(get_db)): # 用户是否存在 user_obj = get_user_by_email(db, body.email) @@ -112,8 +120,7 @@ def rest_password(body: UserSchemas.RestPasswordReqBody, db: Session = Depends(g return {"state": 1, "msg": "密码修改成功"} -@router.post("/get_rest_password_email_verify_code", summary="获取邮箱验证码") +@router.post("/get_rest_password_email_verify_code", summary="获取邮箱验证码", response_model=CommonRes) def get_rest_password_email_verify_code(body: UserSchemas.EmailSendReqBody): - email = body.email - EmailVerifyCode.send_rest_code(email, EmailVerifyType.reset_password) - return {"msg": "验证码已发送至邮箱,请查看"} + EmailVerifyCode.send_rest_code(body.email) + return {"msg": "验证码已发送至邮箱,请查看", "state": 1} diff --git a/Router/UserRouter.py b/Router/UserRouter.py index ca67f3f..4e732cf 100644 --- a/Router/UserRouter.py +++ b/Router/UserRouter.py @@ -29,7 +29,7 @@ def get_user_info(token_data: TokenData = Depends(token_data_depend), db: Sessio @router.post('/avatar_upload',summary="用户头像上传") -def avatar_upload(file: UploadFile = File(...), token_data: TokenData = Depends(token_data_depend)): +def avatar_upload(file: UploadFile = File(...), token_data: TokenData = Depends(token_data_depend), db: Session = Depends(get_db)): if file.content_type not in ['image/png', 'image/jpeg']: raise Exception('图片格式应为png和jpg') contents = file.file.read(1024 * 201) @@ -43,5 +43,5 @@ def avatar_upload(file: UploadFile = File(...), token_data: TokenData = Depends( with open(save_path / file_md, 'wb') as f: f.write(contents) file_url_path = f"/static_data/user/avatar/{file_md}" - UserCrud.change_user_info(token_data.id, {'avatar': file_url_path}) + UserCrud.change_user_info(db,token_data.id, {'avatar': file_url_path}) return {"msg": "上传成功", "state": 1} diff --git a/Schemas/ApiCommonSchemas.py b/Schemas/ApiCommonSchemas.py new file mode 100644 index 0000000..05caf29 --- /dev/null +++ b/Schemas/ApiCommonSchemas.py @@ -0,0 +1,6 @@ +from pydantic import BaseModel + + +class CommonRes(BaseModel): + msg: str + state: int diff --git a/Schemas/UserSchemas.py b/Schemas/UserSchemas.py index 433709c..2f38416 100644 --- a/Schemas/UserSchemas.py +++ b/Schemas/UserSchemas.py @@ -8,11 +8,12 @@ passwordRegex = constr(regex="^(?![A-Za-z0-9]+$)(?![a-z0-9\\W]+$)(?![A-Za-z\\W]+ class ImageCaptchaRes(BaseModel): captcha_id: str img_data: str + captcha_code:str class LoginReqBody(BaseModel): - email: EMailRegex = "xxxx@fecr.com.cn" - password: passwordRegex = "包含大小写字母和数字,长度8-16位" + email: str + password: str captcha_id: str captcha_code: str app_id: Union[str, None] # @@ -47,6 +48,7 @@ class RegisterReqBody(BaseModel): class RestPasswordReqBody(BaseModel): email: EMailRegex + password: passwordRegex email_verify_code: str diff --git a/Utils/AuthUtils.py b/Utils/AuthUtils.py index 09d90e2..24ce2cf 100644 --- a/Utils/AuthUtils.py +++ b/Utils/AuthUtils.py @@ -1,3 +1,5 @@ +from typing import List + from jose import jwt, JWTError from datetime import datetime, timedelta from fastapi import Header, Request, HTTPException @@ -20,8 +22,8 @@ def create_token(data: dict, secret_key, algorithm, expires_delta: timedelta = t return encoded_jwt -def decode_token(token: str, secret_key: str, algorithm: str = 'HS256'): - payload = jwt.decode(token, secret_key, algorithms=[algorithm]) +def decode_token(token: str, secret_key: str, algorithms: List[str] = ['HS256']): + payload = jwt.decode(token, secret_key, algorithms=algorithms) return payload @@ -40,8 +42,8 @@ class Token: def token_data_depend(Authorization: str = Header(None)): - jwt_token = Authorization try: + _, jwt_token = Authorization.split(" ") payload = Token.decode_token(jwt_token) token_data = TokenData(**payload) return token_data @@ -52,7 +54,12 @@ def token_data_depend(Authorization: str = Header(None)): # 管理员token验证 def admin_auth_token_depend(Authorization: str = Header(None)) -> TokenData: - token_data: TokenData = token_data_depend(Authorization) + try: + _, token = Authorization.split(" ") + token_data: TokenData = token_data_depend(Authorization) + except Exception as e: + print(e) + raise HTTPException(status_code=403, detail="非管理员,无权限的操作") if token_data.role != 'admin': raise HTTPException(status_code=403, detail="非管理员,无权限的操作") return token_data diff --git a/Utils/VerifyCodeUtils.py b/Utils/VerifyCodeUtils.py index 3eab051..5182618 100644 --- a/Utils/VerifyCodeUtils.py +++ b/Utils/VerifyCodeUtils.py @@ -21,7 +21,7 @@ class ImageCaptchaVerify: code = get_random_letter_and_num_code(4) image_bytes = image.generate(code).getvalue() ctx.redis_pool.conn.set(captcha_id, code, expire_time_s) - return captcha_id, image_bytes + return captcha_id, image_bytes,code @classmethod def check_code(cls, captcha_id, code: str) -> bytes: @@ -66,7 +66,8 @@ class EmailVerifyCode: @classmethod def send_rest_code(cls, email): - send_email("", email, "") + code = cls.make_code(email,verify_type=EmailVerifyType.reset_password) + send_email("密码重置验证码", email, code) pass @classmethod diff --git a/main.py b/main.py index c87d053..92a7d74 100644 --- a/main.py +++ b/main.py @@ -37,4 +37,4 @@ app.include_router(UserManageRouter.router) app.include_router(AppManageRouter.router) app.include_router(AuthRuleRouter.router) -uvicorn.run(app=app, port=8001) +# uvicorn.run(app=app, port=8001)