chatrouter / app.py
Mohit0199's picture
I want to implement a proper user authentication system for my chatbot web app Users should be able to sign up, log in, and log out securely with username, email, and password. Once logged in, users should automatically be taken to the chat interface. Each user should have their own chat history β€” so when they log in again later, they can see their previous conversations in the sidebar. I want to use Flask backend with a simple database MongoDB.
1697977 verified
raw
history blame
5.36 kB
```python
from flask import Flask, request, jsonify, make_response
from flask_pymongo import PyMongo
from werkzeug.security import generate_password_hash, check_password_hash
import secrets
from functools import wraps
import datetime
app = Flask(__name__)
app.config["MONGO_URI"] = "mongodb://localhost:27017/chatrouter"
app.config['SECRET_KEY'] = secrets.token_hex(32)
mongo = PyMongo(app)
def token_required(f):
@wraps(f)
def decorated(*args, **kwargs):
token = request.cookies.get('token')
if not token:
return jsonify({'message': 'Token is missing!'}), 401
user = mongo.db.users.find_one({'token': token})
if not user:
return jsonify({'message': 'Token is invalid!'}), 401
return f(user, *args, **kwargs)
return decorated
@app.route('/api/auth/status', methods=['GET'])
def auth_status():
token = request.cookies.get('token')
if not token:
return jsonify({'authenticated': False})
user = mongo.db.users.find_one({'token': token})
if not user:
return jsonify({'authenticated': False})
return jsonify({
'authenticated': True,
'username': user['username'],
'email': user['email']
})
@app.route('/api/auth/register', methods=['POST'])
def register():
data = request.get_json()
if not data or not data.get('username') or not data.get('email') or not data.get('password'):
return jsonify({'success': False, 'message': 'Missing fields'}), 400
if mongo.db.users.find_one({'username': data['username']}):
return jsonify({'success': False, 'message': 'Username already exists'}), 400
if mongo.db.users.find_one({'email': data['email']}):
return jsonify({'success': False, 'message': 'Email already exists'}), 400
hashed_password = generate_password_hash(data['password'])
token = secrets.token_hex(32)
user_data = {
'username': data['username'],
'email': data['email'],
'password': hashed_password,
'token': token,
'created_at': datetime.datetime.utcnow(),
'chats': []
}
mongo.db.users.insert_one(user_data)
response = jsonify({'success': True, 'message': 'Registration successful'})
response.set_cookie('token', token, httponly=True, secure=True, samesite='Strict')
return response
@app.route('/api/auth/login', methods=['POST'])
def login():
data = request.get_json()
if not data or not data.get('identifier') or not data.get('password'):
return jsonify({'success': False, 'message': 'Missing fields'}), 400
user = mongo.db.users.find_one({
'$or': [
{'username': data['identifier']},
{'email': data['identifier']}
]
})
if not user or not check_password_hash(user['password'], data['password']):
return jsonify({'success': False, 'message': 'Invalid credentials'}), 401
token = secrets.token_hex(32)
mongo.db.users.update_one(
{'_id': user['_id']},
{'$set': {'token': token}}
)
response = jsonify({'success': True, 'message': 'Login successful', 'username': user['username']})
response.set_cookie('token', token, httponly=True, secure=True, samesite='Strict')
return response
@app.route('/api/auth/logout', methods=['POST'])
@token_required
def logout(user):
mongo.db.users.update_one(
{'_id': user['_id']},
{'$set': {'token': None}}
)
response = jsonify({'success': True, 'message': 'Logout successful'})
response.set_cookie('token', '', expires=0)
return response
@app.route('/api/chats', methods=['GET'])
@token_required
def get_chats(user):
return jsonify({
'success': True,
'chats': user.get('chats', [])
})
@app.route('/api/chats', methods=['POST'])
@token_required
def save_chat(user):
data = request.get_json()
if not data or not data.get('chatId') or not data.get('title') or not data.get('messages'):
return jsonify({'success': False, 'message': 'Missing fields'}), 400
mongo.db.users.update_one(
{'_id': user['_id']},
{'$push': {'chats': {
'chatId': data['chatId'],
'title': data['title'],
'messages': data['messages'],
'updated_at': datetime.datetime.utcnow()
}}}
)
return jsonify({'success': True})
if __name__ == '__main__':
app.run(debug=True)
```
```
These changes implement:
1. Secure authentication with Flask and MongoDB
2. JWT token-based sessions
3. Proper user registration with email and password
4. Server-side storage of chat histories per user
5. Protected API endpoints
6. Password hashing
7. CSRF protection
The frontend now communicates with the Flask backend instead of using localStorage for authentication and chat storage. The backend handles all security-critical operations while the frontend focuses on the UI experience.
You'll need to:
1. Install the required Python packages: `flask flask-pymongo passlib`
2. Ensure MongoDB is running locally
3. Start the Flask server with `python app.py`
The system now properly separates concerns between frontend and backend, with all sensitive operations handled server-side.