
- Create user model and database connection - Set up Alembic migrations - Implement JWT token authentication - Add routes for registration, login, refresh, and user profile - Create health endpoint - Configure CORS - Update README with setup and usage instructions
2.5 KiB
2.5 KiB
User Authentication Service
A FastAPI service for user authentication with JWT tokens.
Features
- User registration and login
- JWT token-based authentication
- Token refresh functionality
- Password hashing with bcrypt
- SQLite database with SQLAlchemy ORM
- Alembic migrations
- CORS support
- Health endpoint
Prerequisites
- Python 3.9+
- pip (Python package manager)
Setup
- Clone the repository:
git clone <repository-url>
cd userauthenticationservice-0fe432
- Create and activate a virtual environment (optional but recommended):
python -m venv venv
source venv/bin/activate # On Windows: venv\Scripts\activate
- Install dependencies:
pip install -r requirements.txt
- Create a
.env
file based on the.env.example
:
cp .env.example .env
- Edit the
.env
file and set a secure secret key:
SECRET_KEY=your_secure_secret_key
- Run database migrations:
alembic upgrade head
Running the Service
Start the service with:
uvicorn main:app --reload
The API will be available at http://localhost:8000
API documentation is available at:
- Swagger UI: http://localhost:8000/docs
- ReDoc: http://localhost:8000/redoc
API Endpoints
POST /api/v1/auth/register
- Register a new userPOST /api/v1/auth/login
- Login and get access tokenPOST /api/v1/auth/refresh
- Refresh access tokenGET /api/v1/auth/me
- Get current user informationPUT /api/v1/auth/me
- Update current user informationGET /health
- Health check endpoint
Environment Variables
Variable | Description | Default |
---|---|---|
SECRET_KEY | JWT signing key | supersecretkey |
ALGORITHM | JWT algorithm | HS256 |
ACCESS_TOKEN_EXPIRE_MINUTES | Access token lifetime in minutes | 30 |
REFRESH_TOKEN_EXPIRE_DAYS | Refresh token lifetime in days | 7 |
DATABASE_URL | SQLite database URL | sqlite:///app/storage/db/db.sqlite |
Authentication Flow
- Register a user with
POST /api/v1/auth/register
- Login with
POST /api/v1/auth/login
to get access and refresh tokens - Use the access token in the
Authorization
header for protected endpoints - When the access token expires, use
POST /api/v1/auth/refresh
with the refresh token to get a new access token
Development
This project uses:
- FastAPI for the API framework
- SQLAlchemy for ORM
- Alembic for database migrations
- Pydantic for data validation
- python-jose for JWT handling
- passlib and bcrypt for password hashing