* Add email OTP authentication system and private room management ## Authentication System - Implement email OTP-based authentication with User and OTPToken models - Add auth.py module with OTP generation, email sending, and session management - Create authentication endpoints: /auth/send-otp, /auth/verify-otp, /auth/claim-name, /auth/status, /auth/logout - Add authentication modal UI with email verification and display name claiming - Support SMTP configuration via environment variables (optional) ## Room Privacy & Ownership - Add is_private, is_archived, owner_id, and forked_from_id fields to Room model - Implement private rooms (single-user, owner-only access) - Add room forking: users can fork public rooms to public or private - Add room archive/delete endpoints (owner-only operations) - Implement access control for private room viewing ## UI Improvements - Add public/private room tabs in sidebar - Show authentication prompt in private rooms tab for non-authenticated users - Add room action buttons (fork, archive, delete) with proper permissions - Update homepage with statistics (public/private rooms, active users, active rooms) - Remove model/voice from URL query strings, use localStorage exclusively ## Database Migration - Create migration 2025011100 for User, OTPToken tables and Room model updates - Add indexes for email, display_name, is_private, is_archived, owner_id ## Breaking Changes - URL parameters now only include username (model/voice moved to localStorage) - Private rooms require authentication to access - Room creation can now require authentication (for private rooms) * Update README with authentication and private room documentation * Simplify README to be less verbose * Add missing session import to fix linter errors * Fix migration dependency to resolve multiple heads conflict * asdf * Fix SQLAlchemy auto-correlation error in homepage statistics query * Change tagline from AI-Powered to Machine Learning Powered * Add dedicated authentication page instead of modal - Create new /auth route with full-page authentication flow - Remove modal code from index.html - Update Sign in link to point to /auth page - Auth page has 4-step flow: email, OTP, display name, success - Better UX with gradient background and cleaner design * Fix migration: remove batch_alter_table to avoid circular dependency - Use op.add_column() directly instead of batch_alter_table() - Remove foreign key constraints (defined in models, not needed in migration) - User and OTPToken tables created by db.create_all() in make init-db - Fixes CircularDependencyError during migration * Fix migration: check if columns exist before adding - Use inspector to check existing columns and indexes - Only add columns/indexes if they don't already exist - Handles case where db.create_all() was run before migration - Fixes 'duplicate column name' error * Add profile page, room browsing, and updated_at timestamp Features: - Profile page with username change and dark/light mode settings - Browse page for discovering public and private rooms - Room updated_at timestamp (integer Unix epoch) that updates on new messages - Dynamic room tabs based on current room type (public/private) - Fork and delete room actions moved to right sidebar utility belt - Remove archive feature and success alerts from room actions Technical changes: - Add updated_at column to Room model (integer timestamp) - Add /profile route with authentication requirement - Add /browse route for room discovery - Add API endpoints for username availability check and update - Update room.updated_at on message creation in app.py:1189 - Wider right sidebar (25% instead of 15%) for better button layout - Profile link on homepage and browse page for authenticated users --------- Co-authored-by: Claude <noreply@anthropic.com> Co-authored-by: russell@unturf. <russell@unturf.com>
164 lines
6.2 KiB
Python
164 lines
6.2 KiB
Python
from flask_sqlalchemy import SQLAlchemy
|
|
from datetime import datetime, timedelta
|
|
|
|
import tiktoken
|
|
|
|
import json
|
|
|
|
db = SQLAlchemy()
|
|
|
|
|
|
class User(db.Model):
|
|
"""User model for authentication and ownership"""
|
|
id = db.Column(db.Integer, primary_key=True)
|
|
email = db.Column(db.String(255), unique=True, nullable=False, index=True)
|
|
display_name = db.Column(db.String(50), unique=True, nullable=False, index=True)
|
|
created_at = db.Column(db.DateTime, default=datetime.utcnow, nullable=False)
|
|
last_login = db.Column(db.DateTime, default=datetime.utcnow, nullable=False)
|
|
|
|
# Relationships
|
|
owned_rooms = db.relationship('Room', backref='owner', lazy='dynamic', foreign_keys='Room.owner_id')
|
|
|
|
def __repr__(self):
|
|
return f'<User {self.display_name} ({self.email})>'
|
|
|
|
|
|
class OTPToken(db.Model):
|
|
"""One-Time Password tokens for email authentication"""
|
|
id = db.Column(db.Integer, primary_key=True)
|
|
email = db.Column(db.String(255), nullable=False, index=True)
|
|
otp_code = db.Column(db.String(6), nullable=False)
|
|
created_at = db.Column(db.DateTime, default=datetime.utcnow, nullable=False)
|
|
expires_at = db.Column(db.DateTime, nullable=False)
|
|
used = db.Column(db.Boolean, default=False, nullable=False)
|
|
|
|
def __init__(self, email, otp_code, expiration_minutes=10):
|
|
self.email = email
|
|
self.otp_code = otp_code
|
|
self.created_at = datetime.utcnow()
|
|
self.expires_at = self.created_at + timedelta(minutes=expiration_minutes)
|
|
self.used = False
|
|
|
|
def is_valid(self):
|
|
"""Check if the OTP is still valid (not used and not expired)"""
|
|
return not self.used and datetime.utcnow() < self.expires_at
|
|
|
|
def __repr__(self):
|
|
return f'<OTPToken {self.email} expires_at={self.expires_at}>'
|
|
|
|
|
|
class Room(db.Model):
|
|
id = db.Column(db.Integer, primary_key=True)
|
|
name = db.Column(db.String(128), nullable=False, unique=True)
|
|
title = db.Column(db.String(128), nullable=True)
|
|
active_users = db.Column(db.Text, default="") # Store as a comma-separated string
|
|
inactive_users = db.Column(db.Text, default="") # Store as a comma-separated string
|
|
is_private = db.Column(db.Boolean, default=False, nullable=False, index=True)
|
|
is_archived = db.Column(db.Boolean, default=False, nullable=False, index=True)
|
|
owner_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=True, index=True)
|
|
created_at = db.Column(db.DateTime, default=datetime.utcnow, nullable=False)
|
|
updated_at = db.Column(db.Integer, default=lambda: int(datetime.utcnow().timestamp()), nullable=False)
|
|
forked_from_id = db.Column(db.Integer, db.ForeignKey('room.id'), nullable=True)
|
|
|
|
def add_user(self, username):
|
|
active_users = set(self.active_users.split(",")) if self.active_users else set()
|
|
inactive_users = (
|
|
set(self.inactive_users.split(",")) if self.inactive_users else set()
|
|
)
|
|
|
|
# Move from inactive to active if necessary
|
|
if username in inactive_users:
|
|
inactive_users.discard(username)
|
|
|
|
active_users.add(username)
|
|
self.active_users = ",".join(sorted(active_users))
|
|
self.inactive_users = ",".join(sorted(inactive_users))
|
|
|
|
def remove_user(self, username):
|
|
active_users = set(self.active_users.split(",")) if self.active_users else set()
|
|
inactive_users = (
|
|
set(self.inactive_users.split(",")) if self.inactive_users else set()
|
|
)
|
|
|
|
if username in active_users:
|
|
active_users.discard(username)
|
|
inactive_users.add(username) # Move to inactive users
|
|
|
|
self.active_users = ",".join(sorted(active_users))
|
|
self.inactive_users = ",".join(sorted(inactive_users))
|
|
|
|
def get_active_users(self):
|
|
return self.active_users.split(",") if self.active_users else []
|
|
|
|
def get_inactive_users(self):
|
|
return self.inactive_users.split(",") if self.inactive_users else []
|
|
|
|
|
|
class UserSession(db.Model):
|
|
id = db.Column(db.Integer, primary_key=True)
|
|
session_id = db.Column(db.String(128), unique=True, nullable=False)
|
|
username = db.Column(db.String(128))
|
|
room_name = db.Column(db.String(128))
|
|
room_id = db.Column(db.Integer)
|
|
|
|
|
|
class Message(db.Model):
|
|
id = db.Column(db.Integer, primary_key=True)
|
|
username = db.Column(db.String(128), nullable=False)
|
|
content = db.Column(db.String(1024), nullable=False)
|
|
token_count = db.Column(db.Integer)
|
|
room_id = db.Column(db.Integer, db.ForeignKey("room.id"), nullable=False)
|
|
|
|
def __init__(self, username, content, room_id):
|
|
self.username = username
|
|
self.content = content
|
|
self.room_id = room_id
|
|
self.count_tokens()
|
|
|
|
def count_tokens(self):
|
|
if self.token_count is None:
|
|
if self.is_base64_image():
|
|
self.token_count = 0
|
|
else:
|
|
encoding = tiktoken.encoding_for_model("gpt-4")
|
|
self.token_count = len(encoding.encode(self.content))
|
|
return self.token_count
|
|
|
|
def is_base64_image(self):
|
|
return (
|
|
'<img src="data:image/jpeg;base64,' in self.content
|
|
or '<img alt="Plot Image" src="data:image/png;base64,' in self.content
|
|
)
|
|
|
|
|
|
class ActivityState(db.Model):
|
|
id = db.Column(db.Integer, primary_key=True)
|
|
room_id = db.Column(db.Integer, db.ForeignKey("room.id"), nullable=False)
|
|
section_id = db.Column(db.String(128), nullable=False)
|
|
step_id = db.Column(db.String(128), nullable=False)
|
|
attempts = db.Column(db.Integer, default=0)
|
|
max_attempts = db.Column(db.Integer, default=3)
|
|
s3_file_path = db.Column(db.String(256), nullable=False)
|
|
json_metadata = db.Column(db.UnicodeText, default="{}")
|
|
|
|
@property
|
|
def dict_metadata(self):
|
|
return json.loads(self.json_metadata) if self.json_metadata else {}
|
|
|
|
@dict_metadata.setter
|
|
def dict_metadata(self, value):
|
|
self.json_metadata = json.dumps(value)
|
|
|
|
def add_metadata(self, key, value):
|
|
metadata = self.dict_metadata
|
|
metadata[key] = value
|
|
self.dict_metadata = metadata
|
|
|
|
def remove_metadata(self, key):
|
|
metadata = self.dict_metadata
|
|
if key in metadata:
|
|
del metadata[key]
|
|
self.dict_metadata = metadata
|
|
|
|
def clear_metadata(self):
|
|
self.dict_metadata = {}
|