feat: add models yaml
This commit is contained in:
parent
8e3e4daaef
commit
7f4d970198
13
design/classes/User.yaml
Normal file
13
design/classes/User.yaml
Normal 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()
|
7
design/db/mysql/Comments.yaml
Normal file
7
design/db/mysql/Comments.yaml
Normal 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
|
7
design/db/mysql/Posts.yaml
Normal file
7
design/db/mysql/Posts.yaml
Normal 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
|
10
design/db/mysql/Users.yaml
Normal file
10
design/db/mysql/Users.yaml
Normal 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
52
main.py
@ -1,10 +1,10 @@
|
||||
import uvicorn
|
||||
from passlib.context import CryptContext
|
||||
from datetime import datetime, timedelta
|
||||
import jwt
|
||||
from fastapi import FastAPI, HTTPException, Request
|
||||
from models.User import User
|
||||
from fastapi import FastAPI, Request
|
||||
from models.User import *
|
||||
from models.Token import *
|
||||
from controllers.JWT import secret_key
|
||||
from starlette.responses import Response
|
||||
|
||||
|
||||
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")
|
||||
async def login(user: User):
|
||||
async def login(request: Request, response: Response, user: UserLogin):
|
||||
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]
|
||||
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)
|
||||
return {"access_token": token}
|
||||
|
||||
|
||||
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")
|
||||
response.set_cookie("token", token)
|
||||
return {"code": 200, "status": "success"}
|
||||
|
||||
|
||||
@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")
|
||||
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:
|
||||
payload = jwt.decode(cookie, secret_key, algorithms=["HS256"])
|
||||
payload = jwt.decode(token, secret_key, algorithms=["HS256"])
|
||||
username = payload["username"]
|
||||
if username == "guest":
|
||||
return {"code": 200, "status": "success", "username": "guest"}
|
||||
if username not in users_db:
|
||||
raise HTTPException(status_code=401, detail="Invalid username")
|
||||
return {"username": username}
|
||||
response.status_code = 401
|
||||
return {"code": 401, "status": "error", "detail": "Invalid username"}
|
||||
return {"code": 200, "status": "success", "username": username}
|
||||
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__':
|
||||
|
19
models/Token.py
Normal file
19
models/Token.py
Normal 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
|
@ -1,6 +1,6 @@
|
||||
from pydantic import BaseModel
|
||||
|
||||
|
||||
class User(BaseModel):
|
||||
class UserLogin(BaseModel):
|
||||
username: str
|
||||
password: str
|
||||
|
@ -1,17 +1,26 @@
|
||||
import requests
|
||||
|
||||
|
||||
url = "http://127.0.0.1/login"
|
||||
data = {
|
||||
"username": "admin",
|
||||
"password": "admin123"
|
||||
}
|
||||
r = requests.post(url, json=data)
|
||||
token = r.json()["access_token"]
|
||||
headers = {
|
||||
"Cookie": token
|
||||
}
|
||||
print(token)
|
||||
conn = requests.Session()
|
||||
url = "http://127.0.0.1"
|
||||
r = conn.get(url)
|
||||
# print(r.json())
|
||||
print(r.headers)
|
||||
# url = "http://127.0.0.1/login"
|
||||
# data = {
|
||||
# "username": "admin",
|
||||
# "password": "admin123"
|
||||
# }
|
||||
# r = requests.post(url, json=data)
|
||||
# print(r.json())
|
||||
# token = r.headers.get("set-cookie")
|
||||
# headers = {
|
||||
# "Cookie": token
|
||||
# }
|
||||
# print(token)
|
||||
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)
|
||||
|
Loading…
Reference in New Issue
Block a user