Skip to content

Commit dff6260

Browse files
authored
Fix the swagger form login structure abnormality (#46)
1 parent 4aace9f commit dff6260

File tree

7 files changed

+37
-38
lines changed

7 files changed

+37
-38
lines changed

backend/app/api/jwt.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,7 @@
1818

1919
pwd_context = CryptContext(schemes=['bcrypt'], deprecated='auto')
2020

21-
oauth2_schema = OAuth2PasswordBearer(tokenUrl=settings.TOKEN_URL)
21+
oauth2_schema = OAuth2PasswordBearer(tokenUrl=settings.TOKEN_URL_SWAGGER)
2222

2323

2424
def get_hash_password(password: str) -> str:

backend/app/api/service/user_service.py

Lines changed: 19 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -9,13 +9,13 @@
99
from backend.app.crud.crud_user import UserDao
1010
from backend.app.database.db_mysql import async_db_session
1111
from backend.app.models import User
12-
from backend.app.schemas.user import CreateUser, ResetPassword, UpdateUser, Avatar
12+
from backend.app.schemas.user import CreateUser, ResetPassword, UpdateUser, Avatar, Auth
1313
from backend.app.utils import re_verify
1414

1515

1616
class UserService:
1717
@staticmethod
18-
async def login(form_data: OAuth2PasswordRequestForm):
18+
async def swagger_login(form_data: OAuth2PasswordRequestForm):
1919
async with async_db_session() as db:
2020
current_user = await UserDao.get_user_by_username(db, form_data.username)
2121
if not current_user:
@@ -32,23 +32,23 @@ async def login(form_data: OAuth2PasswordRequestForm):
3232
access_token = jwt.create_access_token(user.id)
3333
return access_token, user
3434

35-
# @staticmethod
36-
# async def login(obj: Auth):
37-
# async with async_db_session() as db:
38-
# current_user = await UserDao.get_user_by_username(db, obj.username)
39-
# if not current_user:
40-
# raise errors.NotFoundError(msg='用户名不存在')
41-
# elif not jwt.password_verify(obj.password, current_user.password):
42-
# raise errors.AuthorizationError(msg='密码错误')
43-
# elif not current_user.is_active:
44-
# raise errors.AuthorizationError(msg='该用户已被锁定,无法登录')
45-
# # 更新登陆时间
46-
# await UserDao.update_user_login_time(db, obj.username)
47-
# # 获取最新用户信息
48-
# user = await UserDao.get_user_by_id(db, current_user.id)
49-
# # 创建token
50-
# access_token = jwt.create_access_token(user.id)
51-
# return access_token, user
35+
@staticmethod
36+
async def login(obj: Auth):
37+
async with async_db_session() as db:
38+
current_user = await UserDao.get_user_by_username(db, obj.username)
39+
if not current_user:
40+
raise errors.NotFoundError(msg='用户名不存在')
41+
elif not jwt.password_verify(obj.password, current_user.password):
42+
raise errors.AuthorizationError(msg='密码错误')
43+
elif not current_user.is_active:
44+
raise errors.AuthorizationError(msg='该用户已被锁定,无法登录')
45+
# 更新登陆时间
46+
await UserDao.update_user_login_time(db, obj.username)
47+
# 获取最新用户信息
48+
user = await UserDao.get_user_by_id(db, current_user.id)
49+
# 创建token
50+
access_token = jwt.create_access_token(user.id)
51+
return access_token, user
5252

5353
@staticmethod
5454
async def register(obj: CreateUser):

backend/app/api/v1/auth/user.py

Lines changed: 10 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -8,23 +8,22 @@
88
from backend.app.common.pagination import Page
99
from backend.app.common.response.response_schema import response_base
1010
from backend.app.schemas.token import Token
11-
from backend.app.schemas.user import CreateUser, GetUserInfo, ResetPassword, UpdateUser, Avatar
11+
from backend.app.schemas.user import CreateUser, GetUserInfo, ResetPassword, UpdateUser, Avatar, Auth
1212

1313
router = APIRouter()
1414

1515

16-
@router.post('/login', summary='表单登录', description='form 格式登录,支持直接在 api 文档调试接口')
17-
async def user_login(form_data: OAuth2PasswordRequestForm = Depends()):
18-
token, user = await UserService.login(form_data)
19-
data = Token(access_token=token, user=user)
20-
return response_base.response_200(data=data)
16+
@router.post('/swagger_login', summary='swagger 表单登录', description='form 格式登录,仅用于 swagger 文档调试接口')
17+
async def swagger_user_login(form_data: OAuth2PasswordRequestForm = Depends()) -> Token:
18+
token, user = await UserService.swagger_login(form_data)
19+
return Token(access_token=token, user=user)
2120

2221

23-
# @router.post('/login', summary='用户登录', description='json 格式登录, 仅支持在第三方api工具调试接口, 例如: postman')
24-
# async def user_login(obj: Auth):
25-
# token, user = await UserService.login(obj)
26-
# data = Token(access_token=token, user=user)
27-
# return response_base.response_200(data=data)
22+
@router.post('/login', summary='用户登录', description='json 格式登录, 仅支持在第三方api工具调试接口, 例如: postman')
23+
async def user_login(obj: Auth):
24+
token, user = await UserService.login(obj)
25+
data = Token(access_token=token, user=user)
26+
return response_base.response_200(data=data)
2827

2928

3029
@router.post('/register', summary='用户注册')

backend/app/api/v1/sys_config.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -42,7 +42,7 @@ async def get_sys_config() -> ResponseModel:
4242
'aps_misfire_grace_time': settings.APS_MISFIRE_GRACE_TIME,
4343
'token_algorithm': settings.TOKEN_ALGORITHM,
4444
'token_expire_minutes': settings.TOKEN_EXPIRE_MINUTES,
45-
'token_url': settings.TOKEN_URL,
45+
'token_url': settings.TOKEN_URL_SWAGGER,
4646
'log_file_name': settings.LOG_FILE_NAME,
4747
'middleware_cors': settings.MIDDLEWARE_CORS,
4848
'middleware_gzip': settings.MIDDLEWARE_GZIP,

backend/app/core/conf.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -71,7 +71,7 @@ def validator_api_url(cls, values):
7171
# Token
7272
TOKEN_ALGORITHM: str = 'HS256' # 算法
7373
TOKEN_EXPIRE_MINUTES: int = 60 * 24 * 1 # token 时效 60 * 24 * 1 = 1 天
74-
TOKEN_URL: str = '/v1/auth/users/login'
74+
TOKEN_URL_SWAGGER: str = '/v1/auth/users/swagger_login'
7575

7676
# Log
7777
LOG_FILE_NAME: str = 'fba.log'

backend/app/test/conftest.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -19,9 +19,9 @@ def anyio_backend():
1919
@pytest.fixture(scope='package', autouse=True)
2020
async def function_fixture(anyio_backend):
2121
auth_data = {
22-
'url': f'http://{settings.UVICORN_HOST}:{settings.UVICORN_PORT}{settings.TOKEN_URL}',
23-
'headers': {'accept': 'application/json', 'Content-Type': 'application/x-www-form-urlencoded'},
24-
'data': {'username': 'test', 'password': 'test'},
22+
'url': f'http://{settings.UVICORN_HOST}:{settings.UVICORN_PORT}/v1/auth/users/login',
23+
'headers': {'accept': 'application/json', 'Content-Type': 'application/json'},
24+
'json': {'username': 'test', 'password': 'test'},
2525
}
2626
async with AsyncClient() as client:
2727
response = await client.post(**auth_data)

backend/app/test/test_auth.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -25,10 +25,10 @@ async def get_token(self):
2525

2626
async def test_login(self):
2727
async with AsyncClient(
28-
app=app, headers={'accept': 'application/json', 'Content-Type': 'application/x-www-form-urlencoded'}
28+
app=app, headers={'accept': 'application/json', 'Content-Type': 'application/json'}
2929
) as client:
3030
response = await client.post(
31-
url=f'{self.users_api_base_url}/login', data={'username': '1', 'password': '1'}
31+
url=f'{self.users_api_base_url}/login', json={'username': 'test', 'password': 'test'}
3232
)
3333
assert response.status_code == 200
3434
assert response.json()['data']['token_type'] == 'Bearer'

0 commit comments

Comments
 (0)