Add user creation
This commit is contained in:
parent
58382df49d
commit
97afe5447a
3 changed files with 29 additions and 3 deletions
|
|
@ -7,9 +7,9 @@ from fastapi.security import OAuth2PasswordBearer
|
|||
from pwdlib import PasswordHash
|
||||
|
||||
from app.config import Settings
|
||||
from app.database import get_from_database_where
|
||||
from app.database import add_to_database, get_from_database_where
|
||||
from app.models.token import TokenData
|
||||
from app.models.user import User, UserInDB
|
||||
from app.models.user import User, UserIn, UserInDB
|
||||
|
||||
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token")
|
||||
|
||||
|
|
@ -37,6 +37,16 @@ def get_user(username: str):
|
|||
return UserInDB.model_validate(user[0])
|
||||
|
||||
|
||||
def save_user(user: UserIn):
|
||||
user_in_db = UserInDB(
|
||||
username=user.username,
|
||||
authority=user.authority,
|
||||
hashed_password=get_password_hash(user.password),
|
||||
)
|
||||
add_to_database(user_in_db)
|
||||
return user_in_db
|
||||
|
||||
|
||||
def authenticate_user(username: str, password: str):
|
||||
user = get_user(username)
|
||||
if not user:
|
||||
|
|
|
|||
|
|
@ -9,5 +9,9 @@ class User(SQLModel, table=True):
|
|||
authority: int
|
||||
|
||||
|
||||
class UserIn(User):
|
||||
password: str
|
||||
|
||||
|
||||
class UserInDB(User):
|
||||
hashed_password: str
|
||||
|
|
|
|||
|
|
@ -9,9 +9,10 @@ from app.logic.user_logic import (
|
|||
authenticate_user,
|
||||
create_access_token,
|
||||
get_current_user,
|
||||
save_user,
|
||||
)
|
||||
from app.models.token import Token
|
||||
from app.models.user import User
|
||||
from app.models.user import User, UserIn
|
||||
|
||||
router = APIRouter(prefix="/users", tags=["users"])
|
||||
|
||||
|
|
@ -21,6 +22,17 @@ def get_default():
|
|||
return {"message": "Root for Users API"}
|
||||
|
||||
|
||||
@router.post("/")
|
||||
async def create_user(user_in: UserIn):
|
||||
user = save_user(user_in)
|
||||
access_token_expires = timedelta(minutes=Settings.access_token_expire_minutes)
|
||||
access_token = create_access_token(
|
||||
data={"sub": user.username},
|
||||
expires_delta=access_token_expires,
|
||||
)
|
||||
return Token(access_token=access_token, token_type="bearer")
|
||||
|
||||
|
||||
@router.get("/me")
|
||||
async def read_me(current_user: Annotated[User, Depends(get_current_user)]):
|
||||
return current_user
|
||||
|
|
|
|||
Loading…
Reference in a new issue