Skip to content
Closed
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 16 additions & 0 deletions requirements.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
# Web Framework and Authentication
Flask==3.0.0
Flask-Login==0.6.3
Flask-WTF==1.2.1
Flask-SQLAlchemy==3.1.1
Flask-Migrate==4.0.5
Werkzeug==3.0.1
WTForms==3.1.1

# Security
bcrypt==4.1.2
PyJWT==2.8.0

# Testing
pytest==7.4.3
pytest-flask==1.3.0
240 changes: 240 additions & 0 deletions src/frontend/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,240 @@
# Frontend Infrastructure for Role & Authentication

This module provides a comprehensive frontend infrastructure with role-based authentication for the SDLC Core system.

## Features

### πŸ” Authentication System
- **User Registration & Login**: Secure user account creation and authentication
- **Password Security**: Bcrypt password hashing for security
- **Session Management**: Flask-Login for session handling
- **CSRF Protection**: Built-in CSRF protection for forms

### πŸ‘₯ Role-Based Access Control (RBAC)
- **Flexible Role System**: Support for multiple user roles
- **Role Decorators**: Easy-to-use decorators for protecting routes
- **Default Roles**: Pre-configured roles (admin, user, moderator, analyst, developer)
- **Dynamic Permissions**: Runtime role checking and permission enforcement

### 🌐 Web Interface
- **Responsive Design**: Bootstrap 5 responsive web interface
- **Modern UI**: Clean, professional interface with icons and animations
- **Dashboard**: User dashboard with profile information
- **Admin Panel**: Comprehensive admin interface for user/role management

### πŸ”Œ API Endpoints
- **RESTful API**: JSON API endpoints for authentication
- **User Profile API**: Programmatic access to user information
- **Admin API**: Administrative endpoints for user management
- **Error Handling**: Consistent error responses with proper HTTP status codes

## Quick Start

### 1. Install Dependencies
```bash
pip install -r requirements.txt
```

### 2. Run the Application
```bash
cd src/frontend
python app.py
```

### 3. Access the Application
- **Home**: http://localhost:5000/
- **Login**: http://localhost:5000/auth/login
- **Register**: http://localhost:5000/auth/register
- **Admin Panel**: http://localhost:5000/admin (admin role required)

### 4. Default Admin Account
- **Username**: admin
- **Password**: admin123
- ⚠️ **Important**: Change the admin password after first login!

## Architecture

### Models
- **User**: Core user model with authentication capabilities
- **Role**: Role definition with description
- **UserRole**: Many-to-many relationship between users and roles

### Views
- **Authentication Routes**: Login, register, logout, unauthorized
- **Main Routes**: Index, dashboard, admin panel
- **API Routes**: JSON endpoints for programmatic access

### Security Features
- **Password Hashing**: Secure bcrypt password storage
- **Session Security**: Secure session management with Flask-Login
- **CSRF Protection**: Built-in CSRF token validation
- **Role Validation**: Server-side role validation for all protected routes

## API Reference

### Authentication Endpoints

#### POST /auth/api/login
Login a user and return user information.

**Request:**
```json
{
"username": "string",
"password": "string"
}
```

**Response:**
```json
{
"message": "Login successful",
"user": {
"id": 1,
"username": "string",
"email": "string",
"roles": ["role1", "role2"]
}
}
```

#### GET /auth/api/user/profile
Get current user profile (requires authentication).

**Response:**
```json
{
"user": {
"id": 1,
"username": "string",
"email": "string",
"roles": ["role1", "role2"],
"is_active": true,
"created_at": "2024-01-01T00:00:00",
"last_login": "2024-01-01T00:00:00"
}
}
```

### Admin Endpoints

#### GET /api/admin/users
Get all users (admin only).

#### GET /api/admin/roles
Get all roles (admin only).

## Role System

### Default Roles
- **admin**: Full system administrator access
- **user**: Standard user access
- **moderator**: Content moderation access
- **analyst**: Data analysis and reporting access
- **developer**: Development and API access

### Using Role Decorators

```python
from frontend.decorators import require_role, admin_required, login_required

@require_role('admin')
def admin_only_view():
return "Admin content"

@admin_required
def another_admin_view():
return "Also admin content"

@login_required
def authenticated_view():
return "Requires login"
```

### Checking Roles in Templates
```html
{% if current_user.has_role('admin') %}
<a href="/admin">Admin Panel</a>
{% endif %}
```

## Configuration

### Environment Variables
- **SECRET_KEY**: Flask secret key for sessions (required in production)
- **DATABASE_URL**: Database connection string (default: SQLite)
- **FLASK_ENV**: Environment setting (development/production)
- **PORT**: Port to run on (default: 5000)

### Database
The system uses SQLAlchemy with support for multiple database backends:
- **SQLite**: Default, good for development
- **PostgreSQL**: Recommended for production
- **MySQL**: Also supported

## Testing

Run the test suite:
```bash
pytest test/unit/frontend/
```

Tests cover:
- User model functionality
- Role system
- Authentication flows
- API endpoints
- Access control

## Security Considerations

### Production Deployment
1. **Change Default Credentials**: Update admin password immediately
2. **Set SECRET_KEY**: Use a secure, random secret key
3. **Use HTTPS**: Always use HTTPS in production
4. **Database Security**: Use a production database with proper credentials
5. **Environment Variables**: Store sensitive config in environment variables

### Best Practices
- Regular password updates
- Monitor failed login attempts
- Audit user roles and permissions
- Keep dependencies updated
- Use secure session settings

## File Structure

```
src/frontend/
β”œβ”€β”€ __init__.py # Module initialization
β”œβ”€β”€ app.py # Application entry point
β”œβ”€β”€ auth.py # Authentication routes and app factory
β”œβ”€β”€ models.py # Database models
β”œβ”€β”€ forms.py # WTForms form definitions
β”œβ”€β”€ decorators.py # Authentication decorators
β”œβ”€β”€ static/
β”‚ β”œβ”€β”€ css/
β”‚ β”‚ └── style.css # Custom styles
β”‚ └── js/
β”‚ └── app.js # Frontend JavaScript
└── templates/
β”œβ”€β”€ base.html # Base template
β”œβ”€β”€ index.html # Home page
β”œβ”€β”€ dashboard.html # User dashboard
β”œβ”€β”€ admin.html # Admin panel
└── auth/
β”œβ”€β”€ login.html # Login form
β”œβ”€β”€ register.html # Registration form
└── unauthorized.html # Access denied page
```

## Contributing

1. Follow the existing code style
2. Add tests for new features
3. Update documentation for changes
4. Ensure security best practices

## License

This project is part of the SDLC Core system. See the main project license for details.
14 changes: 14 additions & 0 deletions src/frontend/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
# Frontend Infrastructure Module
from .auth import create_app, auth_bp, main_bp
from .models import db, User, Role, UserRole, init_default_roles
from .decorators import require_role, login_required, admin_required, require_any_role
from .forms import LoginForm, RegisterForm, ChangePasswordForm, UserEditForm, RoleAssignmentForm

__all__ = [
'create_app', 'auth_bp', 'main_bp', 'db',
'User', 'Role', 'UserRole', 'init_default_roles',
'require_role', 'login_required', 'admin_required', 'require_any_role',
'LoginForm', 'RegisterForm', 'ChangePasswordForm', 'UserEditForm', 'RoleAssignmentForm'
]

__version__ = '1.0.0'
98 changes: 98 additions & 0 deletions src/frontend/app.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,98 @@
#!/usr/bin/env python3
"""
SDLC Core Frontend Application Entry Point

This script starts the Flask web application with authentication and role management.
"""
import os
import sys
from pathlib import Path

# Add the src directory to the Python path
src_path = Path(__file__).parent.parent
sys.path.insert(0, str(src_path))

from frontend.auth import create_app
from frontend.models import db, User, Role, UserRole, init_default_roles


def create_admin_user(app):
"""Create a default admin user if none exists."""
with app.app_context():
admin_user = User.query.filter_by(username='admin').first()
if not admin_user:
admin_role = Role.query.filter_by(name='admin').first()
if admin_role:
admin_user = User(
username='admin',
email='admin@sdlccore.com'
)
admin_user.set_password('admin123') # Change this in production!
db.session.add(admin_user)
db.session.flush() # Get user ID before adding role

user_role = UserRole(user_id=admin_user.id, role_id=admin_role.id)
db.session.add(user_role)
db.session.commit()
print("βœ“ Default admin user created (username: admin, password: admin123)")
else:
print("βœ— Admin role not found. Cannot create admin user.")
else:
print("βœ“ Admin user already exists")


def main():
"""Main entry point for the application."""
print("πŸš€ Starting SDLC Core Frontend Infrastructure...")

# Set environment variables if not set
if not os.getenv('SECRET_KEY'):
os.environ['SECRET_KEY'] = 'dev-secret-key-change-in-production'
print("⚠️ Using default SECRET_KEY. Change in production!")

if not os.getenv('DATABASE_URL'):
db_path = Path(__file__).parent / 'sdlc_core.db'
os.environ['DATABASE_URL'] = f'sqlite:///{db_path.absolute()}'
print(f"πŸ“ Using SQLite database: {db_path.absolute()}")

# Create the Flask app
app = create_app()

# Create admin user
create_admin_user(app)

# Print available routes
print("\nπŸ“‹ Available Routes:")
with app.app_context():
for rule in app.url_map.iter_rules():
methods = ','.join(rule.methods - {'HEAD', 'OPTIONS'})
print(f" {rule.endpoint:30} {methods:10} {rule.rule}")

print("\n🌐 Frontend Infrastructure Setup Complete!")
print(" β€’ Role-based authentication system βœ“")
print(" β€’ User management interface βœ“")
print(" β€’ Admin panel βœ“")
print(" β€’ REST API endpoints βœ“")
print(" β€’ Responsive web interface βœ“")

print(f"\nπŸ”— Access the application at: http://localhost:5000")
print(" β€’ Home: http://localhost:5000/")
print(" β€’ Login: http://localhost:5000/auth/login")
print(" β€’ Register: http://localhost:5000/auth/register")
print(" β€’ Admin: http://localhost:5000/admin (admin role required)")

print("\nπŸ”‘ Default Admin Credentials:")
print(" Username: admin")
print(" Password: admin123")
print(" ⚠️ Please change the admin password after first login!")

# Run the application
debug = os.getenv('FLASK_ENV') == 'development'
port = int(os.getenv('PORT', 5000))

print(f"\nπŸƒ Running on port {port} (debug={'on' if debug else 'off'})")
app.run(host='0.0.0.0', port=port, debug=debug)


if __name__ == '__main__':
main()
Loading
Loading