This document explains the implementation of user management in the SecondBrain application. The implementation provides basic authentication with JWT tokens and ensures all user data (chats, documents, tags) is isolated per user.
New Table: users
id(UUID, Primary Key)username(String, Unique)password_hash(String, BCrypt hashed)created_at(DateTime)updated_at(DateTime)
Modified Tables:
chats: Addeduser_idforeign keydocuments: Addeduser_idforeign keytags: Addeduser_idforeign key, changed name uniqueness to be per-usermessages: Inherit user through chat relationshipdocument_chunks: Inherit user through document relationshipdocument_tags: Inherit user through document relationship
Security Components:
- Password Hashing: BCrypt with PassLib
- JWT Tokens: Using python-jose with 7-day expiration
- Dependencies: FastAPI dependency injection for authentication
Key Files:
backend/app/core/security.py: Password hashing and JWT utilitiesbackend/app/core/deps.py: Authentication dependenciesbackend/app/schemas/auth.py: Pydantic schemas for authenticationbackend/app/api/auth.py: Login and user info endpoints
All existing endpoints now:
- Require authentication via JWT Bearer token
- Filter all queries by current user's ID
- Only return data belonging to authenticated user
New Endpoints:
POST /api/v1/auth/login: User loginGET /api/v1/auth/me: Get current user info
ChatService Changes:
- All methods accept
user_idparameter - Queries filtered by user ownership
- User context passed through RAG system
EmbeddingService Changes:
- Similarity search filtered by user
- Document processing assigns user ownership
- Vector search respects user boundaries
Features:
- Reactive Svelte store for auth state
- Token storage in localStorage
- Automatic token validation on app start
- Centralized auth service for all components
Features:
- Clean, responsive login form
- Form validation and error handling
- Loading states and user feedback
- Automatic redirect after successful login
Features:
- Automatic authentication check on app load
- Route guards redirecting unauthenticated users
- Public routes configuration
All API calls now:
- Include JWT Bearer token in Authorization header
- Handle authentication errors gracefully
- Provide user feedback for auth failures
cd backend
pip install python-jose[cryptography]==3.3.0 passlib[bcrypt]==1.7.4cd backend
alembic upgrade headcd backend
python create_user.py --interactiveOr:
python create_user.py --username admin --password securepassword123Add to your .env file:
SECRET_KEY=your-super-secret-key-change-this-in-production
POST /api/v1/auth/login
Content-Type: application/json
{
"username": "admin",
"password": "password123"
}Response:
{
"access_token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
"token_type": "bearer"
}GET /api/v1/auth/me
Authorization: Bearer <token>Response:
{
"id": "uuid",
"username": "admin",
"created_at": "2025-08-24T12:00:00Z"
}All existing endpoints (/api/v1/chats, /api/v1/documents, etc.) now require authentication:
GET /api/v1/chats
Authorization: Bearer <token>import { authService } from '$lib/stores/auth';
// Login
await authService.login(username, password);
// Logout
authService.logout();
// Get auth headers for API calls
const headers = authService.getAuthHeaders();import { authStore } from '$lib/stores/auth';
// Subscribe to auth state
$authStore.isAuthenticated
$authStore.user
$authStore.isLoading- Storage: Tokens stored in localStorage (consider httpOnly cookies for production)
- Expiration: 7-day token lifetime
- Validation: Automatic token validation on app start
- Hashing: BCrypt with automatic salt generation
- Validation: Minimum 6 character requirement (easily configurable)
- Complete Separation: Users can only access their own data
- Database Level: All queries filtered by user_id
- API Level: Authentication required for all data endpoints
cd backend
python create_user.py --username testuser1 --password test123
python create_user.py --username testuser2 --password test456- Visit
/loginin your browser - Login with created credentials
- Verify redirect to main application
- Test logout functionality
- Login as
testuser1 - Create some chats and documents
- Logout and login as
testuser2 - Verify you can't see testuser1's data
- Create different data as testuser2
- Switch back to testuser1 and verify isolation
If you have existing data in the system:
The migration creates user_id columns as nullable initially. You'll need to either:
- Assign existing data to a default user
- Clear existing data for a fresh start
-- Option 1: Create default user and assign all data
INSERT INTO users (id, username, password_hash, created_at)
VALUES ('default-uuid', 'admin', 'hashed-password', NOW());
UPDATE chats SET user_id = 'default-uuid' WHERE user_id IS NULL;
UPDATE documents SET user_id = 'default-uuid' WHERE user_id IS NULL;
UPDATE tags SET user_id = 'default-uuid' WHERE user_id IS NULL;
-- Option 2: Clear existing data (if acceptable)
DELETE FROM document_chunks;
DELETE FROM documents;
DELETE FROM messages;
DELETE FROM chats;
DELETE FROM document_tags;
DELETE FROM tags;- Check SECRET_KEY is set in environment
- Verify JWT token format and expiration
- Check password hashing with create_user.py script
- Ensure PostgreSQL is running
- Check database connection string
- Run migration manually:
alembic upgrade head
- Check browser localStorage for tokens
- Verify API endpoints are reachable
- Check browser network tab for auth headers
- Ensure CORS_ORIGINS includes your frontend URL
- Check that preflight requests include auth headers
# Add to main.py for debugging
import logging
logging.basicConfig(level=logging.DEBUG)
# Check auth dependency
from app.core.deps import get_current_user
# This will log authentication attempts// Check auth state
console.log($authStore);
// Check stored tokens
console.log(localStorage.getItem('auth_token'));
// Check API headers
console.log(authService.getAuthHeaders());- Role-based permissions (admin/user)
- User registration endpoint
- Password reset functionality
- Session management
- Multi-factor authentication
- User profile management
- HTTP-only cookie storage for tokens
- Token refresh mechanism
- Rate limiting on login attempts
- Account lockout after failed attempts
- Audit logging for user actions
- Remember me functionality
- Better error messaging
- Loading states throughout app
- User dashboard/settings page
The user management implementation provides a solid foundation for multi-user SecondBrain deployment. The system ensures complete data isolation while maintaining the existing functionality. The JWT-based authentication is stateless and scalable, making it suitable for both single-server and distributed deployments.
The implementation follows security best practices and provides a clean separation between authentication logic and business logic, making future enhancements straightforward to implement.