Skip to content

Commit

Permalink
feat(routes): Remove content routes & update user creation functionality
Browse files Browse the repository at this point in the history
This commit removes the content routes from the application and adds functionality to create new users. The `content.py` file has been deleted, along with its associated model classes and route handlers. The `user.py` file now includes a new route handler for creating users, which checks if the username already exists and only allows superusers to create other superuser accounts. Additionally, if this is the first user being created in the database, they are automatically assigned as a superuser.

The changes made in this commit simplify the codebase by removing unused functionality and enhance user management capabilities by allowing for easy creation of new accounts.
  • Loading branch information
SakuraIsayeki committed Jul 19, 2023
1 parent a6fc27d commit 30f7145
Show file tree
Hide file tree
Showing 5 changed files with 23 additions and 200 deletions.
73 changes: 0 additions & 73 deletions wowskarma_api_minimap/src/models/content.py

This file was deleted.

2 changes: 0 additions & 2 deletions wowskarma_api_minimap/src/routes/__init__.py
Original file line number Diff line number Diff line change
@@ -1,13 +1,11 @@
from fastapi import APIRouter

from .content import router as content_router
from .profile import router as profile_router
from .security import router as security_router
from .user import router as user_router

main_router = APIRouter()

main_router.include_router(content_router, prefix="/content", tags=["content"])
main_router.include_router(profile_router, tags=["user"])
main_router.include_router(security_router, tags=["security"])
main_router.include_router(user_router, prefix="/user", tags=["user"])
Expand Down
105 changes: 0 additions & 105 deletions wowskarma_api_minimap/src/routes/content.py

This file was deleted.

29 changes: 19 additions & 10 deletions wowskarma_api_minimap/src/routes/user.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,17 +26,31 @@ async def list_users(*, session: Session = ActiveSession):
return users


@router.post("/", response_model=UserResponse, dependencies=[AdminUser])
@router.post("/", response_model=UserResponse)
async def create_user(*, session: Session = ActiveSession, user: UserCreate):

# verify user with username doesn't already exist
try:
await query_user(session=session, user_id_or_username=user.username)
await query_user(session=session, username=user.username)
except HTTPException:
pass
else:
raise HTTPException(status_code=422, detail="Username already exists")
raise HTTPException(status_code=422, detail="Username is already taken")

# If the new user is marked as superuser, check the current user is superuser too
try:
current_user: User = get_current_user()
except Exception as e:
current_user = None

if user.superuser and (not current_user or not current_user.superuser):
raise HTTPException(status_code=403, detail="Only superusers can create superuser accounts")

# If this is the first user in database, make it a superuser
if not session.exec(select(User)).first():
user.superuser = True

# Create the user
db_user = User.from_orm(user)
session.add(db_user)
session.commit()
Expand Down Expand Up @@ -86,14 +100,9 @@ async def update_user_password(
dependencies=[AuthenticatedUser],
)
async def query_user(
*, session: Session = ActiveSession, user_id_or_username: Union[str, int]
*, session: Session = ActiveSession, username: Union[str, int]
):
user = session.query(User).where(
or_(
User.id == user_id_or_username,
User.username == user_id_or_username,
)
)
user = session.query(User).where(User.username == username)

if not user.first():
raise HTTPException(status_code=404, detail="User not found")
Expand Down
14 changes: 4 additions & 10 deletions wowskarma_api_minimap/src/security.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import uuid as uuid_pkg
from datetime import datetime, timedelta
from typing import Callable, List, Optional, Union

Expand All @@ -8,8 +9,6 @@
from pydantic import BaseModel
from sqlmodel import Field, Relationship, Session, SQLModel

from .models.content import Content, ContentResponse

from .config import settings
from .db import engine

Expand Down Expand Up @@ -67,26 +66,21 @@ def validate(cls, v):


class User(SQLModel, table=True):
id: Optional[int] = Field(default=None, primary_key=True)
username: str = Field(sa_column_kwargs={"unique": True})
id: uuid_pkg.UUID = Field(default_factory=uuid_pkg.uuid4, primary_key=True, index=True, nullable=False)
username: str = Field(unique=True, index=True, nullable=False)
password: HashedPassword
superuser: bool = False
disabled: bool = False

# it populates the .user attribute on the Content Model
contents: List["Content"] = Relationship(back_populates="user")


class UserResponse(BaseModel):
"""This is the User model to be used as a response_model
it doesn't include the password.
"""

id: int
id: uuid_pkg.UUID
username: str
disabled: bool
superuser: bool
contents: Optional[List[ContentResponse]] = Field(default_factory=list)


class UserCreate(BaseModel):
Expand Down

0 comments on commit 30f7145

Please sign in to comment.