feat: add models yaml

This commit is contained in:
gaze 2024-01-23 19:30:28 +08:00
parent 8e3e4daaef
commit 7f4d970198
8 changed files with 112 additions and 33 deletions

13
design/classes/User.yaml Normal file
View File

@ -0,0 +1,13 @@
User:
uuid: str
email: str
password: str md5()
name: str
avatar: str url
detail: str
privilege: int
functions:
- login(email, password)
- change_pwd(password, new_password)
- update(attr, new_value)
- logout()

View File

@ -0,0 +1,7 @@
Comment:
uuid: str unique
uid: str foreign_key to Users
pid: foreign_key to Posts
updated_at: timestamp
created_at: timestamp
content: str

View File

@ -0,0 +1,7 @@
Post:
uuid: str unique
title: str unique
uid: str foreign_key to Users
updated_at: timestamp
created_at: timestamp
content: str

View File

@ -0,0 +1,10 @@
User:
uuid: str unique
email: str unique
password: str md5()
name: str
created_at: time_stamp
updated_at: time_stamp
avatar: str url
detail: str
privilege: int

52
main.py
View File

@ -1,10 +1,10 @@
import uvicorn import uvicorn
from passlib.context import CryptContext from passlib.context import CryptContext
from datetime import datetime, timedelta from fastapi import FastAPI, Request
import jwt from models.User import *
from fastapi import FastAPI, HTTPException, Request from models.Token import *
from models.User import User
from controllers.JWT import secret_key from controllers.JWT import secret_key
from starlette.responses import Response
app = FastAPI() app = FastAPI()
@ -19,34 +19,48 @@ users_db = {
} }
@app.get("/")
async def index(request: Request, response: Response,):
cookie = request.headers.get("Cookie")
if cookie is None:
token = await generate_token("guest")
response.set_cookie("token", token)
return {"code": 200, "status": "success"}
@app.post("/login") @app.post("/login")
async def login(user: User): async def login(request: Request, response: Response, user: UserLogin):
if user.username not in users_db: if user.username not in users_db:
raise HTTPException(status_code=401, detail="Invalid username") response.status_code = 401
return {"code": 401, "status": "error", "detail": "Invalid username"}
stored_user = users_db[user.username] stored_user = users_db[user.username]
if not pwd_context.verify(user.password, stored_user["password"]): if not pwd_context.verify(user.password, stored_user["password"]):
raise HTTPException(status_code=401, detail="Invalid password") response.status_code = 401
return {"code": 401, "status": "error", "detail": "Invalid password"}
token = await generate_token(user.username) token = await generate_token(user.username)
return {"access_token": token} response.set_cookie("token", token)
return {"code": 200, "status": "success"}
async def generate_token(username: str) -> str:
expiration = datetime.utcnow() + timedelta(minutes=30)
payload = {"username": username, "exp": expiration}
return jwt.encode(payload, secret_key, algorithm="HS256")
@app.get("/users/me") @app.get("/users/me")
async def get_user_profile(request: Request): async def get_user_profile(request: Request, response: Response):
cookie = request.headers.get("Cookie") cookie = request.headers.get("Cookie")
token = await get_token_from_cookie(cookie)
if token is None:
response.status_code = 400
return {"code": 400, "status": "error", "detail": "Token is required"}
try: try:
payload = jwt.decode(cookie, secret_key, algorithms=["HS256"]) payload = jwt.decode(token, secret_key, algorithms=["HS256"])
username = payload["username"] username = payload["username"]
if username == "guest":
return {"code": 200, "status": "success", "username": "guest"}
if username not in users_db: if username not in users_db:
raise HTTPException(status_code=401, detail="Invalid username") response.status_code = 401
return {"username": username} return {"code": 401, "status": "error", "detail": "Invalid username"}
return {"code": 200, "status": "success", "username": username}
except jwt.DecodeError: except jwt.DecodeError:
raise HTTPException(status_code=401, detail="Invalid token") response.status_code = 401
return {"code": 401, "status": "error", "detail": "Invalid token"}
if __name__ == '__main__': if __name__ == '__main__':

19
models/Token.py Normal file
View File

@ -0,0 +1,19 @@
from datetime import datetime, timedelta
from typing import Union
from controllers.JWT import secret_key
import jwt
async def generate_token(username: str) -> str:
expiration = datetime.utcnow() + timedelta(minutes=30)
payload = {"username": username, "exp": expiration}
return jwt.encode(payload, secret_key, algorithm="HS256")
async def get_token_from_cookie(cookie: str) -> Union[str, None]:
for item in cookie.split("; "):
if "token=" not in item:
continue
token = item.replace("token=", "")
return token
return None

View File

@ -1,6 +1,6 @@
from pydantic import BaseModel from pydantic import BaseModel
class User(BaseModel): class UserLogin(BaseModel):
username: str username: str
password: str password: str

View File

@ -1,17 +1,26 @@
import requests import requests
conn = requests.Session()
url = "http://127.0.0.1/login" url = "http://127.0.0.1"
data = { r = conn.get(url)
"username": "admin", # print(r.json())
"password": "admin123" print(r.headers)
} # url = "http://127.0.0.1/login"
r = requests.post(url, json=data) # data = {
token = r.json()["access_token"] # "username": "admin",
headers = { # "password": "admin123"
"Cookie": token # }
} # r = requests.post(url, json=data)
print(token) # print(r.json())
# token = r.headers.get("set-cookie")
# headers = {
# "Cookie": token
# }
# print(token)
url = "http://127.0.0.1/users/me" url = "http://127.0.0.1/users/me"
r = requests.get(url, headers=headers) token = r.headers.get('set-cookie')
headers = {
"Cookie": f"token={token}"
}
r = conn.get(url, headers=headers)
print(r.text) print(r.text)