A comprehensive Flask-based authentication system with OAuth integration, multi-factor authentication (MFA), email verification, password reset functionality, and advanced security features.
- User Registration & Login - Secure user account creation and authentication
- Google OAuth Integration - Sign in with Google account
- JWT Token Management - Access and refresh token handling with automatic blacklisting
- Multi-Factor Authentication (MFA) - TOTP-based two-factor authentication using PyOTP
- Session Management - Automatic token cleanup for inactive users
- Rate Limiting - Protection against brute force attacks
- Password Security - Bcrypt hashing for password storage
- Email Verification - Account activation via email confirmation
- Password Reset - Secure password recovery via email
- Token Blacklisting - Automatic invalidation of compromised tokens
- HTTPS Enforcement - Optional HTTPS redirection for production
- CORS Support - Cross-origin resource sharing configuration
- Profile Management - User profile updates with profile picture upload
- OTP Verification - One-time password for additional security
- Activity Tracking - User activity monitoring with batch processing
- Account Status - Active/inactive account management
- Email Confirmation - Account verification emails
- Password Reset Emails - Secure password recovery
- Resend Confirmation - Re-send verification emails
- Gmail SMTP Integration - Email delivery via Gmail
- Backend Framework: Flask 3.1.1
- Database: SQLAlchemy with SQLite (configurable)
- Authentication: Flask-JWT-Extended, Authlib
- Email: Flask-Mail with Gmail SMTP
- Security: Flask-Bcrypt, PyOTP, Cryptography
- Rate Limiting: Flask-Limiter
- Task Scheduling: APScheduler
- File Uploads: Flask-Uploads, Pillow
- CORS: Flask-CORS
- Python 3.8 or higher
- Gmail account for email functionality
- Google Cloud Console project for OAuth (optional)
-
Clone the repository
git clone <repository-url> cd flask_oauth_app
-
Create a virtual environment
python -m venv .venv source .venv/bin/activate # On Windows: .venv\Scripts\activate
-
Install dependencies
pip install -r requirements.txt
-
Environment Configuration
Create a
.envfile in the root directory with the following variables:# Flask Configuration SECRET_KEY=your-secret-key-here JWT_SECRET_KEY=your-jwt-secret-key-here WTF_CSRF_SECRET_KEY=your-csrf-secret-key-here FLASK_ENV=development # Database Configuration SQLALCHEMY_DATABASE_URI=sqlite:///user.db # Google OAuth Configuration (Optional) GOOGLE_CLIENT_ID=your-google-client-id GOOGLE_CLIENT_SECRET=your-google-client-secret GOOGLE_DISCOVERY_URL=https://accounts.google.com/.well-known/openid-configuration SERVER_METADATA_URL=https://accounts.google.com/.well-known/openid-configuration # Email Configuration MAIL_USERNAME=your-gmail-address@gmail.com MAIL_PASSWORD=your-gmail-app-password # Application Configuration FERNET_KEY=your-fernet-encryption-key BASE_URL=http://127.0.0.1:5000 # Security Configuration (Optional) FORCE_HTTPS=false
-
Google OAuth Setup (Optional)
- Go to Google Cloud Console
- Create a new project or select existing one
- Enable Google+ API
- Create OAuth 2.0 credentials
- Add authorized redirect URIs:
http://localhost:5000/auth/google/callback
-
Gmail App Password Setup
- Enable 2-factor authentication on your Gmail account
- Generate an app-specific password
- Use this password in the
MAIL_PASSWORDenvironment variable
-
Start the Flask application
python app.py
-
Access the application
- API Base URL:
http://127.0.0.1:5000 - The application will create database tables automatically on first run
- API Base URL:
| Method | Endpoint | Description | Rate Limit |
|---|---|---|---|
| POST | /signup |
User registration | Default |
| POST | /login |
User login | 5/minute |
| POST | /logout |
User logout | Default |
| POST | /refresh |
Refresh JWT token | Default |
| Method | Endpoint | Description |
|---|---|---|
| GET | /auth/google |
Initiate Google OAuth |
| GET | /auth/google/callback |
Google OAuth callback |
| Method | Endpoint | Description | Rate Limit |
|---|---|---|---|
| GET | /confirm/<token> |
Confirm email address | Default |
| POST | /resend-confirmation |
Resend confirmation email | 5/minute |
| POST | /forgot-password |
Request password reset | 5/minute |
| POST | /reset-password/<token> |
Reset password | 5/minute |
| Method | Endpoint | Description |
|---|---|---|
| POST | /mfa |
Setup/verify MFA |
| POST | /send-otp |
Send OTP code |
| POST | /verify-otp |
Verify OTP code |
| Method | Endpoint | Description |
|---|---|---|
| GET/PUT | /profile |
Get/update user profile |
- Global Limits: 200 requests/day, 50 requests/hour
- Endpoint-specific Limits: 5 requests/minute for sensitive operations
- Memory-based Storage: Uses in-memory storage for rate limiting
- Access Tokens: 30-minute expiration
- Refresh Tokens: 1-day expiration
- Automatic Blacklisting: Tokens for inactive users (20+ minutes)
- Cleanup Jobs: Scheduled cleanup of expired tokens
- Bcrypt Hashing: Industry-standard password hashing
- Strength Requirements: Configurable password policies
- Reset Tokens: Secure, time-limited password reset tokens
- Fernet Encryption: MFA secrets encrypted at rest
- JWT Security: Secure token generation and validation
- HTTPS Support: Optional HTTPS enforcement
flask_oauth_app/
βββ app.py # Main application file
βββ config.py # Configuration settings
βββ model.py # Database models
βββ requirements.txt # Python dependencies
βββ .env # Environment variables (not in repo)
βββ .gitignore # Git ignore rules
βββ app.log # Application logs
βββ resources/ # API resource modules
β βββ __init__.py
β βββ auth.py # Login/logout endpoints
β βββ signup.py # User registration
β βββ profile.py # User profile management
β βββ mfa.py # Multi-factor authentication
β βββ token_refresh.py # Token refresh logic
β βββ google_auth.py # Google OAuth integration
β βββ email_confirmation.py # Email verification
β βββ password_reset.py # Password reset functionality
β βββ otp.py # OTP verification
β βββ utils.py # Utility functions
βββ instance/ # Instance-specific files
βββ uploads/ # File upload directory
β βββ profile_pictures/
βββ .venv/ # Virtual environment
- SQLite: Default database (development)
- PostgreSQL/MySQL: Supported via SQLAlchemy URI
- Connection Pooling: Configurable via SQLAlchemy
- SMTP Server: Gmail SMTP (configurable)
- SSL/TLS: Supports both SSL and TLS
- Timeout: Configurable email timeout (default: 20s)
- Upload Directory:
uploads/profile_pictures/ - Max File Size: 16MB
- Allowed Extensions: PNG, JPG, JPEG, GIF
- Log Levels: INFO, WARNING, ERROR
- Log Destinations: File (
app.log) and console - Structured Logging: Timestamp, level, module, message
- Token Cleanup: Daily cleanup of expired blacklist tokens
- Inactive User Cleanup: Every 5 minutes, blacklist tokens for inactive users
- Activity Batching: Batch processing of user activity updates
- User Registration: Test signup with email verification
- Login Flow: Test login with and without MFA
- OAuth Flow: Test Google OAuth integration
- Password Reset: Test forgot password functionality
- Rate Limiting: Test rate limit enforcement
- Postman: Import API collection for testing
- curl: Command-line testing examples
- HTTPie: Alternative HTTP client
- Environment Variables: Set production values in
.env - Database: Use PostgreSQL or MySQL for production
- HTTPS: Enable
FORCE_HTTPS=true - Secret Keys: Generate secure, random secret keys
- Email: Configure production SMTP settings
- Rate Limiting: Consider Redis for distributed rate limiting
FROM python:3.9-slim
WORKDIR /app
COPY requirements.txt .
RUN pip install -r requirements.txt
COPY . .
EXPOSE 5000
CMD ["python", "app.py"]- Fork the repository
- Create a feature branch (
git checkout -b feature/amazing-feature) - Commit your changes (
git commit -m 'Add amazing feature') - Push to the branch (
git push origin feature/amazing-feature) - Open a Pull Request
This project is licensed under the MIT License - see the LICENSE file for details.
-
Email Not Sending
- Verify Gmail app password is correct
- Check firewall settings for SMTP ports
- Ensure 2FA is enabled on Gmail account
-
Google OAuth Not Working
- Verify Google Client ID and Secret
- Check authorized redirect URIs in Google Console
- Ensure Google+ API is enabled
-
Database Errors
- Check database file permissions
- Verify SQLAlchemy URI format
- Ensure database directory exists
-
Rate Limiting Issues
- Check rate limit configuration
- Consider using Redis for production
- Monitor rate limit logs
Enable debug mode for development:
app.run(debug=True)Check app.log for detailed error messages and application flow.
For support and questions:
- Create an issue in the repository
- Check existing documentation
- Review application logs for error details
Note: This application is designed for educational and development purposes. For production use, ensure proper security auditing and testing.