User Authentication Service
A FastAPI-based user authentication service with JWT token authentication.
Features
- User registration and login
- JWT-based authentication
- Password hashing with bcrypt
- SQLite database with SQLAlchemy ORM
- Alembic migrations
- Protected routes with OAuth2 dependencies
- Health check endpoint
Project Structure
.
├── alembic.ini
├── app
│ ├── api
│ │ ├── deps.py
│ │ ├── endpoints
│ │ │ ├── auth.py
│ │ │ ├── health.py
│ │ │ └── users.py
│ │ └── routes.py
│ ├── core
│ │ ├── config.py
│ │ └── security.py
│ ├── crud
│ │ ├── base.py
│ │ └── user.py
│ ├── db
│ │ ├── base.py
│ │ ├── base_class.py
│ │ └── session.py
│ ├── models
│ │ └── user.py
│ ├── schemas
│ │ ├── token.py
│ │ └── user.py
│ └── utils
├── main.py
├── migrations
│ ├── env.py
│ └── versions
│ └── 0001_create_users_table.py
└── requirements.txt
Setup
- Clone the repository:
git clone <repository-url>
cd userauthenticationservice
- Create a virtual environment and install dependencies:
python -m venv venv
source venv/bin/activate # On Windows: venv\Scripts\activate
pip install -r requirements.txt
- Set up environment variables:
Create a .env
file in the root directory with the following content:
SECRET_KEY=your-secret-key
ACCESS_TOKEN_EXPIRE_MINUTES=10080 # 7 days
- Run database migrations:
alembic upgrade head
- Run the application:
uvicorn main:app --reload
API Endpoints
Authentication
-
POST /auth/register: Register a new user
- Request:
{ "email": "user@example.com", "username": "username", "password": "password" }
- Response: User object
- Request:
-
POST /auth/login: Login and get access token
- Request: Form data with
username
(email) andpassword
- Response:
{ "access_token": "token", "token_type": "bearer" }
- Request: Form data with
Users
-
GET /users/me: Get current user details (requires authentication)
- Response: User object
-
PUT /users/me: Update current user details (requires authentication)
- Request:
{ "email": "new-email@example.com", "username": "new-username", "password": "new-password" }
- Response: Updated user object
- Request:
Health Check
- GET /health: Check API health
- Response:
{ "status": "healthy", "database": "healthy" }
- Response:
Authentication
The API uses JWT tokens for authentication. To access protected endpoints, include the token in the Authorization header:
Authorization: Bearer <your-token>
Database
The application uses SQLite as the database, with the file stored at /app/storage/db/db.sqlite
.
SQLAlchemy is used as the ORM, and Alembic for database migrations.
Environment Variables
SECRET_KEY
: Secret key used for JWT token generationACCESS_TOKEN_EXPIRE_MINUTES
: Token expiration time in minutes (default: 10080 - 7 days)BACKEND_CORS_ORIGINS
: List of allowed CORS origins (default: "*")
Description
Languages
Python
97.6%
Mako
2.4%