This repository contains a Flask-based user authentication service with SQLAlchemy as the ORM and bcrypt for password hashing. Below is an overview of each task implemented:
alx-backend-user-data/
└── 0x03-user_authentication_service/
├── app.py # Flask application with all routes
├── auth.py # Auth class with core authentication logic
├── db.py # Database interaction class
├── user.py # User model definition
├── main.py # Integration test script
└── README.md # Project documentation
-
User Management
- Secure user registration with email/password
- Password hashing using bcrypt
- Unique email validation
-
Session Management
- Session creation with UUID tokens
- Session validation middleware
- Secure logout functionality
-
Authentication Flow
- Login with email/password
- Protected routes requiring valid sessions
- Profile access control
-
Password Recovery
- Reset token generation
- Secure password update flow
- Token invalidation after use
-
Database Integration
- SQLAlchemy ORM for database operations
- SQLite database (can be configured for other DBMS)
- User model with all required fields
- Backend Framework: Flask
- Database ORM: SQLAlchemy
- Password Hashing: bcrypt
- Session Management: UUID tokens
- Testing: Python unittest via integration tests
| Endpoint | Method | Description |
|---|---|---|
| / | GET | Welcome message |
| /users | POST | Register new user |
| /sessions | POST | User login |
| /sessions | DELETE | User logout |
| /profile | GET | Get user profile |
| /reset_password | POST | Request password reset token |
| /reset_password | PUT | Update password with reset token |
- All passwords are hashed with bcrypt before storage
- Session tokens are randomly generated UUIDs
- No sensitive data exposed in API responses
- Proper error handling for invalid requests
- CSRF protection via session tokens
-
Setup:
pip install -r requirements.txt
-
Run the server:
python app.py
-
Run tests:
python main.py
-
Register a user:
curl -XPOST localhost:5000/users -d 'email=test@example.com' -d 'password=secure123'
-
Login:
curl -XPOST localhost:5000/sessions -d 'email=test@example.com' -d 'password=secure123' -v
-
Access profile:
curl -XGET localhost:5000/profile -b "session_id=<your_session_id>" -
Reset password:
# Request token curl -XPOST localhost:5000/reset_password -d 'email=test@example.com' # Update password curl -XPUT localhost:5000/reset_password -d 'email=test@example.com' -d 'reset_token=<token>' -d 'new_password=newsecure123'
This service provides a complete authentication solution that can be integrated into larger applications or used as a reference implementation for Flask-based authentication systems.
- Created a SQLAlchemy model named
Userfor a database table namedusers - Attributes:
id: integer primary keyemail: non-nullable stringhashed_password: non-nullable stringsession_id: nullable stringreset_token: nullable string
- Implemented
add_usermethod in DB class - Takes email and hashed_password as arguments
- Saves user to database and returns User object
- Implemented
find_user_bymethod in DB class - Takes arbitrary keyword arguments to filter users
- Raises
NoResultFoundif no user found - Raises
InvalidRequestErrorfor invalid query arguments
- Implemented
update_usermethod in DB class - Takes user_id and arbitrary keyword arguments for updates
- Raises ValueError if invalid user attribute is passed
- Implemented
_hash_passwordmethod - Takes password string, returns salted hash as bytes
- Uses bcrypt.hashpw for hashing
- Implemented
register_userin Auth class - Takes email and password, hashes password
- Raises ValueError if user already exists
- Returns created User object
- Created basic Flask app with single GET route "/"
- Returns JSON:
{"message": "Bienvenue"}
- Implemented POST /users route
- Registers new user with email and password
- Returns 400 if email already registered
- Implemented
valid_loginmethod in Auth class - Checks email and password against database
- Returns True if valid, False otherwise
- Implemented
_generate_uuidhelper function - Returns string representation of new UUID
- Implemented
create_sessionmethod in Auth class - Generates session ID for user and stores in database
- Returns session ID string
- Implemented POST /sessions route
- Validates login credentials
- Sets session_id cookie on successful login
- Returns 401 for invalid credentials
- Implemented
get_user_from_session_idmethod - Returns User object for valid session ID
- Returns None for invalid/expired sessions
- Implemented
destroy_sessionmethod - Updates user's session_id to None
- Implemented DELETE /sessions route
- Destroys session based on session_id cookie
- Redirects to home page or returns 403
- Implemented GET /profile route
- Returns user email for valid session
- Returns 403 for invalid session
- Implemented
get_reset_password_tokenmethod - Generates and stores reset token for user
- Raises ValueError for invalid email
- Implemented POST /reset_password route
- Generates reset token for valid email
- Returns 403 for invalid email
- Implemented
update_passwordmethod - Updates password using reset token
- Raises ValueError for invalid token
- Implemented PUT /reset_password route
- Updates password with email, token and new password
- Returns 403 for invalid token
- Created test script that exercises all endpoints
- Tests registration, login, profile access, logout, and password reset
- Uses assertions to validate responses
The service provides a complete authentication flow with user registration, session management, and password reset functionality.