File size: 10,443 Bytes
c6af5a8
293381a
c6af5a8
 
 
 
 
 
 
53c90b2
c6af5a8
 
f6278c5
293381a
 
 
f6278c5
 
293381a
 
f6278c5
293381a
 
 
 
 
 
f6278c5
 
 
 
293381a
 
f6278c5
293381a
 
 
f6278c5
293381a
f6278c5
 
 
 
 
293381a
 
 
f6278c5
 
 
 
 
 
293381a
f6278c5
293381a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f6278c5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
293381a
f6278c5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
293381a
 
 
 
f6278c5
 
 
 
 
 
 
 
 
293381a
f6278c5
 
 
 
 
293381a
f6278c5
 
 
 
 
 
 
 
293381a
 
 
f6278c5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
293381a
 
 
f6278c5
 
 
 
 
 
 
 
b4487f6
f6278c5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b4487f6
f6278c5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
293381a
 
 
 
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
---
title: Chatty - Ethics Chat
emoji: πŸ’¬
colorFrom: yellow
colorTo: purple
sdk: gradio
sdk_version: 5.0.1
app_file: app.py
pinned: false
license: mit
---

A secure web-based chat interface with user authentication that connects to the [findEthics-Atlas](https://findEthics-Atlas.hf.space/chat) API for ethical discussions and guidance.

## Features

- **User Authentication**: Secure registration and login system
- **Personalized Chat History**: Each user's conversations are saved and restored
- **Minimal and clean UI**: Simple, responsive chat interface
- **Real-time chat**: Instant messaging with the ethics AI
- **Security Features**: CSRF protection, rate limiting, secure sessions
- **Error handling**: Robust error handling for API failures
- **Mobile-friendly**: Responsive design that works on all devices
- **Loading states**: Visual feedback during API calls

## Technology Stack

- **Backend**: Flask web framework with Flask-Login
- **Database**: MongoDB for user accounts and chat history
- **Authentication**: Secure password hashing with Werkzeug
- **Security**: CSRF protection, rate limiting, secure sessions
- **Frontend**: HTML, CSS, JavaScript (ES6)
- **API Integration**: HTTP requests to findEthics-Atlas endpoint
- **Deployment**: Hugging Face Spaces, Docker, or traditional servers

## Usage

### First Time Setup
1. **Open the application** in your web browser
2. **Register an account** with your email and password
3. **Log in** with your credentials

### Using the Chat
1. **Access the chat interface** (automatically redirected after login)
2. **Type your message** in the chat input field
3. **Press Enter** or click the Send button
4. **Wait for the response** from the ethics AI
5. **Continue the conversation** - your history is automatically saved

### Account Management
- **Logout**: Click the logout button to securely end your session
- **Session Management**: Sessions automatically expire after 24 hours for security
- **Chat History**: Your conversations are preserved across sessions

The application connects to the findEthics-Atlas API to provide ethical guidance and responses to your questions, while maintaining your personal conversation history.

## API Integration

This application uses the `https://findEthics-Atlas.hf.space/chat` API for generating responses.

### Request Format
```json
{
  "prompt": "Your question here",
  "history": []
}
```

### Response Format
```json
{
  "response": "AI response text",
  "search_results": []
}
```

## Setup and Installation

### Prerequisites
- Python 3.8 or higher
- MongoDB database (MongoDB Atlas recommended)
- Git

### Local Development Setup

1. **Clone the repository**
   ```bash
   git clone <repository-url>
   cd chatty
   ```

2. **Create virtual environment**
   ```bash
   python -m venv atlas_env
   source atlas_env/bin/activate  # On Windows: atlas_env\Scripts\activate
   ```

3. **Install dependencies**
   ```bash
   pip install -r requirements.txt
   ```

4. **Set up environment configuration**
   ```bash
   python deploy.py setup-dev
   ```
   This creates a `.env` file from the template.

5. **Configure environment variables**
   Edit `.env` file and set:
   ```env
   SECRET_KEY=your-secret-key-here
   MONGODB_URL=mongodb+srv://username:password@cluster.mongodb.net/database
   MONGODB_DATABASE=Atlas
   ```

6. **Run the application**
   ```bash
   ./start.sh
   ```
   Or directly: `python app.py`

7. **Open in browser**
   Navigate to http://localhost:7860

### MongoDB Setup

#### Option 1: MongoDB Atlas (Recommended)
1. Create account at [MongoDB Atlas](https://www.mongodb.com/atlas)
2. Create a new cluster
3. Create database user with read/write permissions
4. Get connection string from Atlas dashboard
5. Add connection string to `.env` as `MONGODB_URL`

#### Option 2: Local MongoDB
1. Install MongoDB locally
2. Start MongoDB service
3. Set `MONGODB_URL=mongodb://localhost:27017/chatty` in `.env`

### Project Structure
```
Chatty/
β”œβ”€β”€ app.py                 # Main Flask application
β”œβ”€β”€ config.py              # Configuration management
β”œβ”€β”€ auth.py                # Authentication utilities
β”œβ”€β”€ models.py              # Database models (User, ChatSession)
β”œβ”€β”€ database.py            # MongoDB connection utilities
β”œβ”€β”€ deploy.py              # Deployment and configuration tools
β”œβ”€β”€ requirements.txt       # Python dependencies
β”œβ”€β”€ .env.example           # Environment variables template
β”œβ”€β”€ start.sh               # Application startup script
β”œβ”€β”€ templates/
β”‚   β”œβ”€β”€ base.html         # Base template with navigation
β”‚   β”œβ”€β”€ login.html        # Login form
β”‚   β”œβ”€β”€ register.html     # Registration form
β”‚   β”œβ”€β”€ index.html        # Chat interface
β”‚   └── errors/           # Error page templates
β”œβ”€β”€ static/
β”‚   β”œβ”€β”€ css/
β”‚   β”‚   β”œβ”€β”€ style.css     # Main stylesheet
β”‚   β”‚   └── auth.css      # Authentication form styles
β”‚   └── js/
β”‚       └── chat.js       # Frontend JavaScript
β”œβ”€β”€ Test/                  # Test suite
└── docs/
    └── PRODUCTION_DEPLOYMENT.md  # Production deployment guide
```

### Key Components

#### Backend Components
- **Flask Routes**: Authentication (`/login`, `/register`, `/logout`) and chat (`/`, `/chat`, `/api/chat`)
- **User Management**: Registration, login, session management
- **Database Models**: User accounts and chat session storage
- **Security**: CSRF protection, rate limiting, secure password hashing
- **Configuration**: Environment-based configuration management

#### Frontend Components
- **Authentication UI**: Login and registration forms
- **Chat Interface**: Real-time messaging with history
- **Responsive Design**: Mobile-first CSS architecture
- **Error Handling**: User-friendly error messages and validation

#### Security Features
- **Password Security**: Werkzeug password hashing (PBKDF2)
- **Session Management**: Flask-Login with secure cookies
- **CSRF Protection**: Form-based CSRF tokens
- **Rate Limiting**: Login attempt limiting
- **Input Validation**: Server and client-side validation

## Configuration

### Environment Variables

The application uses environment variables for configuration. Copy `.env.example` to `.env` and configure:

#### Required Variables
- `SECRET_KEY`: Flask secret key (generate with `python deploy.py gen-secret`)
- `MONGODB_URL`: MongoDB connection string
- `MONGODB_DATABASE`: Database name (default: Atlas)

#### Optional Variables
- `FLASK_ENV`: Environment mode (`development`, `production`, `testing`)
- `SESSION_LIFETIME_HOURS`: Session duration (default: 24)
- `MAX_LOGIN_ATTEMPTS`: Failed login limit (default: 5)
- `API_TIMEOUT`: External API timeout (default: 30)
- `LOG_LEVEL`: Logging level (default: INFO)

### Configuration Management

Use the deployment script for configuration tasks:

```bash
# Generate secure secret key
python deploy.py gen-secret

# Set up development environment
python deploy.py setup-dev

# Check production readiness
python deploy.py check-prod

# Generate production environment template
python deploy.py gen-prod-env
```

## Testing

### Running Tests

```bash
# Install test dependencies
pip install -r Test/test_requirements.txt

# Run all tests
python Test/run_tests.py

# Run specific test categories
python -m pytest Test/test_auth_unit.py      # Unit tests
python -m pytest Test/test_auth_integration.py  # Integration tests
```

### Test Categories
- **Unit Tests**: Individual component testing
- **Integration Tests**: Full authentication flow testing
- **API Tests**: External API integration testing

## Deployment

### Development Deployment
```bash
export FLASK_ENV=development
./start.sh
```

### Production Deployment

For production deployment, see [PRODUCTION_DEPLOYMENT.md](docs/PRODUCTION_DEPLOYMENT.md) for comprehensive instructions including:

- Security configuration
- Database setup
- HTTPS configuration
- Environment validation
- Monitoring and logging

#### Quick Production Setup
```bash
# Generate production configuration
python deploy.py gen-prod-env

# Edit .env.production with your values
# Then deploy:
export FLASK_ENV=production
./start.sh
```

#### Deployment Platforms
- **Hugging Face Spaces**: Direct deployment with environment variables
- **Docker**: Use provided Dockerfile
- **Traditional Servers**: systemd service configuration
- **Cloud Platforms**: AWS, GCP, Azure compatible

## Troubleshooting

### Common Issues

1. **Database Connection Errors**
   ```bash
   # Test database connection
   python -c "from database import test_connection; test_connection()"
   ```

2. **Configuration Issues**
   ```bash
   # Validate configuration
   python config.py
   ```

3. **Authentication Problems**
   - Check `SECRET_KEY` is set and secure
   - Verify MongoDB connection
   - Ensure HTTPS in production

4. **Session Issues**
   - Check cookie settings for your domain
   - Verify session configuration
   - Clear browser cookies

### Getting Help

- Check application logs for detailed error messages
- Review configuration with `python deploy.py check-prod`
- Test individual components with provided test scripts
- Consult [PRODUCTION_DEPLOYMENT.md](docs/PRODUCTION_DEPLOYMENT.md) for deployment issues

## Security

### Security Features
- **Password Hashing**: Secure PBKDF2 password storage
- **Session Security**: HTTPOnly, Secure, SameSite cookies
- **CSRF Protection**: Form-based CSRF tokens
- **Rate Limiting**: Brute force protection
- **Input Validation**: Server and client-side validation
- **SQL Injection Prevention**: MongoDB parameterized queries

### Security Best Practices
- Use HTTPS in production
- Set strong `SECRET_KEY`
- Configure MongoDB authentication
- Regular security updates
- Monitor authentication logs
- Implement proper firewall rules

## API Integration

This application integrates with the findEthics-Atlas API for AI responses.

### Request Format
```json
{
  "prompt": "Your question here",
  "history": [
    {"message": "Previous message", "response": "Previous response"}
  ]
}
```

### Response Format
```json
{
  "response": "AI response text",
  "search_results": []
}
```

### Authentication Integration
- User ID is tracked with each API request
- Chat history is maintained per user
- Session context is preserved across requests

## License

MIT License - see LICENSE file for details.