File size: 11,023 Bytes
479644c e627d25 479644c e627d25 479644c e627d25 479644c e627d25 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 |
---
title: Flask Login
emoji: ๐ป
colorFrom: green
colorTo: indigo
sdk: docker
pinned: true
license: mit
short_description: A simple yet comprehensive Flask-based user authentication.
---
Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
---
# Flask Login System ๐
A simple yet comprehensive Flask-based user authentication system with SQLite database integration, featuring user registration, login, session management, and "Remember Me" functionality.
**Live Demo:** [https://rahul23232-flask-login.hf.space/](https://rahul23232-flask-login.hf.space/)
## ๐ Table of Contents
- [Features](#features)
- [Technologies Used](#technologies-used)
- [Installation](#installation)
- [Usage](#usage)
- [Project Structure](#project-structure)
- [API Routes](#api-routes)
- [Database Schema](#database-schema)
- [Security Considerations](#security-considerations)
- [Contributing](#contributing)
- [License](#license)
## โจ Features
- **User Registration**: Create new user accounts with unique usernames
- **User Authentication**: Secure login system with credential verification
- **Session Management**: Server-side session handling for user state
- **Remember Me**: Optional persistent login that survives browser restarts
- **Cookie Management**: Last visit tracking with customizable expiration
- **SQLite Integration**: Lightweight database for user storage
- **Responsive Design**: Clean, user-friendly interface
- **Error Handling**: Proper validation and error messages
## ๐ ๏ธ Technologies Used
- **Backend**: Python 3.x, Flask
- **Database**: SQLite3
- **Frontend**: HTML, CSS (Bootstrap-compatible)
- **Session Management**: Flask Sessions
- **Deployment**: Hugging Face Spaces
## ๐ฆ Installation
### Prerequisites
- Python 3.7 or higher
- pip (Python package installer)
### Local Setup
1. **Clone the repository**
```bash
git clone https://github.com/yourusername/flask-login-system.git
cd flask-login-system
```
2. **Install dependencies**
```bash
pip install flask
```
3. **Run the application**
```bash
python app.py
```
4. **Access the application**
- Open your browser and navigate to `http://localhost:5000`
### Docker Setup (for Hugging Face Spaces)
The project includes Docker configuration for deployment on Hugging Face Spaces:
```dockerfile
FROM python:3.9-slim
WORKDIR /app
COPY requirements.txt .
RUN pip install -r requirements.txt
COPY . .
EXPOSE 7860
CMD ["python", "app.py"]
```
## ๐ฏ Usage
### Getting Started
1. **Access the Application**: Navigate to the home URL
2. **Create Account**: Click "Sign Up" to create a new user account
3. **Login**: Use your credentials to log in
4. **Remember Me**: Check the "Remember Me" option to stay logged in
5. **Logout**: Click "Logout" to end your session
### User Flow
```mermaid
graph TD
A[Visit Homepage] --> B{User Logged In?}
B -->|No| C[Redirect to Login]
B -->|Yes| D[Show Dashboard]
C --> E[Login Form]
E --> F[Submit Credentials]
F --> G{Valid Credentials?}
G -->|No| H[Show Error]
G -->|Yes| I[Create Session]
I --> J{Remember Me?}
J -->|Yes| K[Set Permanent Session]
J -->|No| L[Set Temporary Session]
K --> D
L --> D
D --> M[Logout Option]
M --> N[Clear Session & Cookies]
N --> C
```
## ๐ Project Structure
```
flask-login-system/
โโโ app.py # Main Flask application
โโโ templates/ # HTML templates
โ โโโ base.html # Base template
โ โโโ login.html # Login page
โ โโโ signup.html # Registration page
โ โโโ home.html # Dashboard/home page
โโโ static/ # Static files (CSS, JS, images)
โ โโโ style.css # Custom styles
โโโ users.db # SQLite database (created automatically)
โโโ requirements.txt # Python dependencies
โโโ Dockerfile # Docker configuration
โโโ README.md # Project documentation
โโโ .gitignore # Git ignore rules
```
## ๐ฃ๏ธ API Routes
### Public Routes
| Route | Method | Description | Parameters |
|-------|---------|-------------|------------|
| `/login` | GET, POST | User login page | `username`, `password`, `remember` |
| `/signup` | GET, POST | User registration | `username`, `password` |
### Protected Routes
| Route | Method | Description | Authentication Required |
|-------|---------|-------------|------------------------|
| `/` | GET | Homepage/Dashboard | Yes |
| `/logout` | GET | User logout | Yes |
### Route Details
#### `/` (Homepage)
- **Method**: GET
- **Authentication**: Required
- **Description**: Main dashboard showing welcome message and last visit info
- **Response**: Redirects to login if not authenticated
#### `/signup` (Registration)
- **Methods**: GET, POST
- **Parameters**:
- `username` (string): Unique username
- `password` (string): User password
- **Validation**: Username must be unique
- **Response**: Redirects to login on success
#### `/login` (Authentication)
- **Methods**: GET, POST
- **Parameters**:
- `username` (string): User's username
- `password` (string): User's password
- `remember` (checkbox): Optional "Remember Me"
- **Response**: Redirects to homepage on success
#### `/logout` (Session Termination)
- **Method**: GET
- **Description**: Clears session and cookies
- **Response**: Redirects to login page
## ๐๏ธ Database Schema
### Users Table
```sql
CREATE TABLE users (
id INTEGER PRIMARY KEY AUTOINCREMENT,
username TEXT UNIQUE NOT NULL,
password TEXT NOT NULL
);
```
| Column | Type | Constraints | Description |
|--------|------|-------------|-------------|
| `id` | INTEGER | PRIMARY KEY, AUTOINCREMENT | Unique user identifier |
| `username` | TEXT | UNIQUE, NOT NULL | User's login name |
| `password` | TEXT | NOT NULL | User's password (plain text) |
### Database Operations
- **Connection**: SQLite3 with `sqlite3.Row` factory for dictionary-like access
- **Initialization**: Automatic table creation on first run
- **Queries**: Parameterized queries to prevent SQL injection
## ๐ Security Considerations
### Current Implementation
- โ
SQL injection protection via parameterized queries
- โ
Session-based authentication
- โ
CSRF protection through Flask's secret key
- โ
Input validation and error handling
### Production Recommendations
- โ ๏ธ **Password Hashing**: Currently stores plain text passwords
```python
from werkzeug.security import generate_password_hash, check_password_hash
# For registration
hashed_password = generate_password_hash(password)
# For login verification
check_password_hash(stored_hash, provided_password)
```
- โ ๏ธ **Environment Variables**: Move secret key to environment variables
```python
import os
app.secret_key = os.environ.get('SECRET_KEY', 'fallback-secret-key')
```
- โ ๏ธ **HTTPS**: Enable HTTPS in production
- โ ๏ธ **Rate Limiting**: Implement login attempt limits
- โ ๏ธ **Input Validation**: Add comprehensive input sanitization
- โ ๏ธ **Session Security**: Configure secure session cookies
### Recommended Security Enhancements
```python
# Enhanced security configuration
app.config.update(
SESSION_COOKIE_SECURE=True, # HTTPS only
SESSION_COOKIE_HTTPONLY=True, # No JS access
SESSION_COOKIE_SAMESITE='Lax', # CSRF protection
PERMANENT_SESSION_LIFETIME=timedelta(hours=1) # Shorter sessions
)
```
## ๐จ Frontend Templates
### Template Structure
All templates extend `base.html` for consistent styling:
```html
<!-- base.html -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>{% block title %}Flask Login System{% endblock %}</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<div class="container mt-4">
{% block content %}{% endblock %}
</div>
</body>
</html>
```
### Form Examples
#### Login Form
```html
<form method="POST">
<div class="mb-3">
<label for="username" class="form-label">Username</label>
<input type="text" class="form-control" name="username" required>
</div>
<div class="mb-3">
<label for="password" class="form-label">Password</label>
<input type="password" class="form-control" name="password" required>
</div>
<div class="mb-3 form-check">
<input type="checkbox" class="form-check-input" name="remember">
<label class="form-check-label">Remember Me</label>
</div>
<button type="submit" class="btn btn-primary">Login</button>
</form>
```
## ๐ Deployment
### Hugging Face Spaces
The project is configured for deployment on Hugging Face Spaces:
1. **Create Space**: Create a new Space on Hugging Face
2. **Upload Files**: Push your code to the Space repository
3. **Configuration**: Ensure `app.py` runs on port 7860
4. **Environment**: The Space will automatically build and deploy
### Local Development
```bash
# Development mode with auto-reload
export FLASK_ENV=development
export FLASK_DEBUG=1
python app.py
```
### Production Deployment
```bash
# Use a production WSGI server
pip install gunicorn
gunicorn -w 4 -b 0.0.0.0:5000 app:app
```
## ๐ค Contributing
1. Fork the repository
2. Create a feature branch (`git checkout -b feature/amazing-feature`)
3. Commit your changes (`git commit -m 'Add amazing feature'`)
4. Push to the branch (`git push origin feature/amazing-feature`)
5. Open a Pull Request
### Development Guidelines
- Follow PEP 8 style guidelines
- Add comments for complex logic
- Update documentation for new features
- Test all functionality before submitting
## ๐ License
This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.
## ๐ Known Issues
- Plain text password storage (security concern)
- No password strength validation
- No account recovery mechanism
- Limited input sanitization
## ๐ฎ Future Enhancements
- [ ] Password hashing with bcrypt/scrypt
- [ ] Email verification system
- [ ] Password reset functionality
- [ ] User profile management
- [ ] Role-based access control
- [ ] OAuth integration (Google, GitHub)
- [ ] Rate limiting and brute force protection
- [ ] Advanced session management
- [ ] API endpoints for mobile apps
- [ ] Unit and integration tests
## ๐ Support
For questions, issues, or contributions:
- **Repository**: [GitHub Repository](https://github.com/yourusername/flask-login-system)
- **Live Demo**: [Flask Login System](https://rahul23232-flask-login.hf.space/)
- **Issues**: Use GitHub Issues for bug reports and feature requests
---
**Note**: This is a demonstration project for educational purposes. For production use, implement proper security measures including password hashing, HTTPS, and comprehensive input validation. |