# Admin Interface Documentation ## Overview A web-based admin interface has been added to MySMSAPio for managing API keys and monitoring SMS logs through a user-friendly dashboard. ## Features ### 1. Dashboard - Real-time statistics overview - Total and online gateways - Active API keys count - Messages sent/received today - Failed messages tracking - Recent messages display - Gateway status overview ### 2. API Keys Management - **List API Keys**: View all API keys with their status, permissions, and usage - **Create API Keys**: Generate new API keys with customizable permissions - Send SMS permission - Receive SMS permission - Manage Gateways permission - Optional expiration date - **Revoke API Keys**: Deactivate API keys when no longer needed - **View Details**: See API key prefix, last used date, and creation date ### 3. SMS Logs Monitoring - **View All Messages**: Paginated list of all SMS messages (50 per page) - **Advanced Filtering**: - Direction (Inbound/Outbound) - Status (Pending/Queued/Sent/Delivered/Failed) - Phone number search - Gateway filter - Date range (Start/End date) - **Message Details**: View message ID, content, timestamps, retry count, and error messages - **Real-time Updates**: See the latest message activity ### 4. Gateways Management - **List Gateways**: View all registered gateway devices - **Gateway Details**: - Connection status (Online/Offline) - Message statistics (today and total) - Last heartbeat timestamp - Device metadata - **Activate/Deactivate**: Toggle gateway active status - **Recent Messages**: View messages processed by each gateway ## Access ### Default Login Credentials After running `bin/rails db:seed`, you can access the admin interface with: - **URL**: http://localhost:3000/admin/login - **Email**: admin@example.com - **Password**: password123 ⚠️ **IMPORTANT**: Change the default password immediately in production! ### Creating Additional Admin Users ```ruby # In Rails console (bin/rails console) Admin.create!( email: "your-email@example.com", password: "your-secure-password", name: "Your Name" ) ``` ## Routes All admin routes are namespaced under `/admin`: - `GET /admin/login` - Login page - `POST /admin/login` - Login action - `DELETE /admin/logout` - Logout action - `GET /admin/dashboard` - Dashboard home - `GET /admin/api_keys` - List API keys - `GET /admin/api_keys/new` - Create new API key - `POST /admin/api_keys` - Save new API key - `DELETE /admin/api_keys/:id` - Revoke API key - `POST /admin/api_keys/:id/toggle` - Toggle API key active status - `GET /admin/logs` - View SMS logs with filtering - `GET /admin/gateways` - List all gateways - `GET /admin/gateways/:id` - View gateway details - `POST /admin/gateways/:id/toggle` - Toggle gateway active status ## Technical Details ### Authentication - Uses Rails' `has_secure_password` with bcrypt for secure password hashing - Session-based authentication - Password must be at least 8 characters - Email validation with format checking ### Authorization - All admin controllers inherit from `Admin::BaseController` - `require_admin` before_action ensures user is logged in - Redirects to login page if not authenticated ### Models - **Admin** (`app/models/admin.rb`): Admin user accounts - Fields: email, password_digest, name, last_login_at - Validations: email uniqueness and format, password minimum length - Methods: `update_last_login!` for tracking login activity ### Controllers - **Admin::SessionsController**: Handles login/logout - **Admin::DashboardController**: Dashboard with statistics - **Admin::ApiKeysController**: API key CRUD operations - **Admin::LogsController**: SMS message logs with filtering - **Admin::GatewaysController**: Gateway management ### Views - Custom admin layout with built-in CSS (no external dependencies) - Responsive design with clean, modern UI - Turbo-powered for fast navigation - Integrated flash messages for user feedback ### Styling - Custom CSS included in admin layout - No external CSS frameworks required - Clean, modern design with: - Card-based layouts - Color-coded badges for status indicators - Responsive grid system - Form styling with validation states - Alert notifications ### Pagination - Uses Pagy gem for efficient pagination - Configured in `Admin::BaseController` with `include Pagy::Backend` - Frontend helpers in `ApplicationHelper` with `include Pagy::Frontend` - 50 items per page for logs ## Security Best Practices 1. **Change Default Password**: Immediately change admin@example.com password in production 2. **Use Strong Passwords**: Enforce minimum 8 characters (configured in model) 3. **HTTPS Only**: Always use HTTPS in production 4. **Session Security**: Configure secure session cookies in production 5. **Rate Limiting**: Consider adding rate limiting to login endpoint 6. **Regular Audits**: Monitor admin access through `last_login_at` field ## Database Schema ### Admins Table ```ruby create_table "admins" do |t| t.string :email, null: false t.string :password_digest, null: false t.string :name, null: false t.datetime :last_login_at t.timestamps t.index :email, unique: true end ``` ## Customization ### Adding New Admin Features 1. Create controller in `app/controllers/admin/` 2. Inherit from `Admin::BaseController` 3. Add routes in `config/routes.rb` under `namespace :admin` 4. Create views in `app/views/admin/` ### Styling Customization - Edit inline styles in `app/views/layouts/admin.html.erb` - Modify CSS variables for colors, spacing, fonts - Add custom JavaScript if needed ### Adding Permissions - Extend `Admin` model with role/permission system - Add authorization checks in controllers - Update views to show/hide features based on permissions ## Troubleshooting ### "Please log in to continue" message - Session may have expired - Navigate to `/admin/login` to log in again ### API key not showing after creation - API keys are only shown once for security - If lost, revoke and create a new one ### Pagination not working - Ensure Pagy gem is installed: `bundle exec gem list pagy` - Check that `Pagy::Backend` is included in `Admin::BaseController` - Verify `Pagy::Frontend` is in `ApplicationHelper` ### Filters not applying - Check that form is submitting with GET method - Verify filter parameters are being passed in URL - Check `apply_filters` method in `Admin::LogsController` ## Development ### Running Tests ```bash bin/rails test ``` ### Checking Routes ```bash bin/rails routes | grep admin ``` ### Console Access ```bash bin/rails console # Check admin users Admin.all # Create new admin Admin.create!(email: "test@example.com", password: "password", name: "Test") ``` ## Future Enhancements Potential features to add: - [ ] Role-based permissions (Admin, Viewer, Operator) - [ ] Activity logs (audit trail) - [ ] Two-factor authentication (2FA) - [ ] Email notifications for critical events - [ ] Export functionality (CSV, JSON) - [ ] Advanced analytics and charts - [ ] Webhook management interface - [ ] OTP code management - [ ] Bulk operations for messages - [ ] API usage analytics per key --- ## Tailwind CSS Theme The admin interface has been completely redesigned with **Tailwind CSS v4** for a modern, professional appearance. ### Design Features #### Color Scheme - **Primary**: Blue (#3b82f6 - blue-600) - **Success**: Green (#10b981 - green-500) - **Warning**: Yellow (#f59e0b - yellow-500) - **Danger**: Red (#ef4444 - red-500) - **Neutral**: Gray scale for text and backgrounds #### Components **Sidebar Navigation:** - Dark gradient background (gray-900 to gray-800) - Fixed 288px width (w-72) - Active state highlighting - User profile section at bottom - Smooth transitions on hover **Cards:** - Rounded corners (rounded-xl) - Subtle shadows (ring-1 ring-gray-900/5) - White background - Proper spacing and padding **Stats Cards:** - Colored icon backgrounds - Large numbers for metrics - Secondary information in smaller text - Animated pulse indicators for online status **Tables:** - Alternating row backgrounds on hover - Sticky headers - Responsive overflow scrolling - Color-coded status badges **Badges:** - Rounded-full design - Color-coded by status - Ring borders for depth - Icons integrated **Forms:** - Rounded inputs (rounded-lg) - Icon prefixes for visual clarity - Focus states with blue ring - Proper validation styling - Checkbox descriptions **Buttons:** - Primary: Blue gradient with hover effect - Secondary: Gray with hover effect - Danger: Red for destructive actions - Success: Green for positive actions - All include smooth transitions #### Typography - Headlines: Bold, large sizes (text-3xl) - Body: Gray-900 for primary text, gray-600 for secondary - Font weights: Semibold for emphasis, medium for labels - Proper line heights and spacing #### Icons - **Font Awesome 6.4.0** icons throughout - Contextual icon usage - Consistent sizing - Proper spacing with text #### Responsive Design - Mobile-first approach - Grid layouts that adapt (1/2/3/4 columns) - Overflow scrolling on mobile - Touch-friendly tap targets #### Animations - Pulse animation for online indicators - Smooth transitions (duration-200) - Hover state changes - Loading states ### Development **Build Tailwind CSS:** ```bash bin/rails tailwindcss:build ``` **Watch for changes (development):** ```bash bin/rails tailwindcss:watch ``` **Using foreman (recommended for development):** ```bash bin/dev ``` This automatically runs both Rails server and Tailwind watcher. ### Customization #### Custom Colors Edit `app/assets/tailwind/application.css`: ```css @theme { --color-primary-500: #your-color; --color-primary-600: #your-darker-color; } ``` #### Extending Tailwind The project uses Tailwind CSS v4 with the new `@import "tailwindcss"` syntax. Custom utilities can be added directly to the CSS file. #### Custom Scrollbar Custom scrollbar styling is included for webkit browsers with gray colors matching the theme. ### Browser Support - Modern browsers (Chrome, Firefox, Safari, Edge) - CSS Grid and Flexbox required - Custom scrollbar styles for webkit browsers - Responsive design works on all screen sizes ### Performance - Tailwind CSS is compiled and cached - Production builds are automatically optimized - Uses Rails asset pipeline for caching - Minimal JavaScript (only for interactive features like copy-to-clipboard) ### Accessibility - Semantic HTML elements - Proper ARIA labels - Keyboard navigation support - Focus states visible - Color contrast meets WCAG guidelines - Screen reader friendly