An AI-powered intelligent chatbot platform for DBIT College that provides instant access to academic schedules, course details, faculty information, campus events, and official notices.
- AI-Powered Chat Interface: Natural language processing for intelligent responses using Lovable AI
- Real-time Messaging: WebSocket-based instant communication with typing indicators
- Anonymous & Authenticated Sessions: Support for guest users and registered accounts with secure session tokens
- Multi-Category Support: Academic, administrative, technical queries with smart routing
- File Upload Support: Document processing and querying with 10MB limit
- Chat History: Persistent conversation tracking for authenticated users
- Quick Actions: Pre-defined common queries for faster access
- Role-Based Access Control: Student, Faculty, Staff, and Admin roles with granular permissions
- User Authentication: Secure login with email/password via Supabase Auth
- Profile Management: Customizable user profiles with avatars, department, and year information
- Session Management: Automatic token refresh and session expiration warnings
- Password Security: Minimum 8 characters with uppercase, lowercase, and numbers
- Analytics Dashboard: User metrics, message statistics, and system performance insights
- Content Management: Knowledge base and FAQ management with categories
- User Management: Role assignment and account administration
- Event & Announcement Management: Campus-wide notifications with priority levels
- Audit Logging: Complete activity tracking for security and compliance
- Feedback Analytics: View and analyze user feedback on bot responses
- Row-Level Security (RLS): Database-level access control for all tables
- Session Token Protection: Secure anonymous user sessions with UUID-based tokens
- Input Validation: Comprehensive validation using Zod schemas
- XSS Protection: Input sanitization and output encoding
- Error Boundaries: Graceful error handling with user-friendly messages
- CSRF Protection: Built-in with Supabase Auth
- React 18 with TypeScript
- Vite for fast development and optimized builds
- Tailwind CSS with semantic design tokens
- shadcn/ui for accessible UI components
- React Router v6 for client-side routing
- TanStack Query for efficient data fetching and caching
- Supabase for:
- PostgreSQL database with Row-Level Security
- Authentication with email/password
- Real-time subscriptions for live chat
- Storage for avatars and chat attachments
- Edge Functions for serverless logic
- Lovable AI for intelligent response generation and context-aware conversations
-
Clone the repository
git clone <repository-url> cd dbit-chatbot
-
Install dependencies
npm install
-
Set up environment variables Create a
.envfile with:VITE_SUPABASE_URL=your_supabase_url VITE_SUPABASE_PUBLISHABLE_KEY=your_supabase_anon_key VITE_SUPABASE_PROJECT_ID=your_project_id
-
Run database migrations
- Access your Supabase dashboard
- Go to SQL Editor
- Run migrations from
supabase/migrations/directory in order
-
Configure Supabase Auth
- Enable Email provider in Authentication โ Providers
- Configure email templates (optional)
- Enable Leaked Password Protection (recommended)
-
Start development server
npm run dev
Application will be available at
http://localhost:8080
- Go to Supabase Dashboard โ Authentication โ Policies
- Enable "Leaked Password Protection"
- This prevents users from using compromised passwords from data breaches
To set a user as admin, run this SQL query after they register:
UPDATE user_roles
SET role = 'admin'
WHERE user_id = (SELECT id FROM auth.users WHERE email = 'admin@example.com');Verify storage buckets are properly configured:
avatars: Public bucket for user profile pictureschat-attachments: Private bucket for document uploads (10MB limit)
Anonymous users are assigned secure session tokens that:
- Are stored in localStorage
- Are validated via RLS policies
- Expire when cleared manually
- Prevent unauthorized access to other users' conversations
-
Guest Access
- Visit the homepage at
/ - Click "Start Chatting" to begin immediately as a guest
- Your conversation is secured with a session token
- Visit the homepage at
-
Registered User Access
- Sign up at
/signupwith your college email - Verify your email (if enabled)
- Access additional features:
- Chat history across sessions
- Profile customization
- File uploads for document queries
- Personalized recommendations
- Sign up at
-
Initial Setup
- Register a normal account
- Have another admin promote your account via SQL query
- Or manually update the
user_rolestable
-
Admin Dashboard (
/admin)- View analytics and system metrics
- Manage knowledge base content
- Create and schedule announcements
- Manage campus events
- Assign user roles
- Review audit logs
- Monitor user feedback
dbit-chatbot/
โโโ src/
โ โโโ components/ # Reusable UI components
โ โ โโโ admin/ # Admin-specific components
โ โ โ โโโ AdminAnalytics.tsx
โ โ โ โโโ AdminUsers.tsx
โ โ โ โโโ AdminKnowledgeBase.tsx
โ โ โ โโโ AdminEvents.tsx
โ โ โ โโโ AdminAnnouncements.tsx
โ โ โโโ chat/ # Chat interface components
โ โ โ โโโ ChatHeader.tsx
โ โ โ โโโ ChatInput.tsx
โ โ โ โโโ ChatSidebar.tsx
โ โ โ โโโ MessageBubble.tsx
โ โ โ โโโ QuickActions.tsx
โ โ โ โโโ TypingIndicator.tsx
โ โ โโโ ui/ # shadcn/ui components
โ โ โโโ ErrorBoundary.tsx
โ โ โโโ ProtectedRoute.tsx
โ โ โโโ PermissionGuard.tsx
โ โ โโโ SessionWarning.tsx
โ โโโ contexts/ # React contexts
โ โ โโโ AuthContext.tsx
โ โ โโโ ChatContext.tsx
โ โโโ hooks/ # Custom React hooks
โ โ โโโ useProtectedRoute.ts
โ โ โโโ useRole.ts
โ โ โโโ useSession.ts
โ โ โโโ useTypingIndicator.ts
โ โ โโโ useRealtimeMessages.ts
โ โโโ pages/ # Page components
โ โ โโโ Index.tsx
โ โ โโโ Chat.tsx
โ โ โโโ Login.tsx
โ โ โโโ Signup.tsx
โ โ โโโ Profile.tsx
โ โ โโโ Admin.tsx
โ โ โโโ FAQ.tsx
โ โ โโโ About.tsx
โ โ โโโ Contact.tsx
โ โ โโโ NotFound.tsx
โ โโโ services/ # API and business logic
โ โ โโโ api.ts # Base API utilities
โ โ โโโ auth.ts # Authentication service
โ โ โโโ chatService.ts # Chat operations
โ โ โโโ aiService.ts # AI integration
โ โ โโโ userService.ts # User management
โ โ โโโ adminService.ts # Admin operations
โ โ โโโ fileService.ts # File upload/download
โ โ โโโ cacheService.ts # Client-side caching
โ โ โโโ knowledgeBaseService.ts
โ โโโ types/ # TypeScript type definitions
โ โ โโโ index.ts
โ โโโ utils/ # Utility functions
โ โ โโโ validation.ts # Zod validation schemas
โ โ โโโ sessionToken.ts # Session management
โ โโโ index.css # Global styles and design tokens
โ โโโ App.tsx # Root component with routing
โ โโโ main.tsx # Application entry point
โโโ supabase/
โ โโโ functions/ # Edge Functions
โ โ โโโ chat-ai/ # AI chat integration
โ โโโ migrations/ # Database migrations
โโโ public/ # Static assets
โโโ .env # Environment variables
โโโ tailwind.config.ts # Tailwind configuration
โโโ vite.config.ts # Vite configuration
โโโ package.json # Dependencies and scripts
The application uses semantic design tokens defined in:
src/index.css - CSS variables for colors, spacing, and animations:
:root {
--primary: 221 83% 53%; /* Blue */
--secondary: 215 16% 47%; /* Slate Gray */
--accent: 160 84% 39%; /* Emerald */
--background: 210 40% 98%; /* Light Gray */
/* ... more tokens */
}tailwind.config.ts - Tailwind configuration with custom plugins and theme extensions
VITE_SUPABASE_URL- Supabase project URLVITE_SUPABASE_PUBLISHABLE_KEY- Supabase anonymous keyVITE_SUPABASE_PROJECT_ID- Supabase project identifier
- Code Splitting: Automatic route-based code splitting with React.lazy()
- Image Optimization: WebP format with lazy loading
- Caching: Client-side caching for frequently accessed data
- Database Indexes: Optimized queries with proper indexing
- Bundle Size: Tree-shaking and minification in production
User profile information
id(uuid, PK)name(text)student_id(text, unique)phone(text)department(text)year(integer)avatar_url(text)
Role-based access control
id(uuid, PK)user_id(uuid, FK)role(app_role enum: student, faculty, staff, admin)
Chat conversations
id(uuid, PK)user_id(uuid, FK, nullable)session_token(text, for anonymous users)title(text)is_active(boolean)
Chat messages
id(uuid, PK)conversation_id(uuid, FK)content(text)sender_type(text: user, bot, system)attachments(text[])
FAQ and knowledge articles
id(uuid, PK)category(text)question(text)answer(text)keywords(text[])
Campus events
id(uuid, PK)title(text)description(text)date(timestamptz)location(text)category(text)
Official notices
id(uuid, PK)title(text)content(text)priority(text: low, medium, high, urgent)publish_date(timestamptz)expires_at(timestamptz, nullable)
User feedback on bot responses
id(uuid, PK)message_id(uuid, FK)rating(integer)comment(text)
System activity logs
id(uuid, PK)user_id(uuid)action(text)resource_type(text)resource_id(uuid)details(jsonb)
avatars- User profile pictures (public, 5MB limit)chat-attachments- Document uploads (private, 10MB limit)
handle_new_user()- Trigger to create profile on user registrationhas_role()- Security definer function for role checkinglog_admin_action()- Audit logging for admin actionshandle_updated_at()- Automatic timestamp updates
-
Via Lovable Platform:
- Click "Publish" in the Lovable editor
- Your app will be deployed to
*.lovable.app - Connect a custom domain in Settings โ Domains
-
Manual Deployment:
npm run build
Deploy the
dist/folder to:- Vercel
- Netlify
- Cloudflare Pages
- Any static hosting provider
- Edge Functions: Deploy automatically to Supabase
- Database Migrations: Run manually via Supabase dashboard
- Environment Variables: Set in hosting platform settings
- Verify environment variables
- Run all database migrations
- Enable Leaked Password Protection
- Configure email templates
- Set up admin accounts
- Test authentication flow
- Verify file upload functionality
- Check real-time messaging
- Test role-based access control
Authentication
- User registration with email
- Email verification (if enabled)
- Login with valid credentials
- Login with invalid credentials
- Password reset flow
- Session persistence
- Automatic logout on expiration
Chat Functionality
- Guest chat with session token
- Authenticated user chat
- Message sending and receiving
- Real-time updates
- File upload and processing
- Quick actions
- Chat history (authenticated users)
- Clear chat functionality
Admin Features
- Admin dashboard access
- Analytics display
- User management
- Role assignment
- Knowledge base CRUD
- Event management
- Announcement creation
- Audit log viewing
Security
- RLS policies enforcement
- Role-based access control
- Session token validation
- Input validation
- XSS prevention
- Anonymous user isolation
Responsive Design
- Mobile view (< 768px)
- Tablet view (768px - 1024px)
- Desktop view (> 1024px)
- Navigation menu responsiveness
- Chat interface on mobile
Cross-Browser Compatibility
- Chrome
- Firefox
- Safari
- Edge
Use these tools for monitoring:
- Supabase Dashboard: Database query performance, auth metrics
- Browser DevTools: Network, performance profiling
- Lighthouse: Accessibility, performance, SEO scores
- Database query response times
- Edge function execution times
- Storage usage
- Authentication success/failure rates
- Chat message volume
- User engagement metrics
- Client-side: Error Boundaries catch and display user-friendly messages
- Server-side: Edge Function logs in Supabase dashboard
- Admin: Audit logs for system activities
-
Weekly:
- Review audit logs
- Monitor system performance
- Check for failed edge function calls
-
Monthly:
- Update knowledge base content
- Review and respond to user feedback
- Optimize slow database queries
- Update dependencies
-
Quarterly:
- Database backup verification
- Security audit
- Performance optimization review
- User acceptance testing
1. "New row violates row-level security policy"
- Cause: User trying to access data they don't have permission for
- Solution: Verify RLS policies and ensure user_id is set correctly
2. Session token not working for anonymous users
- Cause: Session token not being sent in headers
- Solution: Check that
getSessionToken()is called and token is persisted
3. Messages not appearing in real-time
- Cause: Realtime subscription not set up correctly
- Solution: Verify that
messagestable is insupabase_realtimepublication
4. File upload failing
- Cause: File size exceeds limit or invalid file type
- Solution: Check file size (<10MB) and allowed MIME types
5. Admin dashboard not accessible
- Cause: User doesn't have admin role
- Solution: Update user_roles table to assign admin role
// Create conversation
chatService.createConversation(title: string)
// Send message
chatService.createMessage({
conversation_id: string,
content: string,
sender_type: 'user' | 'bot' | 'system',
attachments?: string[]
})
// Get messages
chatService.getMessages(conversationId: string)// Sign up
auth.signUp(email, password, name, studentId, role)
// Sign in
auth.signIn(email, password)
// Sign out
auth.signOut()
// Reset password
auth.resetPassword(email)// Get profile
userService.getProfile(userId)
// Update profile
userService.updateProfile(userId, updates)
// Upload avatar
userService.uploadAvatar(file)- Fork the repository
- Create a feature branch (
git checkout -b feature/amazing-feature) - Commit your changes (
git commit -m 'Add amazing feature') - Push to the branch (
git push origin feature/amazing-feature) - Open a Pull Request
This project is licensed under the MIT License - see the LICENSE file for details.
- Project Lead: [Manoj S]
- Backend Developer: [Manoj Gowda B Y]
- Frontend Developer: [Harshavardhan S]
- UI/UX Designer: [Manoj S]
- DBIT College for project support
- Lovable.dev for AI integration platform
- Supabase for backend infrastructure
- shadcn/ui for component library
- Email: support@dbit.edu
- Contact Form:
/contactpage in the application - Admin Support: Contact via admin dashboard
- GitHub Issues: Report bugs and feature requests
- Documentation: Lovable Docs
- Supabase Docs: Supabase Documentation
- Voice input for chat messages
- Multi-language support
- Advanced analytics dashboard
- Mobile app (React Native)
- Integration with college ERP system
- Video call support for faculty consultations
- AI-powered content recommendations
- Advanced search with filters
- Export chat history
- Dark mode improvements
Built with โค๏ธ for DBIT College
Powered by Lovable AI, Supabase, and React