Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions backend/.env.example
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,15 @@ API_V1_PREFIX="/api/v1"
# Note: NeonDB (PostgreSQL) connection string
DATABASE_URL="postgresql://user:password@localhost/dbname"


# Security
SECRET_KEY="your-secret-key-change-in-production"
ALGORITHM="HS256"
ACCESS_TOKEN_EXPIRE_MINUTES=3000

#AUTH
GOOGLE_CLIENT_ID=
GOOGLE_CLIENT_SECRET=
GOOGLE_REDIRECT_URI=http://localhost:8000/users/google/callback

FRONTEND_URL=http://localhost:5173
8 changes: 8 additions & 0 deletions backend/app/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,14 @@ class Settings(BaseSettings):
STORAGE_PROVIDER: str = "supabase"
BACKGROUND_WORKER: str = "taskiq"

# Goole Oauth
GOOGLE_CLIENT_ID: str = ""
GOOGLE_CLIENT_SECRET: str = ""
GOOGLE_REDIRECT_URI: str = ""

# Frontend
FRONTEND_URL: str = ""

class Config:
env_file = ".env"
case_sensitive = True
Expand Down
8 changes: 8 additions & 0 deletions backend/app/main.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
from collections.abc import AsyncGenerator
from contextlib import asynccontextmanager

from authlib.integrations.starlette_client import OAuth
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from starlette.middleware.sessions import SessionMiddleware

from app.config import settings
from app.exceptions.auth import register_auth_exception_handlers
Expand Down Expand Up @@ -49,6 +51,12 @@ async def lifespan(_: FastAPI) -> AsyncGenerator[None, None]:
allow_methods=["*"],
allow_headers=["*"],
)

app.add_middleware(
SessionMiddleware,
secret_key=settings.SECRET_KEY,
)

register_auth_exception_handlers(app)
register_common_exception_handlers(app)
register_sql_alchemy_exception_handlers(app)
Expand Down
55 changes: 54 additions & 1 deletion backend/app/routers/user.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,11 @@
from fastapi import APIRouter, Depends, status
from typing import cast

from fastapi import APIRouter, Depends, Request, status
from fastapi.responses import RedirectResponse
from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession

from app.config import settings
from app.database import get_db
from app.exceptions.auth import UserNotFoundError
from app.logger import get_logger
Expand All @@ -15,6 +19,7 @@
)
from app.utils.authorization import get_current_user, verify_ownership
from app.utils.bcrypt_hasher import BcryptHasher
from app.utils.google_oauth import oauth
from app.utils.jwt_auth import JwtAuth

logger = get_logger(__name__)
Expand Down Expand Up @@ -55,6 +60,14 @@ async def login(credentials: UserLogin, db: AsyncSession = Depends(get_db)) -> T
return TokenResponse(token=token, user=UserResponse.model_validate(user))


@router.get("/me", response_model=UserResponse)
async def get_me(
current_user: User = Depends(get_current_user), db: AsyncSession = Depends(get_db)
) -> UserResponse:
await db.refresh(current_user, attribute_names=["profile"])
return UserResponse.model_validate(current_user)


@router.get("/{user_id}", response_model=UserResponse)
async def get_user(
user_id: int,
Expand Down Expand Up @@ -141,3 +154,43 @@ async def delete_user(
await db.delete(user)
await db.commit()
logger.info("User deleted successfully: %d", user_id)


# Google Oauth login
@router.get("/google/login")
async def google_login(request: Request) -> RedirectResponse:
return cast(
RedirectResponse,
await oauth.google.authorize_redirect(
request, redirect_uri="http://localhost:8000/users/google/callback"
),
)


@router.get("/google/callback")
async def google_callback(
request: Request,
db: AsyncSession = Depends(get_db),
) -> RedirectResponse:
token = await oauth.google.authorize_access_token(request)
user_info = token.get("userinfo")
email = user_info["email"]
username = user_info.get("name", email.split("@")[0])
result = await db.execute(select(User).where(User.email == email))
user = result.scalar_one_or_none()
if not user:
user = User(
username=username,
email=email,
password_hash="none",
)
db.add(user)
await db.flush()
profile = UserProfile(user_id=user.id)
db.add(profile)
await db.commit()
await db.refresh(user)
auth = JwtAuth(db)
access_token = await auth.generate_token(user)

return RedirectResponse(url=f"{settings.FRONTEND_URL}?token={access_token}")
15 changes: 15 additions & 0 deletions backend/app/utils/google_oauth.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
from authlib.integrations.starlette_client import OAuth

from app.config import settings

oauth = OAuth()

oauth.register(
name="google",
client_id=settings.GOOGLE_CLIENT_ID,
client_secret=settings.GOOGLE_CLIENT_SECRET,
server_metadata_url="https://accounts.google.com/.well-known/openid-configuration",
client_kwargs={
"scope": "openid email profile",
},
)
5 changes: 3 additions & 2 deletions backend/app/utils/jwt_auth.py
Original file line number Diff line number Diff line change
Expand Up @@ -110,14 +110,15 @@ async def generate_token(self, user: User) -> str:
return token

async def authenticate(self, username: str, password: str) -> User:

result = await self.db_session.execute(select(User).where(User.username == username))

user = result.scalar_one_or_none()

if not user:
raise InvalidUserCredentialsError()

if not user.password_hash:
raise InvalidUserCredentialsError()

if not self.hasher.verify(password, user.password_hash):
raise InvalidUserCredentialsError()

Expand Down
4 changes: 4 additions & 0 deletions backend/pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -23,10 +23,14 @@ dependencies = [
"taskiq-redis>=0.5.0",
"python-multipart>=0.0.27",
"supabase>=2.30.0",
"authlib>=1.7.2",
"httpx>=0.28.1",
"itsdangerous>=2.2.0",
]

[dependency-groups]
dev = [
"mypy>=1.20.1",
"ruff>=0.15.10",
"pytest>=8.0.0",
]
15 changes: 15 additions & 0 deletions backend/tests/test_auth.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
from fastapi.testclient import TestClient

from app.main import app

client = TestClient(app)


def test_app_runs() -> None:
response = client.get("/google/login")
assert response.status_code != 500


def test_google_callback_exists() -> None:
response = client.get("/google/callback")
assert response.status_code != 500
76 changes: 76 additions & 0 deletions backend/uv.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading