Skip to content

Commit

Permalink
change:
Browse files Browse the repository at this point in the history
- add random pwd_key.
- backend auth change from Auth token to cookies
  • Loading branch information
EstrellaXD committed Sep 6, 2023
1 parent fdd6769 commit d6b36e5
Show file tree
Hide file tree
Showing 11 changed files with 110 additions and 262 deletions.
2 changes: 0 additions & 2 deletions backend/src/module/api/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@
from .auth import router as auth_router
from .bangumi import router as bangumi_router
from .config import router as config_router
from .download import router as download_router
from .log import router as log_router
from .program import router as program_router
from .rss import router as rss_router
Expand All @@ -16,7 +15,6 @@
v1.include_router(auth_router)
v1.include_router(log_router)
v1.include_router(program_router)
v1.include_router(download_router)
v1.include_router(bangumi_router)
v1.include_router(config_router)
v1.include_router(rss_router)
Expand Down
79 changes: 28 additions & 51 deletions backend/src/module/api/auth.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,85 +2,62 @@

from fastapi import APIRouter, Depends, HTTPException, status
from fastapi.security import OAuth2PasswordRequestForm
from fastapi.responses import JSONResponse
from fastapi.responses import JSONResponse, Response

from module.models.user import User, UserUpdate
from module.models import APIResponse
from module.security.api import (
auth_user,
get_current_user,
update_user_info,
active_user
)
from module.security.jwt import create_access_token

router = APIRouter(prefix="/auth", tags=["auth"])


@router.post("/login", response_model=dict)
async def login(form_data: OAuth2PasswordRequestForm = Depends()):
async def login(response: Response, form_data=Depends(OAuth2PasswordRequestForm)):
user = User(username=form_data.username, password=form_data.password)
auth_user(user)
token = create_access_token(
data={"sub": user.username}, expires_delta=timedelta(days=1)
)
response.set_cookie(key="token", value=token, httponly=True, max_age=86400)
return {"access_token": token, "token_type": "bearer"}

return JSONResponse(
status_code=status.HTTP_200_OK,
content={
"access_token": token,
"token_type": "bearer",
"expire": 86400,
},
)


@router.get("/refresh_token", response_model=dict)
async def refresh(current_user: User = Depends(get_current_user)):
if not current_user:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED, detail="invalid token"
)
token = create_access_token(data={"sub": current_user.username})
return JSONResponse(
status_code=status.HTTP_200_OK,
content={
"access_token": token,
"token_type": "bearer",
"expire": 86400,
},
@router.get("/refresh_token", response_model=dict, dependencies=[Depends(get_current_user)])
async def refresh(response: Response):
token = create_access_token(
data={"sub": get_current_user}, expires_delta=timedelta(days=1)
)
response.set_cookie(key="token", value=token, httponly=True, max_age=86400)
return {"access_token": token, "token_type": "bearer"}


@router.get("/logout", response_model=APIResponse)
async def logout(current_user: User = Depends(get_current_user)):
if not current_user:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED, detail="invalid token"
)
@router.get("/logout", response_model=APIResponse, dependencies=[Depends(get_current_user)])
async def logout(response: Response):
active_user.clear()
response.delete_cookie(key="token")
return JSONResponse(
status_code=status.HTTP_200_OK,
content={
"msg_en": "Logout success",
"msg_zh": "登出成功",
},
status_code=200,
content={"msg_en": "Logout successfully.", "msg_zh": "登出成功。"},
)


@router.post("/update", response_model=dict)
@router.post("/update", response_model=dict, dependencies=[Depends(get_current_user)])
async def update_user(
user_data: UserUpdate, current_user: User = Depends(get_current_user)
user_data: UserUpdate, response: Response
):
if not current_user:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED, detail="invalid token"
)
if update_user_info(user_data, current_user):
return JSONResponse(
status_code=status.HTTP_200_OK,
content={
"message": "update success",
"access_token": create_access_token({"sub": user_data.username}),
"token_type": "bearer",
"expire": 86400,
},
old_user = active_user[0]
if update_user_info(user_data, old_user):
token = create_access_token(data={"sub": old_user}, expires_delta=timedelta(days=1))
response.set_cookie(
key="token",
value=token,
httponly=True,
max_age=86400,
)
return {"access_token": token, "token_type": "bearer"}
62 changes: 18 additions & 44 deletions backend/src/module/api/bangumi.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,93 +16,67 @@ def str_to_list(data: Bangumi):
return data


@router.get("/get/all", response_model=list[Bangumi])
async def get_all_data(current_user=Depends(get_current_user)):
if not current_user:
raise UNAUTHORIZED
@router.get("/get/all", response_model=list[Bangumi], dependencies=[Depends(get_current_user)])
async def get_all_data():
with TorrentManager() as manager:
return manager.bangumi.search_all()


@router.get("/get/{bangumi_id}", response_model=Bangumi)
async def get_data(bangumi_id: str, current_user=Depends(get_current_user)):
if not current_user:
raise UNAUTHORIZED
@router.get("/get/{bangumi_id}", response_model=Bangumi, dependencies=[Depends(get_current_user)])
async def get_data(bangumi_id: str):
with TorrentManager() as manager:
resp = manager.search_one(bangumi_id)
return resp


@router.patch("/update/{bangumi_id}", response_model=APIResponse)
@router.patch("/update/{bangumi_id}", response_model=APIResponse, dependencies=[Depends(get_current_user)])
async def update_rule(
bangumi_id: int, data: BangumiUpdate, current_user=Depends(get_current_user)
bangumi_id: int, data: BangumiUpdate,
):
if not current_user:
raise UNAUTHORIZED
with TorrentManager() as manager:
resp = manager.update_rule(bangumi_id, data)
return u_response(resp)


@router.delete(path="/delete/{bangumi_id}", response_model=APIResponse)
async def delete_rule(
bangumi_id: str, file: bool = False, current_user=Depends(get_current_user)
):
if not current_user:
raise UNAUTHORIZED
@router.delete(path="/delete/{bangumi_id}", response_model=APIResponse, dependencies=[Depends(get_current_user)])
async def delete_rule(bangumi_id: str, file: bool = False):
with TorrentManager() as manager:
resp = manager.delete_rule(bangumi_id, file)
return u_response(resp)


@router.delete(path="/delete/many/", response_model=APIResponse)
async def delete_many_rule(
bangumi_id: list, file: bool = False, current_user=Depends(get_current_user)
):
if not current_user:
raise UNAUTHORIZED
@router.delete(path="/delete/many/", response_model=APIResponse, dependencies=[Depends(get_current_user)])
async def delete_many_rule(bangumi_id: list, file: bool = False):
with TorrentManager() as manager:
for i in bangumi_id:
resp = manager.delete_rule(i, file)
return u_response(resp)


@router.delete(path="/disable/{bangumi_id}", response_model=APIResponse)
async def disable_rule(
bangumi_id: str, file: bool = False, current_user=Depends(get_current_user)
):
if not current_user:
raise UNAUTHORIZED
@router.delete(path="/disable/{bangumi_id}", response_model=APIResponse, dependencies=[Depends(get_current_user)])
async def disable_rule(bangumi_id: str, file: bool = False):
with TorrentManager() as manager:
resp = manager.disable_rule(bangumi_id, file)
return u_response(resp)


@router.delete(path="/disable/many/", response_model=APIResponse)
async def disable_many_rule(
bangumi_id: list, file: bool = False, current_user=Depends(get_current_user)
):
if not current_user:
raise UNAUTHORIZED
@router.delete(path="/disable/many/", response_model=APIResponse, dependencies=[Depends(get_current_user)])
async def disable_many_rule(bangumi_id: list, file: bool = False):
with TorrentManager() as manager:
for i in bangumi_id:
resp = manager.disable_rule(i, file)
return u_response(resp)


@router.get(path="/enable/{bangumi_id}", response_model=APIResponse)
async def enable_rule(bangumi_id: str, current_user=Depends(get_current_user)):
if not current_user:
raise UNAUTHORIZED
@router.get(path="/enable/{bangumi_id}", response_model=APIResponse, dependencies=[Depends(get_current_user)])
async def enable_rule(bangumi_id: str):
with TorrentManager() as manager:
resp = manager.enable_rule(bangumi_id)
return u_response(resp)


@router.get("/reset/all", response_model=APIResponse)
async def reset_all(current_user=Depends(get_current_user)):
if not current_user:
raise UNAUTHORIZED
@router.get("/reset/all", response_model=APIResponse, dependencies=[Depends(get_current_user)])
async def reset_all():
with TorrentManager() as manager:
manager.bangumi.delete_all()
return JSONResponse(
Expand Down
12 changes: 4 additions & 8 deletions backend/src/module/api/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,17 +11,13 @@
logger = logging.getLogger(__name__)


@router.get("/get", response_model=Config)
async def get_config(current_user=Depends(get_current_user)):
if not current_user:
raise UNAUTHORIZED
@router.get("/get", response_model=Config, dependencies=[Depends(get_current_user)])
async def get_config():
return settings


@router.patch("/update", response_model=APIResponse)
async def update_config(config: Config, current_user=Depends(get_current_user)):
if not current_user:
raise UNAUTHORIZED
@router.patch("/update", response_model=APIResponse, dependencies=[Depends(get_current_user)])
async def update_config(config: Config):
try:
settings.save(config_dict=config.dict())
settings.load()
Expand Down
65 changes: 0 additions & 65 deletions backend/src/module/api/download.py

This file was deleted.

12 changes: 4 additions & 8 deletions backend/src/module/api/log.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,21 +8,17 @@
router = APIRouter(prefix="/log", tags=["log"])


@router.get("")
async def get_log(current_user=Depends(get_current_user)):
if not current_user:
raise UNAUTHORIZED
@router.get("", response_model=str, dependencies=[Depends(get_current_user)])
async def get_log():
if LOG_PATH.exists():
with open(LOG_PATH, "rb") as f:
return Response(f.read(), media_type="text/plain")
else:
return Response("Log file not found", status_code=404)


@router.get("/clear", response_model=APIResponse)
async def clear_log(current_user=Depends(get_current_user)):
if not current_user:
raise UNAUTHORIZED
@router.get("/clear", response_model=APIResponse, dependencies=[Depends(get_current_user)])
async def clear_log():
if LOG_PATH.exists():
LOG_PATH.write_text("")
return JSONResponse(
Expand Down
6 changes: 2 additions & 4 deletions backend/src/module/api/program.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,10 +25,8 @@ async def shutdown():
program.stop()


@router.get("/restart", response_model=APIResponse)
async def restart(current_user=Depends(get_current_user)):
if not current_user:
raise UNAUTHORIZED
@router.get("/restart", response_model=APIResponse, dependencies=[Depends(get_current_user)])
async def restart():
try:
program.restart()
return JSONResponse(
Expand Down
Loading

0 comments on commit d6b36e5

Please sign in to comment.