GabrielEValenzuela / chatML

A web API exposing a neural network to detect duplicate entities in knowledge graphs. It uses API key authentication and rate limits requests based on client tiers (FREEMIUM, PREMIUM)
MIT License
0 stars 0 forks source link

Create `register` and `login` endpoints #8

Open GabrielEValenzuela opened 4 weeks ago

GabrielEValenzuela commented 4 weeks ago

Description

Develop register and login endpoints within the FastAPI library. The register endpoint will allow new users to create an account, and the login endpoint will validate credentials. Upon successful login, the endpoint should return an API key, which the user will use for authenticating future requests to protected endpoints (e.g., /service). The task includes secure storage of user credentials and token generation.

User Stories


Details


Example Usage and Responses


Implementation Steps

  1. Create User Database Model:

    • Define a user model in the database (e.g., SQLite) with fields username, hashed_password, and token (if using API keys).
    • Store hashed passwords using a secure hashing function like bcrypt.
  2. Develop Registration Endpoint (/register):

    • Validate the JSON payload for required fields (username and password).
    • Check if the username already exists in the database. If it does, return an error.
    • Hash the password and store the new user record in the database.
    • Return a success message.
  3. Develop Login Endpoint (/login):

    • Validate the JSON payload for required fields (username and password).
    • Retrieve the user from the database by username.
    • Verify the password against the stored hash.
    • If valid:
      • Generate a unique API key and store it in the database for the user.
    • Return the token (API key) in the response.
  4. Secure Endpoint Integration:

    • Modify /service and any future protected endpoints to require authentication by checking the provided token.
    • Verify the key against the stored tokens in the database.

Code Mockup

Here’s an example using JWT for token generation.

from fastapi import APIRouter, HTTPException, Depends
from pydantic import BaseModel
from src.app.utils.auth import authenticate_user, create_access_token, hash_password
from src.app.db.database import get_user, create_user

router = APIRouter()

# Models for request bodies
class RegisterRequest(BaseModel):
    username: str
    password: str

class LoginRequest(BaseModel):
    username: str
    password: str

# Register endpoint
@router.post("/register")
async def register(request: RegisterRequest):
    if get_user(request.username):
        raise HTTPException(status_code=400, detail="Username already exists")

    hashed_password = hash_password(request.password)
    create_user(request.username, hashed_password)

    return {"message": "User registered successfully."}

# Login endpoint
@router.post("/login")
async def login(request: LoginRequest):
    user = authenticate_user(request.username, request.password)
    if not user:
        raise HTTPException(status_code=401, detail="Invalid credentials")

    token = create_access_token(data={"sub": user.username})
    return {"token": token}

Edge Cases