{"id":31425144,"url":"https://github.com/michaelwp/student_attendances","last_synced_at":"2025-09-30T04:57:20.918Z","repository":{"id":308338014,"uuid":"1032409039","full_name":"michaelwp/student_attendances","owner":"michaelwp","description":"ivan's student attendances","archived":false,"fork":false,"pushed_at":"2025-08-05T10:43:15.000Z","size":12029,"stargazers_count":0,"open_issues_count":0,"forks_count":0,"subscribers_count":0,"default_branch":"main","last_synced_at":"2025-08-05T12:34:36.186Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":null,"language":"Go","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/michaelwp.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null}},"created_at":"2025-08-05T09:08:41.000Z","updated_at":"2025-08-05T10:43:19.000Z","dependencies_parsed_at":"2025-08-05T12:34:37.999Z","dependency_job_id":"7f3877bf-c45c-4d36-80f2-eb8e5fc55dda","html_url":"https://github.com/michaelwp/student_attendances","commit_stats":null,"previous_names":["michaelwp/student_attendances"],"tags_count":null,"template":false,"template_full_name":null,"purl":"pkg:github/michaelwp/student_attendances","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/michaelwp%2Fstudent_attendances","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/michaelwp%2Fstudent_attendances/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/michaelwp%2Fstudent_attendances/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/michaelwp%2Fstudent_attendances/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/michaelwp","download_url":"https://codeload.github.com/michaelwp/student_attendances/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/michaelwp%2Fstudent_attendances/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":277632377,"owners_count":25850734,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","status":"online","status_checked_at":"2025-09-30T02:00:09.208Z","response_time":75,"last_error":null,"robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":true,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":[],"created_at":"2025-09-30T04:57:18.055Z","updated_at":"2025-09-30T04:57:20.911Z","avatar_url":"https://github.com/michaelwp.png","language":"Go","funding_links":[],"categories":[],"sub_categories":[],"readme":"# Student Attendance System\n\nA comprehensive full-stack student attendance management system with a REST API backend built with Go/Fiber and a modern React/TypeScript frontend. Features include teacher management, student enrollment, class organization, attendance tracking, and a comprehensive admin dashboard with real-time statistics.\n\n## Features\n\n### Backend API Features\n- **JWT Authentication**: Secure multi-user authentication (Admin, Teacher, Student) with Redis caching\n- **Role-Based Access Control**: Different permission levels for admins, teachers, and students\n- **Teacher Management**: Full CRUD operations with photo upload, password reset, and status management\n- **Class Management**: Create and manage classes with homeroom teacher assignments\n- **Student Management**: Complete student lifecycle management with class assignments and status tracking\n- **Attendance Tracking**: Comprehensive attendance recording with multiple status types and filtering\n- **Absence Requests**: Student absence request workflow with teacher/admin approval\n- **Photo Management**: Profile photo upload/retrieval for teachers and students via AWS S3\n- **Admin Dashboard**: Real-time statistics and comprehensive user management\n- **Password Security**: Automated password reset and secure update functionality\n- **Status Management**: Active/inactive status control for all user types\n- **RESTful API**: Clean, well-documented REST endpoints with consistent patterns\n- **Database Migrations**: Automated database schema management\n- **Comprehensive Documentation**: Full Swagger/OpenAPI specification with updated routes\n\n### Frontend Web Application Features\n- **Modern React/TypeScript**: Built with React 19 and TypeScript for type safety\n- **Multi-language Support**: Full internationalization (i18n) with English and Indonesian\n- **Dark Mode**: System preference detection with manual toggle\n- **Responsive Design**: Mobile-first responsive design with Tailwind CSS\n- **Admin Dashboard**: Real-time statistics with active/inactive breakdowns for all entities\n- **Student Homepage**: Public attendance marking page for students with simple ID/password authentication\n- **Student Dashboard**: Comprehensive student portal with profile management, attendance statistics, and absent request functionality\n- **Complete CRUD Management**: Full create, read, update, delete operations for all business entities\n- **Photo Upload**: Drag-and-drop photo upload with preview and validation\n- **Password Management**: Update/reset password functionality for teachers, students, and admins\n- **Status Management**: Quick toggle for activating/deactivating users\n- **Advanced Data Tables**: Sortable, paginated tables with custom actions\n- **State Management**: Zustand for efficient state management with persistence\n- **Authentication Flow**: Secure login/logout with JWT token management\n- **Professional UI**: Clean, modern interface with accessibility features\n- **Error Handling**: Comprehensive error handling with user-friendly messages\n\n## Architecture\n\nThe application follows clean architecture principles with clear separation of concerns:\n\n### Backend Structure\n```\n   cmd/student_attendance/     # Application entry point\n   internal/\n      api/\n         handlers/          # HTTP handlers with interfaces\n         middleware/        # JWT authentication, CORS, logging\n         router.go          # Route definitions and middleware setup\n      config/                # Configuration management\n      models/                # Data models and business entities\n      repository/            # Data access layer with interfaces\n   db/                        # Database migrations and utilities\n   docs/                      # API documentation (Swagger/OpenAPI)\n   pkg/                       # Shared utilities (JWT, password hashing)\n```\n\n### Frontend Structure\n```\n   web/\n      src/\n         components/        # Reusable React components (Layout, Forms)\n         pages/            # Page components (Dashboard, Login)\n         stores/           # Zustand state management stores\n         services/         # API service layer with type-safe calls\n         types/            # TypeScript type definitions\n         hooks/            # Custom React hooks (theme, auth)\n         i18n/            # Internationalization setup and translations\n         styles/           # Global styles and Tailwind configuration\n```\n\n## Prerequisites\n\n- Go 1.21 or higher\n- PostgreSQL 12 or higher\n- Redis (for JWT token caching and session management)\n- Node.js 18 or higher (for web application)\n- npm or yarn (for frontend dependencies)\n- AWS S3 bucket (for photo storage)\n- Make (optional, for using Makefile commands)\n\n## Installation \u0026 Setup\n\n1. **Clone the repository**\n   ```bash\n   git clone \u003crepository-url\u003e\n   cd student_attendance\n   ```\n\n2. **Install dependencies**\n   ```bash\n   go mod download\n   ```\n\n3. **Set up environment variables**\n   ```bash\n   cp .env.example .env\n   # Edit .env with your database credentials\n   ```\n\n4. **Environment Configuration**\n   Create or update your `.env` file:\n   ```env\n   ENVIRONMENT=development\n   PORT=8080\n   \n   # Database configuration\n   DB_HOST=localhost\n   DB_PORT=5432\n   DB_NAME=student_attendances\n   DB_USER=postgres\n   DB_PASSWORD=postgres\n   DB_SSL_MODE=disable\n   \n   # Connection pool settings\n   MAX_CONNECTIONS=10\n   MAX_IDLE_CONNECTIONS=5\n   MAX_LIFETIME_CONNECTIONS=30\n   \n   # AWS S3 configuration (for photo uploads)\n   AWS_S3_REGION=us-east-1\n   AWS_ACCESS_KEY_ID=your-access-key-id\n   AWS_SECRET_ACCESS_KEY=your-secret-access-key\n   AWS_S3_BUCKET=your-bucket-name\n   \n   # Redis configuration\n   REDIS_HOST=localhost\n   REDIS_PORT=6379\n   REDIS_PASSWORD=\n   REDIS_DB=0\n   \n   # JWT and encryption (for future authentication)\n   JWT_SECRET=your-secret-key\n   SALT=your-salt\n   ROUND=12\n   \n   # Logging\n   LOG_LEVEL=debug\n   ```\n\n5. **Set up PostgreSQL database**\n   ```bash\n   # Create database\n   createdb student_attendances\n   \n   # Run migrations\n   make migration-up\n   # OR\n   go run db/migration.go up\n   ```\n\n6. **Build and run the application**\n   ```bash\n   # Build\n   go build -o bin/student_attendance cmd/student_attendance/main.go\n   \n   # Run\n   ./bin/student_attendance\n   # OR\n   go run cmd/student_attendance/main.go\n   ```\n\n7. **Access the API Documentation**\n   Once the server is running, you can access:\n   - **API Health Check**: http://localhost:8080/health\n   - **Swagger UI**: http://localhost:8080/swagger/index.html\n   - **Interactive API Testing**: Use the Swagger UI to test all endpoints\n\n## API Endpoints\n\n### Base URL\n- Development: `http://localhost:8080`\n- All API endpoints are prefixed with `/api/v1`\n\n### 🚨 **IMPORTANT: Authentication Required for All Endpoints** \n\n**ALL API endpoints require valid JWT authentication except for:**\n- `GET /health` (Health check)\n- `POST /api/v1/auth/login` (Login)\n\n### 🔒 **Authentication Required**\n**IMPORTANT**: All API endpoints require authentication (JWT token) except for:\n- `GET /health` - Health check endpoint\n- `POST /api/v1/auth/login` - User login endpoint\n\n**Authentication Methods**: Include JWT token via:\n- **Authorization Header**: `Authorization: Bearer \u003ctoken\u003e`\n- **HTTP-Only Cookie**: Automatically set after login\n\n### 🛡️ **Role-Based Access Control**\nThe API implements role-based access control with three user types:\n\n| User Type | Access Level | Can Access |\n|-----------|-------------|------------|\n| **Admin** | Full Access | All endpoints including admin management |\n| **Teacher** | Limited | Teachers, Classes, Students, Attendances, Absent Requests |\n| **Student** | Restricted | Limited access to Students, Attendances, Absent Requests |\n\n**Special Restrictions:**\n- **Admin endpoints** (`/admins/*`) - Admin authentication required\n- **Absent Request endpoints** (`/absent-requests/*`) - Student or Teacher authentication required\n- **All other endpoints** - Any authenticated user can access\n\n### Public Endpoints (No Authentication Required)\n- `GET /health` - Check API health status\n- `POST /api/v1/attendance/mark` - Student self-attendance marking (student ID + password)\n\n### Authentication Endpoints\n- `POST /api/v1/auth/login` - User login (admin, teacher, or student) - Returns JWT token\n- `POST /api/v1/auth/logout` - User logout (requires authentication) - Invalidates JWT token\n\n### Teachers (🔒 Authentication Required)\n- `POST /api/v1/teachers` - Create a new teacher\n- `GET /api/v1/teachers` - Get all teachers (paginated)\n- `GET /api/v1/teachers/{id}` - Get teacher by database ID\n- `GET /api/v1/teachers/teacher-id/{teacherId}` - Get teacher by teacher ID\n- `PUT /api/v1/teachers/{id}` - Update teacher\n- `DELETE /api/v1/teachers/{id}` - Delete teacher\n- `PUT /api/v1/teachers/{id}/photo` - Upload teacher profile photo\n- `GET /api/v1/teachers/{id}/photo` - Get teacher profile photo (signed URL)\n- `PUT /api/v1/teachers/teacher-id/{teacherId}/reset-password` - Reset teacher password (generates new password)\n- `PUT /api/v1/teachers/teacher-id/{teacherId}/password` - Update teacher password (user provides old and new password)\n\n### Classes (🔒 Authentication Required)\n- `POST /api/v1/classes` - Create a new class\n- `GET /api/v1/classes` - Get all classes (paginated)\n- `GET /api/v1/classes/{id}` - Get class by ID\n- `GET /api/v1/classes/teacher-id/{teacherId}` - Get classes by teacher\n- `PUT /api/v1/classes/{id}` - Update class\n- `DELETE /api/v1/classes/{id}` - Delete class\n\n### Students (🔒 Authentication Required)\n- `POST /api/v1/students` - Create a new student\n- `GET /api/v1/students` - Get all students (paginated)\n- `GET /api/v1/students/{id}` - Get student by database ID\n- `GET /api/v1/students/student-id/{studentId}` - Get student by student ID\n- `GET /api/v1/students/class-id/{classId}` - Get students by class\n- `PUT /api/v1/students/{id}` - Update student\n- `DELETE /api/v1/students/{id}` - Delete student\n- `PUT /api/v1/students/{id}/photo` - Upload student profile photo\n- `GET /api/v1/students/{id}/photo` - Get student profile photo (signed URL)\n- `PUT /api/v1/students/student-id/{studentId}/reset-password` - Reset student password (generates new password)\n- `PUT /api/v1/students/student-id/{studentId}/password` - Update student password (user provides old and new password)\n\n### Student Dashboard (🔒 Student Authentication Required)\n- `GET /api/v1/student/profile` - Get authenticated student's profile with attendance statistics\n- `PUT /api/v1/student/profile` - Update authenticated student's profile (first name, last name, email, phone)\n- `PUT /api/v1/student/password` - Update authenticated student's password (with old password verification)\n- `GET /api/v1/student/absent-requests` - Get authenticated student's absent requests (paginated)\n- `POST /api/v1/student/absent-requests` - Create new absent request for authenticated student\n- `DELETE /api/v1/student/absent-requests/{id}` - Delete student's own absent request (pending requests only)\n\n### Teacher Dashboard (🔒 Teacher Authentication Required)\n- `GET /api/v1/teacher/profile` - Get authenticated teacher's profile with assigned classes and statistics\n- `PUT /api/v1/teacher/password` - Update authenticated teacher's password (with old password verification)\n- `GET /api/v1/absent-requests/current-teacher` - Get absent requests from students in teacher's classes (paginated)\n- `PUT /api/v1/absent-requests/absent-request-id/{id}/approve` - Approve a student's absent request\n- `PUT /api/v1/absent-requests/absent-request-id/{id}/reject` - Reject a student's absent request\n\n### Attendances (🔒 Authentication Required)\n- `POST /api/v1/attendances` - Create attendance record\n- `GET /api/v1/attendances/all` - Get all attendance records (paginated)\n- `GET /api/v1/attendances/attendances-id/{id}` - Get attendance by database ID\n- `GET /api/v1/attendances/student-id/{studentId}` - Get attendance by student\n- `GET /api/v1/attendances/class-id/{classId}` - Get attendance by class\n- `GET /api/v1/attendances/date-range?start_date=YYYY-MM-DD\u0026end_date=YYYY-MM-DD` - Get attendance by date range\n- `PUT /api/v1/attendances/attendances-id/{id}` - Update attendance record\n- `DELETE /api/v1/attendances/attendances-id/{id}` - Delete attendance record (soft delete)\n\n### Absent Requests (🔒 Authentication Required - Student/Teacher Only)\n- `POST /api/v1/absent-requests` - Create absence request\n- `GET /api/v1/absent-requests/{id}` - Get absent request by ID\n- `GET /api/v1/absent-requests/student-id/{studentId}` - Get requests by student\n- `GET /api/v1/absent-requests/class-id/{classId}` - Get requests by class\n- `GET /api/v1/absent-requests/pending` - Get all pending requests\n- `PATCH /api/v1/absent-requests/{id}/status` - Update request status\n- `DELETE /api/v1/absent-requests/{id}` - Delete absent request\n\n### Admins (🔒 Authentication Required - Admin Only)\n- `POST /api/v1/admins` - Create a new admin\n- `GET /api/v1/admins` - Get all admins (paginated)\n- `GET /api/v1/admins/{id}` - Get admin by database ID\n- `GET /api/v1/admins/email/{email}` - Get admin by email\n- `PUT /api/v1/admins/{id}` - Update admin\n- `DELETE /api/v1/admins/{id}` - Delete admin\n- `PUT /api/v1/admins/{id}/password` - Update admin password (with old password verification)\n- `PUT /api/v1/admins/{id}/status` - Set admin active status (activate/deactivate)\n\n## Data Models\n\n### Teacher\n```json\n{\n  \"id\": 1,\n  \"teacher_id\": \"TCH001\",\n  \"first_name\": \"John\",\n  \"last_name\": \"Doe\",\n  \"email\": \"john.doe@school.com\",\n  \"phone\": \"+1234567890\",\n  \"created_at\": \"2024-01-01T00:00:00Z\",\n  \"updated_at\": \"2024-01-01T00:00:00Z\"\n}\n```\n\n### Class\n```json\n{\n  \"id\": 1,\n  \"name\": \"Grade 10A\",\n  \"homeroom_teacher\": \"TCH001\",\n  \"description\": \"Advanced mathematics class\",\n  \"created_at\": \"2024-01-01T00:00:00Z\",\n  \"updated_at\": \"2024-01-01T00:00:00Z\"\n}\n```\n\n### Student\n```json\n{\n  \"id\": 1,\n  \"student_id\": \"STU001\",\n  \"classes_id\": 1,\n  \"first_name\": \"Jane\",\n  \"last_name\": \"Smith\",\n  \"email\": \"jane.smith@student.com\",\n  \"phone\": \"+1234567890\",\n  \"created_at\": \"2024-01-01T00:00:00Z\",\n  \"updated_at\": \"2024-01-01T00:00:00Z\"\n}\n```\n\n### Attendance\n```json\n{\n  \"id\": 1,\n  \"student_id\": \"STU001\",\n  \"class_id\": 1,\n  \"date\": \"2024-01-15T00:00:00Z\",\n  \"status\": \"present\",\n  \"description\": \"Student was on time\",\n  \"time_in\": \"2024-01-15T08:00:00Z\",\n  \"time_out\": \"2024-01-15T15:30:00Z\",\n  \"created_by\": 1,\n  \"updated_by\": 1,\n  \"created_at\": \"2024-01-01T00:00:00Z\",\n  \"updated_at\": \"2024-01-01T00:00:00Z\",\n  \"deleted_at\": null,\n  \"deleted_by\": null\n}\n```\n\n**Attendance Status Options:**\n- `present`: Student was present and on time\n- `absent`: Student was absent without prior notice\n- `late`: Student arrived late but attended class\n- `excused`: Student was absent with valid excuse/permission\n\n**Field Descriptions:**\n- `student_id`: Reference to the student's unique identifier\n- `class_id`: Reference to the class database ID\n- `date`: The date of attendance (ISO 8601 format)\n- `status`: Current attendance status (see options above)\n- `description`: Optional notes about the attendance record\n- `time_in`: Time when student checked in (auto-recorded for self-marking)\n- `time_out`: Time when student checked out (future feature)\n- `created_by`: ID of user who created the record (admin/teacher ID for manual entry, student ID for self-marking)\n- `updated_by`: ID of user who last updated the record\n- `deleted_at`: Timestamp when record was soft-deleted (null if active)\n- `deleted_by`: ID of admin who deleted the record\n\n### Absent Request\n```json\n{\n  \"id\": 1,\n  \"student_id\": \"STU001\",\n  \"class_id\": 1,\n  \"request_date\": \"2024-01-15\",\n  \"reason\": \"Medical appointment\",\n  \"status\": \"pending\",\n  \"created_at\": \"2024-01-01T00:00:00Z\",\n  \"updated_at\": \"2024-01-01T00:00:00Z\"\n}\n```\n\n**Request Status Options:**\n- `pending`: Request is waiting for approval\n- `approved`: Request has been approved\n- `rejected`: Request has been rejected\n\n### Admin\n```json\n{\n  \"id\": 1,\n  \"email\": \"admin@school.com\",\n  \"last_login\": \"2024-01-15T10:30:00Z\",\n  \"is_active\": true,\n  \"created_at\": \"2024-01-01T00:00:00Z\",\n  \"updated_at\": \"2024-01-01T00:00:00Z\"\n}\n```\n\n**Admin Status Options:**\n- `is_active: true`: Admin account is active and can log in\n- `is_active: false`: Admin account is deactivated and cannot log in\n\n### Authentication Models\n\n#### Login Request\n```json\n{\n  \"user_type\": \"admin\",\n  \"user_id\": \"admin@school.com\",\n  \"password\": \"securepassword123\"\n}\n```\n\n**User Type Options:**\n- `admin`: Use email as user_id\n- `teacher`: Use teacher_id as user_id\n- `student`: Use student_id as user_id\n\n#### Login Response\n```json\n{\n  \"translate_key\": \"success.login_successful\",\n  \"message\": \"Login successful\",\n  \"token\": \"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...\",\n  \"user_type\": \"admin\",\n  \"user_id\": \"admin@school.com\",\n  \"expires_at\": 1640995200\n}\n```\n\n**Additional Response Headers:**\n- `Set-Cookie`: Secure HTTP-only cookie containing the JWT token\n  - `HttpOnly=true` - Cannot be accessed by JavaScript\n  - `Secure=true` - Only transmitted over HTTPS\n  - `SameSite=Strict` - CSRF protection\n  - `Expires` - Same as token expiration (1 hour)\n\n#### JWT Token Claims\n```json\n{\n  \"user_id\": \"admin@school.com\",\n  \"user_type\": \"admin\",\n  \"exp\": 1640995200,\n  \"iat\": 1640991600\n}\n```\n\n## Development Commands\n\nThe project includes a Makefile with useful development commands:\n\n```bash\n# Database migrations\nmake migration-up     # Run migrations up\nmake migration-down   # Run migrations down\n\n# Code quality\nmake lint            # Run golangci-lint\nmake lint-fix        # Run golangci-lint with auto-fix\n\n# Git hooks\nmake install-hooks   # Install pre-commit hooks\nmake uninstall-hooks # Remove pre-commit hooks\n\n# Documentation\nmake swagger         # Generate Swagger documentation\n```\n\n### Manual Commands\n\n```bash\n# Build the application\ngo build -o bin/student_attendance cmd/student_attendance/main.go\n\n# Run tests\ngo test ./...\n\n# Run with coverage\ngo test -cover ./...\n\n# Format code\ngo fmt ./...\n\n# Vet code\ngo vet ./...\n\n# Run migrations manually\ngo run db/migration.go up\ngo run db/migration.go down\n```\n\n## API Documentation\n\n### Swagger/OpenAPI Documentation\n\nThe API comes with integrated Swagger UI for interactive documentation and testing:\n\n#### **Live Interactive Documentation**\n- **Swagger UI**: `http://localhost:8080/swagger/index.html` (when server is running)\n- **API Documentation**: Interactive interface to test all endpoints\n- **Model Schemas**: Complete data model definitions\n- **Try it out**: Execute API calls directly from the browser\n\n#### **Static Documentation Files**\n- **OpenAPI 3.0 Spec**: `docs/swagger.yaml`\n- **Swagger JSON**: `docs/swagger.json`  \n- **Generated Docs**: `docs/docs.go`\n\n#### **Usage Options**\n1. **Interactive Testing**: Visit `/swagger/` when the server is running\n2. **Swagger Editor**: Copy `docs/swagger.yaml` to [Swagger Editor](https://editor.swagger.io/)\n3. **Postman Import**: Import `docs/swagger.json` directly into Postman\n4. **Client SDK Generation**: Use `swagger-codegen` with the spec files\n\n#### **Regenerating Documentation**\nWhen you modify API handlers or add new endpoints:\n```bash\n# Regenerate Swagger docs\nswag init -g cmd/student_attendance/main.go --output docs --parseDependency --parseInternal\n\n# Or use make command (if added to Makefile)\nmake swagger\n```\n\n### Example API Calls\n\n⚠️ **Note**: All examples below (except login) require authentication. Include your JWT token in requests.\n\n#### Authentication Examples\n\n#### Admin Login\n```bash\ncurl -X POST http://localhost:8080/api/v1/auth/login \\\n  -H \"Content-Type: application/json\" \\\n  -d '{\n    \"user_type\": \"admin\",\n    \"user_id\": \"admin@school.com\",\n    \"password\": \"securepassword123\"\n  }'\n```\n\n#### Teacher Login\n```bash\ncurl -X POST http://localhost:8080/api/v1/auth/login \\\n  -H \"Content-Type: application/json\" \\\n  -d '{\n    \"user_type\": \"teacher\",\n    \"user_id\": \"TCH001\",\n    \"password\": \"securepassword123\"\n  }'\n```\n\n#### Student Login\n```bash\ncurl -X POST http://localhost:8080/api/v1/auth/login \\\n  -H \"Content-Type: application/json\" \\\n  -d '{\n    \"user_type\": \"student\",\n    \"user_id\": \"STU001\",\n    \"password\": \"securepassword123\"\n  }'\n```\n\n#### Logout (Requires Authentication)\n```bash\ncurl -X POST http://localhost:8080/api/v1/auth/logout \\\n  -H \"Authorization: Bearer YOUR_JWT_TOKEN_HERE\"\n```\n\n#### Using Authentication for Protected Requests\n```bash\n# Method 1: Using Authorization Header\ncurl -X GET http://localhost:8080/api/v1/teachers \\\n  -H \"Authorization: Bearer YOUR_JWT_TOKEN_HERE\"\n\n# Method 2: Using HTTP-Only Cookie (automatically set after login)\ncurl -X GET http://localhost:8080/api/v1/teachers \\\n  --cookie-jar cookies.txt --cookie cookies.txt\n```\n\n#### Create a Teacher (🔒 Authentication Required)\n```bash\ncurl -X POST http://localhost:8080/api/v1/teachers \\\n  -H \"Content-Type: application/json\" \\\n  -H \"Authorization: Bearer YOUR_JWT_TOKEN\" \\\n  -d '{\n    \"teacher_id\": \"TCH001\",\n    \"first_name\": \"John\",\n    \"last_name\": \"Doe\",\n    \"email\": \"john.doe@school.com\",\n    \"phone\": \"+1234567890\",\n    \"password\": \"securepassword123\"\n  }'\n```\n\n#### Create a Class (🔒 Authentication Required)\n```bash\ncurl -X POST http://localhost:8080/api/v1/classes \\\n  -H \"Content-Type: application/json\" \\\n  -H \"Authorization: Bearer YOUR_JWT_TOKEN\" \\\n  -d '{\n    \"name\": \"Grade 10A\",\n    \"homeroom_teacher\": \"TCH001\",\n    \"description\": \"Advanced mathematics class\"\n  }'\n```\n\n#### Create a Student (🔒 Authentication Required)\n```bash\ncurl -X POST http://localhost:8080/api/v1/students \\\n  -H \"Content-Type: application/json\" \\\n  -H \"Authorization: Bearer YOUR_JWT_TOKEN\" \\\n  -d '{\n    \"student_id\": \"STU001\",\n    \"classes_id\": 1,\n    \"first_name\": \"Jane\",\n    \"last_name\": \"Smith\",\n    \"email\": \"jane.smith@student.com\",\n    \"phone\": \"+1234567890\",\n    \"password\": \"securepassword123\"\n  }'\n```\n\n#### Attendance Management Examples (🔒 Authentication Required)\n\n##### Create Attendance Record\n```bash\ncurl -X POST http://localhost:8080/api/v1/attendances \\\n  -H \"Content-Type: application/json\" \\\n  -H \"Authorization: Bearer YOUR_JWT_TOKEN\" \\\n  -d '{\n    \"student_id\": \"STU001\",\n    \"class_id\": 1,\n    \"date\": \"2024-01-15T09:00:00Z\",\n    \"status\": \"present\",\n    \"description\": \"Student was on time\"\n  }'\n```\n\n##### Get All Attendance Records (Paginated)\n```bash\ncurl -X GET \"http://localhost:8080/api/v1/attendances/all?limit=20\u0026offset=0\" \\\n  -H \"Authorization: Bearer YOUR_JWT_TOKEN\"\n```\n\n##### Get Attendance by ID\n```bash\ncurl -X GET http://localhost:8080/api/v1/attendances/attendances-id/1 \\\n  -H \"Authorization: Bearer YOUR_JWT_TOKEN\"\n```\n\n##### Update Attendance Record\n```bash\ncurl -X PUT http://localhost:8080/api/v1/attendances/attendances-id/1 \\\n  -H \"Content-Type: application/json\" \\\n  -H \"Authorization: Bearer YOUR_JWT_TOKEN\" \\\n  -d '{\n    \"student_id\": \"STU001\",\n    \"class_id\": 1,\n    \"date\": \"2024-01-15T09:00:00Z\",\n    \"status\": \"late\",\n    \"description\": \"Student arrived 10 minutes late\"\n  }'\n```\n\n##### Delete Attendance Record (Soft Delete)\n```bash\ncurl -X DELETE http://localhost:8080/api/v1/attendances/attendances-id/1 \\\n  -H \"Authorization: Bearer YOUR_JWT_TOKEN\"\n```\n\n##### Get Attendance by Student\n```bash\ncurl -X GET http://localhost:8080/api/v1/attendances/student-id/STU001 \\\n  -H \"Authorization: Bearer YOUR_JWT_TOKEN\"\n```\n\n##### Get Attendance by Class\n```bash\ncurl -X GET http://localhost:8080/api/v1/attendances/class-id/1 \\\n  -H \"Authorization: Bearer YOUR_JWT_TOKEN\"\n```\n\n##### Get Attendance by Date Range\n```bash\ncurl -X GET \"http://localhost:8080/api/v1/attendances/date-range?start_date=2024-01-01\u0026end_date=2024-01-31\" \\\n  -H \"Authorization: Bearer YOUR_JWT_TOKEN\"\n```\n\n#### Student Self-Attendance Marking (No Authentication Required)\n```bash\ncurl -X POST http://localhost:8080/api/v1/attendance/mark \\\n  -H \"Content-Type: application/json\" \\\n  -d '{\n    \"student_id\": \"STU001\",\n    \"password\": \"studentpassword123\"\n  }'\n```\n\n#### Create Absence Request (🔒 Student/Teacher Authentication Required)\n```bash\ncurl -X POST http://localhost:8080/api/v1/absent-requests \\\n  -H \"Content-Type: application/json\" \\\n  -H \"Authorization: Bearer YOUR_JWT_TOKEN\" \\\n  -d '{\n    \"student_id\": \"STU001\",\n    \"class_id\": 1,\n    \"request_date\": \"2024-01-20\",\n    \"reason\": \"Medical appointment\"\n  }'\n```\n\n#### Approve Absence Request\n```bash\ncurl -X PATCH http://localhost:8080/api/v1/absent-requests/1/status \\\n  -H \"Content-Type: application/json\" \\\n  -d '{\n    \"status\": \"approved\"\n  }'\n```\n\n#### Upload Teacher Photo\n```bash\ncurl -X PUT http://localhost:8080/api/v1/teachers/1/photo \\\n  -F \"photo=@/path/to/teacher-photo.jpg\"\n```\n\n#### Get Teacher Photo\n```bash\ncurl -X GET http://localhost:8080/api/v1/teachers/1/photo\n```\n\n#### Upload Student Photo\n```bash\ncurl -X PUT http://localhost:8080/api/v1/students/1/photo \\\n  -F \"photo=@/path/to/student-photo.jpg\"\n```\n\n#### Get Student Photo\n```bash\ncurl -X GET http://localhost:8080/api/v1/students/1/photo\n```\n\n#### Reset Teacher Password\n```bash\ncurl -X PUT http://localhost:8080/api/v1/teachers/teacher-id/TCH001/reset-password\n```\n\n#### Update Teacher Password\n```bash\ncurl -X PUT http://localhost:8080/api/v1/teachers/teacher-id/TCH001/password \\\n  -H \"Content-Type: application/json\" \\\n  -d '{\n    \"old_password\": \"current_password\",\n    \"new_password\": \"new_secure_password\"\n  }'\n```\n\n#### Reset Student Password\n```bash\ncurl -X PUT http://localhost:8080/api/v1/students/student-id/STU001/reset-password\n```\n\n#### Update Student Password\n```bash\ncurl -X PUT http://localhost:8080/api/v1/students/student-id/STU001/password \\\n  -H \"Content-Type: application/json\" \\\n  -d '{\n    \"old_password\": \"current_password\",\n    \"new_password\": \"new_secure_password\"\n  }'\n```\n\n#### Student Dashboard Examples (🔒 Student Authentication Required)\n\n##### Get Student Profile with Statistics\n```bash\ncurl -X GET http://localhost:8080/api/v1/student/profile \\\n  -H \"Authorization: Bearer YOUR_STUDENT_JWT_TOKEN\"\n```\n\n##### Update Student Profile\n```bash\ncurl -X PUT http://localhost:8080/api/v1/student/profile \\\n  -H \"Content-Type: application/json\" \\\n  -H \"Authorization: Bearer YOUR_STUDENT_JWT_TOKEN\" \\\n  -d '{\n    \"first_name\": \"Jane\",\n    \"last_name\": \"Smith\",\n    \"email\": \"jane.smith@student.com\",\n    \"phone\": \"+1234567890\"\n  }'\n```\n\n##### Update Student Password (Self-Service)\n```bash\ncurl -X PUT http://localhost:8080/api/v1/student/password \\\n  -H \"Content-Type: application/json\" \\\n  -H \"Authorization: Bearer YOUR_STUDENT_JWT_TOKEN\" \\\n  -d '{\n    \"old_password\": \"current_password\",\n    \"new_password\": \"new_secure_password\"\n  }'\n```\n\n##### Get Student's Absent Requests\n```bash\ncurl -X GET \"http://localhost:8080/api/v1/student/absent-requests?limit=10\u0026offset=0\" \\\n  -H \"Authorization: Bearer YOUR_STUDENT_JWT_TOKEN\"\n```\n\n##### Create Absent Request\n```bash\ncurl -X POST http://localhost:8080/api/v1/student/absent-requests \\\n  -H \"Content-Type: application/json\" \\\n  -H \"Authorization: Bearer YOUR_STUDENT_JWT_TOKEN\" \\\n  -d '{\n    \"request_date\": \"2024-01-20\",\n    \"reason\": \"Medical appointment\"\n  }'\n```\n\n##### Delete Student's Own Absent Request\n```bash\ncurl -X DELETE http://localhost:8080/api/v1/student/absent-requests/1 \\\n  -H \"Authorization: Bearer YOUR_STUDENT_JWT_TOKEN\"\n```\n\n#### Teacher Dashboard Examples (🔒 Teacher Authentication Required)\n\n##### Get Teacher Profile with Classes and Statistics\n```bash\ncurl -X GET http://localhost:8080/api/v1/teacher/profile \\\n  -H \"Authorization: Bearer YOUR_TEACHER_JWT_TOKEN\"\n```\n\n##### Update Teacher Password (Self-Service)\n```bash\ncurl -X PUT http://localhost:8080/api/v1/teacher/password \\\n  -H \"Content-Type: application/json\" \\\n  -H \"Authorization: Bearer YOUR_TEACHER_JWT_TOKEN\" \\\n  -d '{\n    \"old_password\": \"current_password\",\n    \"new_password\": \"new_secure_password\"\n  }'\n```\n\n##### Get Absent Requests from Teacher's Classes\n```bash\ncurl -X GET \"http://localhost:8080/api/v1/absent-requests/current-teacher?limit=10\u0026offset=0\" \\\n  -H \"Authorization: Bearer YOUR_TEACHER_JWT_TOKEN\"\n```\n\n##### Approve Student Absent Request\n```bash\ncurl -X PUT http://localhost:8080/api/v1/absent-requests/absent-request-id/1/approve \\\n  -H \"Authorization: Bearer YOUR_TEACHER_JWT_TOKEN\"\n```\n\n##### Reject Student Absent Request\n```bash\ncurl -X PUT http://localhost:8080/api/v1/absent-requests/absent-request-id/1/reject \\\n  -H \"Authorization: Bearer YOUR_TEACHER_JWT_TOKEN\"\n```\n\n#### Create an Admin (🔒 Admin Authentication Required)\n```bash\ncurl -X POST http://localhost:8080/api/v1/admins \\\n  -H \"Content-Type: application/json\" \\\n  -H \"Authorization: Bearer YOUR_JWT_TOKEN\" \\\n  -d '{\n    \"email\": \"admin@school.com\",\n    \"password\": \"securepassword123\",\n    \"is_active\": true\n  }'\n```\n\n#### Get Admin by Email\n```bash\ncurl -X GET http://localhost:8080/api/v1/admins/email/admin@school.com\n```\n\n#### Update Admin Password\n```bash\ncurl -X PUT http://localhost:8080/api/v1/admins/1/password \\\n  -H \"Content-Type: application/json\" \\\n  -d '{\n    \"old_password\": \"current_password\",\n    \"new_password\": \"new_secure_password\"\n  }'\n```\n\n#### Set Admin Active Status\n```bash\ncurl -X PUT http://localhost:8080/api/v1/admins/1/status \\\n  -H \"Content-Type: application/json\" \\\n  -d '{\n    \"is_active\": false\n  }'\n```\n\n## Database Schema\n\nThe application uses PostgreSQL with the following main tables:\n\n- **teachers**: Teacher information and credentials\n- **classes**: Class information with homeroom teacher references\n- **students**: Student information and class assignments\n- **attendances**: Daily attendance records\n- **absent_requests**: Student absence requests with approval workflow\n- **admins**: Administrator accounts with authentication and status management\n\nAll tables include:\n- Auto-incrementing primary keys\n- Created/updated timestamps\n- Proper foreign key relationships\n- Check constraints for status fields\n\n## Photo Management\n\nThe API supports profile photo uploads for both teachers and students with AWS S3 integration:\n\n### Features\n- **File Upload**: Multipart form-data upload support\n- **S3 Storage**: Photos are stored securely in AWS S3\n- **Signed URLs**: Secure photo access with time-limited signed URLs\n- **Format Support**: Common image formats (JPEG, PNG, GIF, etc.)\n- **Automatic Path Updates**: Database records are updated with S3 keys\n- **Photo Retrieval**: Get secure photo URLs with expiration times\n- **Error Handling**: Comprehensive validation and error responses\n\n### Requirements\n- AWS S3 bucket configured with proper permissions\n- Environment variables for AWS credentials set up\n- Maximum file size limits enforced by the server\n\n### API Endpoints\n- `PUT /api/v1/teachers/{id}/photo` - Upload teacher profile photo\n- `GET /api/v1/teachers/{id}/photo` - Get teacher profile photo (signed URL)\n- `PUT /api/v1/students/{id}/photo` - Upload student profile photo\n- `GET /api/v1/students/{id}/photo` - Get student profile photo (signed URL)\n\n### Usage Examples\n```bash\n# Upload teacher photo\ncurl -X PUT http://localhost:8080/api/v1/teachers/1/photo \\\n  -F \"photo=@teacher-photo.jpg\"\n\n# Get teacher photo (signed URL)\ncurl -X GET http://localhost:8080/api/v1/teachers/1/photo\n\n# Upload student photo  \ncurl -X PUT http://localhost:8080/api/v1/students/1/photo \\\n  -F \"photo=@student-photo.jpg\"\n\n# Get student photo (signed URL)\ncurl -X GET http://localhost:8080/api/v1/students/1/photo\n```\n\n### Upload Response Format\n```json\n{\n  \"translate_key\": \"success.photo_uploaded\",\n  \"message\": \"Photo uploaded successfully\",\n  \"path\": \"https://bucket-name.s3.region.amazonaws.com/photos/teachers/1/teacher_1_1704067200.jpg\"\n}\n```\n\n### Get Photo Response Format\n```json\n{\n  \"translate_key\": \"success.photo_url_retrieved\",\n  \"message\": \"Photo URL retrieved successfully\",\n  \"url\": \"https://bucket-name.s3.region.amazonaws.com/photos/teachers/1/teacher_1_1704067200.jpg?X-Amz-Algorithm=...\"\n}\n```\n\n**Note**: The GET photo endpoint returns a signed URL that expires after a specified time (15 minutes for students, 1 hour for teachers) for security purposes.\n\n### Technical Implementation\nThe photo management system uses several new repository methods:\n\n#### Repository Methods\n- `UpdatePhotoPath(ctx context.Context, id uint, photoPath string) error` - Updates the photo path in the database\n- `GetPhotoPath(ctx context.Context, id uint) (string, error)` - Retrieves the photo path from the database\n\n#### S3 Configuration Methods\n- `UploadFile(client *s3.Client, key string, body []byte) error` - Uploads file to S3\n- `GetObjectURL(key string) string` - Gets public S3 object URL\n- `GetSignedURL(client *s3.Client, key string, expires time.Duration) (string, error)` - Generates presigned URLs\n\n#### File Storage Structure\nPhotos are organized in S3 with the following structure:\n```\nphotos/\n├── teachers/\n│   └── {teacher_id}/\n│       └── teacher_{id}_{timestamp}.{extension}\n└── students/\n    └── {student_id}/\n        └── student_{id}_{timestamp}.{extension}\n```\n\n## Password Management\n\nThe API provides secure password management functionality for both teachers and students:\n\n### Features\n- **Password Reset**: Administrators can reset user passwords and generate new secure passwords\n- **Password Update**: Users can change their own passwords by providing old and new passwords\n- **Secure Hashing**: All passwords are hashed using bcrypt with configurable salt rounds\n- **Password Generation**: System generates secure random passwords when resetting\n- **Validation**: Comprehensive validation for password requirements and user existence\n\n### API Endpoints\n- `PUT /api/v1/teachers/teacher-id/{teacherId}/reset-password` - Reset teacher password\n- `PUT /api/v1/teachers/teacher-id/{teacherId}/password` - Update teacher password\n- `PUT /api/v1/students/student-id/{studentId}/reset-password` - Reset student password  \n- `PUT /api/v1/students/student-id/{studentId}/password` - Update student password\n\n### Usage Examples\n\n#### Reset Teacher Password (Admin Function)\n```bash\ncurl -X PUT http://localhost:8080/api/v1/teachers/teacher-id/TCH001/reset-password\n```\n\n#### Update Teacher Password (User Function)\n```bash\ncurl -X PUT http://localhost:8080/api/v1/teachers/teacher-id/TCH001/password \\\n  -H \"Content-Type: application/json\" \\\n  -d '{\n    \"old_password\": \"current_password\",\n    \"new_password\": \"new_secure_password\"\n  }'\n```\n\n#### Reset Student Password (Admin Function)\n```bash\ncurl -X PUT http://localhost:8080/api/v1/students/student-id/STU001/reset-password\n```\n\n#### Update Student Password (User Function)\n```bash\ncurl -X PUT http://localhost:8080/api/v1/students/student-id/STU001/password \\\n  -H \"Content-Type: application/json\" \\\n  -d '{\n    \"old_password\": \"current_password\", \n    \"new_password\": \"new_secure_password\"\n  }'\n```\n\n### Response Formats\n\n#### Reset Password Response\n```json\n{\n  \"translate_key\": \"success.password.reset\",\n  \"message\": \"Password reset successfully\",\n  \"newPassword\": \"GeneratedSecurePassword123\"\n}\n```\n\n#### Update Password Response\n```json\n{\n  \"translate_key\": \"success.password.updated\",\n  \"message\": \"Password updated successfully\"\n}\n```\n\n### Security Considerations\n- Reset password generates a new secure random password\n- Update password requires knowledge of the current password\n- All passwords are hashed with bcrypt before storage\n- Password complexity is handled by the generation algorithm\n- User existence is verified before any password operations\n\n## Admin Management\n\nThe API provides comprehensive administrator account management functionality:\n\n### Features\n- **Admin Account Creation**: Create new admin accounts with email and password\n- **Account Status Management**: Activate/deactivate admin accounts\n- **Password Management**: Secure password updates with old password verification\n- **Admin Lookup**: Find admins by ID or email address\n- **Account Management**: Full CRUD operations for admin accounts\n- **Security**: Password hashing with bcrypt, account status controls\n\n### API Endpoints\n- `POST /api/v1/admins` - Create a new admin\n- `GET /api/v1/admins` - Get all admins (paginated)\n- `GET /api/v1/admins/{id}` - Get admin by database ID\n- `GET /api/v1/admins/email/{email}` - Get admin by email\n- `PUT /api/v1/admins/{id}` - Update admin information\n- `DELETE /api/v1/admins/{id}` - Delete admin account\n- `PUT /api/v1/admins/{id}/password` - Update admin password\n- `PUT /api/v1/admins/{id}/status` - Set admin active status\n\n### Admin Account States\n- **Active (`is_active: true`)**: Admin can log in and access the system\n- **Inactive (`is_active: false`)**: Admin account is disabled and cannot log in\n\n### Usage Examples\n\n#### Create Admin Account\n```bash\ncurl -X POST http://localhost:8080/api/v1/admins \\\n  -H \"Content-Type: application/json\" \\\n  -d '{\n    \"email\": \"admin@school.com\",\n    \"password\": \"securepassword123\",\n    \"is_active\": true\n  }'\n```\n\n#### Deactivate Admin Account\n```bash\ncurl -X PUT http://localhost:8080/api/v1/admins/1/status \\\n  -H \"Content-Type: application/json\" \\\n  -d '{\n    \"is_active\": false\n  }'\n```\n\n### Response Format\n```json\n{\n  \"translate_key\": \"success.admin_created\",\n  \"message\": \"Admin created successfully\"\n}\n```\n\n### Security Features\n- Email-based authentication and identification\n- Secure password hashing with bcrypt\n- Account activation/deactivation controls\n- Password update requires current password verification\n- Admin existence validation before operations\n\n## Authentication \u0026 Authorization\n\nThe API provides comprehensive JWT-based authentication for three user types: admin, teacher, and student.\n\n### Features\n- **JWT Token Authentication**: Secure token-based authentication with 1-hour expiration\n- **Multi-User Type Support**: Admin, teacher, and student authentication with different credentials\n- **Redis Token Caching**: Tokens are cached in Redis for fast validation and logout functionality\n- **Automatic Token Expiration**: Tokens expire after 1 hour for enhanced security\n- **Role-Based Access**: Different user types have different access levels\n- **Secure HTTP-Only Cookies**: Tokens are also stored in secure HTTP-only cookies\n- **Dual Authentication Support**: Both Bearer tokens and cookies are supported\n- **Secure Logout**: Token invalidation through Redis cache removal and cookie clearing\n\n### Authentication Flow\n1. **Login**: User provides user_type, user_id, and password\n2. **Validation**: System validates credentials based on user type:\n   - Admin: Uses email and password from admins table\n   - Teacher: Uses teacher_id and password from teachers table\n   - Student: Uses student_id and password from students table\n3. **Token Generation**: JWT token is generated with user information and 1-hour expiration\n4. **Redis Caching**: Token is cached in Redis with expiration\n5. **Cookie Setting**: Secure HTTP-only cookie is set with the token\n6. **Role Assignment**: User role is embedded in JWT claims for access control\n7. **Response**: Client receives JWT token in both response body and secure cookie\n\n### Using Authentication\n\n#### Login Process\n```bash\n# Admin login (use email as user_id)\ncurl -X POST http://localhost:8080/api/v1/auth/login \\\n  -H \"Content-Type: application/json\" \\\n  -d '{\n    \"user_type\": \"admin\",\n    \"user_id\": \"admin@school.com\", \n    \"password\": \"password123\"\n  }'\n\n# Teacher login (use teacher_id as user_id)\ncurl -X POST http://localhost:8080/api/v1/auth/login \\\n  -H \"Content-Type: application/json\" \\\n  -d '{\n    \"user_type\": \"teacher\",\n    \"user_id\": \"TCH001\",\n    \"password\": \"password123\"\n  }'\n\n# Student login (use student_id as user_id)\ncurl -X POST http://localhost:8080/api/v1/auth/login \\\n  -H \"Content-Type: application/json\" \\\n  -d '{\n    \"user_type\": \"student\", \n    \"user_id\": \"STU001\",\n    \"password\": \"password123\"\n  }'\n```\n\n#### Using JWT Tokens\nThere are two ways to authenticate with the API:\n\n**Method 1: Authorization Header (Bearer Token)**\n```bash\ncurl -X GET http://localhost:8080/api/v1/teachers \\\n  -H \"Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...\"\n```\n\n**Method 2: HTTP-Only Cookie (Automatic)**\n```bash\n# Cookie is automatically included in subsequent requests after login\ncurl -X GET http://localhost:8080/api/v1/teachers \\\n  --cookie-jar cookies.txt --cookie cookies.txt\n```\n\n#### Logout\nLogout works with either authentication method:\n\n**With Bearer Token:**\n```bash\ncurl -X POST http://localhost:8080/api/v1/auth/logout \\\n  -H \"Authorization: Bearer YOUR_JWT_TOKEN\"\n```\n\n**With Cookie:**\n```bash\ncurl -X POST http://localhost:8080/api/v1/auth/logout \\\n  --cookie-jar cookies.txt --cookie cookies.txt\n```\n\n**Note**: Logout clears both the Redis cache and the HTTP-only cookie for complete session termination.\n\n### Token Structure\nJWT tokens contain the following claims:\n- `user_id`: The user's identifier (email for admin, teacher_id for teacher, student_id for student)\n- `user_type`: The type of user (admin, teacher, student)\n- `exp`: Token expiration timestamp\n- `iat`: Token issued at timestamp\n\n### Middleware Features\nThe authentication middleware provides:\n- **JWTMiddleware**: Requires valid JWT token for all protected routes\n- **OptionalJWTMiddleware**: Validates token if provided, continues without if not\n- **RequireUserType**: Restricts access to specific user types (Admin, Teacher, Student)\n\n**Middleware Implementation:**\n- All API route groups use `JWTMiddleware` for authentication\n- Admin routes additionally use `RequireUserType(\"admin\")` \n- Absent Request routes use `RequireUserType(\"student\", \"teacher\")`\n\n### Security Considerations\n- Tokens are cached in Redis and validated on each request\n- Expired tokens are automatically removed from Redis\n- Admin accounts can be deactivated, preventing login even with valid passwords\n- All passwords are hashed with bcrypt before storage\n- Token expiration is enforced both in JWT claims and Redis cache\n- HTTP-only cookies prevent XSS attacks by making tokens inaccessible to JavaScript\n- Secure flag ensures cookies are only transmitted over HTTPS\n- SameSite=Strict prevents CSRF attacks\n- Logout immediately invalidates tokens by removing them from Redis and clearing cookies\n\n### Authentication Error Responses\n\n#### Missing Authentication\n```json\n{\n  \"translate_key\": \"error.token_required\",\n  \"error\": \"Authorization token is required\"\n}\n```\n\n#### Invalid Token Format\n```json\n{\n  \"translate_key\": \"error.invalid_token_format\", \n  \"error\": \"Token must be in format: Bearer \u003ctoken\u003e\"\n}\n```\n\n#### Expired Token\n```json\n{\n  \"translate_key\": \"error.token_expired\",\n  \"error\": \"Token has expired\"\n}\n```\n\n#### Insufficient Permissions\n```json\n{\n  \"translate_key\": \"error.insufficient_permissions\",\n  \"error\": \"Insufficient permissions for this operation\"\n}\n```\n\n**Common HTTP Status Codes:**\n- `401 Unauthorized`: Missing, invalid, or expired token\n- `403 Forbidden`: Token valid but insufficient permissions for the endpoint\n- `200 OK`: Successful authentication and authorized access\n\n## Security Features\n\n- Password fields are automatically excluded from JSON responses\n- Input validation on all endpoints\n- SQL injection prevention using parameterized queries\n- CORS support for cross-origin requests\n- Request logging middleware\n- Secure file upload with AWS S3 integration\n\n## Error Handling\n\nThe API returns consistent error responses:\n\n```json\n{\n  \"error\": \"Description of the error\"\n}\n```\n\nCommon HTTP status codes:\n- `200`: Success\n- `201`: Created\n- `400`: Bad Request (invalid input)\n- `404`: Not Found\n- `500`: Internal Server Error\n\n## Pagination\n\nList endpoints support pagination with query parameters:\n- `limit`: Number of items to return (default: 10, max: 100)\n- `offset`: Number of items to skip (default: 0)\n\nExample:\n```bash\nGET /api/v1/students?limit=20\u0026offset=40\n```\n\n## Web Application\n\nThe system includes a modern React/TypeScript web application providing a comprehensive admin interface:\n\n### Features\n- **Secure Authentication**: JWT-based login with automatic token management\n- **Admin Dashboard**: Real-time statistics and system overview with comprehensive entity breakdowns\n- **Multi-language Support**: English and Indonesian with automatic language detection\n- **Dark Mode**: System preference detection with manual toggle\n- **Responsive Design**: Mobile-first design that works on all devices\n- **Professional UI**: Clean, modern interface using Tailwind CSS\n- **State Management**: Persistent state management with Zustand\n- **Type Safety**: Full TypeScript support with comprehensive type definitions\n\n### Dashboard Statistics Display\nThe admin dashboard provides comprehensive real-time statistics:\n\n- **Entity Overview Cards**: Display total, active, and inactive counts for:\n  - Administrators with color-coded status indicators\n  - Teachers with active/inactive breakdown\n  - Students with enrollment status\n  - Total classes in the system\n\n- **Today's Attendance Summary**: Real-time attendance data showing:\n  - Total attendance records for today\n  - Present students count\n  - Absent students count  \n  - Late arrivals count\n\n- **Quick Actions**: Navigation shortcuts to manage:\n  - Teachers (add, edit, remove)\n  - Students (enrollment, management)\n  - Classes (creation, assignments)\n  - Attendance tracking\n\n### User Interface Features\n- **Navigation**: Sidebar navigation with route highlighting\n- **Theme Toggle**: Dark/light mode with system preference detection\n- **Language Toggle**: Switch between English and Indonesian\n- **Loading States**: Professional loading indicators and error handling\n- **Responsive Grid**: Adaptive layout for different screen sizes\n- **Accessibility**: ARIA labels and keyboard navigation support\n\n### Technical Implementation\n- **React 19**: Latest React with concurrent features\n- **TypeScript**: Full type safety with strict mode\n- **Tailwind CSS**: Utility-first CSS framework with custom design system\n- **i18next**: Internationalization with namespace support\n- **Zustand**: Lightweight state management with persistence\n- **React Hook Form**: Form handling with validation\n- **Custom Hooks**: Reusable hooks for theme and authentication\n\n### Getting Started with Web Application\n\n1. **Install dependencies**\n   ```bash\n   cd web\n   npm install\n   ```\n\n2. **Start development server**\n   ```bash\n   npm run dev\n   ```\n\n3. **Build for production**\n   ```bash\n   npm run build\n   ```\n\n4. **Access the application**\n   - Development: http://localhost:5173\n   - Login with admin credentials to access the dashboard\n\n### Environment Configuration\nThe web application automatically connects to the API at `http://localhost:8080/api/v1`. Update the API base URL in `web/src/services/api.ts` for different environments.\n\n### Authentication Flow\n1. Users select their account type (Admin, Teacher, Student)\n2. Enter appropriate credentials (email for admin, ID for teacher/student)\n3. System validates credentials and generates JWT token\n4. Token is stored securely and used for subsequent API calls\n5. Dashboard loads with personalized statistics and navigation\n\n### Student Attendance Homepage\nA dedicated public page for students to mark their daily attendance:\n\n**Features:**\n- **Public Access**: No admin authentication required - accessible at the root URL (`/`)\n- **Simple Authentication**: Students enter their Student ID and password\n- **One-Click Attendance**: Quick attendance marking with immediate confirmation\n- **Success Feedback**: Visual confirmation with student name and timestamp\n- **Multi-Student Support**: Ability to mark attendance for multiple students in sequence\n- **Responsive Design**: Works seamlessly on mobile devices and tablets\n- **Multilingual**: Supports both English and Indonesian interfaces\n- **Instructions**: Clear usage instructions for students\n- **Dashboard Access**: Direct navigation link to student login page for accessing the comprehensive student portal\n\n**Usage:**\n1. Navigate to the root URL of the application\n2. Enter Student ID (e.g., \"STU001\") and password\n3. Click \"Mark Attendance\" to record presence\n4. Receive confirmation with name and timestamp\n5. Option to mark attendance for another student or refresh\n\n**API Integration:**\n- Uses `/api/v1/attendance/mark` endpoint for attendance submission\n- Validates student credentials against the database\n- Automatically records attendance with \"present\" status\n- Returns student name and success confirmation\n\n### Student Dashboard Portal\nA comprehensive authenticated dashboard for students to manage their academic profile and track attendance:\n\n**Features:**\n- **Secure Authentication**: JWT-based login using Student ID and password\n- **Profile Management**: View and update personal information (name, email, phone)\n- **Password Management**: Self-service password updates with current password verification\n- **Attendance Statistics**: Real-time attendance tracking with percentage calculations\n- **Absent Request Management**: Create, view, and manage absence requests with status tracking\n- **Auto-Refresh Lists**: Absent request list automatically updates when new requests are submitted\n- **Responsive Interface**: Optimized for both desktop and mobile devices\n- **Real-Time Updates**: Live statistics and immediate feedback for all actions\n- **Multilingual Support**: Available in English and Indonesian\n\n**Dashboard Sections:**\n1. **Overview Tab**: \n   - Student ID and contact information display\n   - Attendance rate with visual percentage indicator\n   - Present and absent days counters\n   - Quick action buttons for common tasks\n\n2. **Profile Tab**:\n   - Personal information editor with validation\n   - Password update form with security requirements\n   - Real-time form validation and error handling\n\n3. **Absent Requests Tab**:\n   - Paginated list of all absence requests with status badges\n   - Create new absence requests with date and reason validation\n   - Real-time list updates when new requests are created (auto-refresh functionality)\n   - Delete pending requests (approved/rejected cannot be modified)\n   - Status tracking (Pending, Approved, Rejected) with color-coded indicators\n\n### Teacher Dashboard Portal\nA dedicated authenticated dashboard for teachers to manage their classes and review student requests:\n**Features:**\n- **Teacher Authentication**: JWT-based login using Teacher ID and password\n- **Profile Management**: View personal information, assigned classes, and teaching statistics\n- **Password Management**: Self-service password updates with security validation\n- **Class Management**: View assigned classes and total student counts\n- **Absent Request Processing**: Review, approve, or reject student absence requests\n- **Request Management**: Real-time list of pending, approved, and rejected requests\n- **Batch Actions**: Process multiple requests efficiently\n- **Student Information**: View detailed request information with student identification\n- **Status Tracking**: Complete audit trail of request decisions with timestamps\n- **Responsive Design**: Optimized interface for various screen sizes\n- **Multilingual Support**: Available in English and Indonesian\n**Dashboard Sections:**\n1. **Profile Tab**: \n   - Teacher ID and contact information display\n   - Assigned classes with student count statistics\n   - Pending requests counter and quick stats\n   - Professional information and status indicators\n2. **Password Tab**:\n   - Secure password update form with current password verification\n   - Password strength requirements and validation\n   - Real-time form validation and security feedback\n3. **Absent Requests Tab**:\n   - List all student absence requests from assigned classes\n   - Filter by status (pending, approved, rejected)\n   - Approve or reject requests with single-click actions\n   - View detailed request information with student context\n   - Real-time updates when actions are performed\n\n**Technical Implementation:**\n- **React Components**: Modular architecture with reusable components\n- **Form Validation**: Real-time validation using React Hook Form\n- **State Management**: Efficient state updates with callback patterns\n- **Error Handling**: Comprehensive error states with user-friendly messages\n- **Toast Notifications**: Success and error feedback for all operations\n- **Modal Dialogs**: Confirmation dialogs for destructive actions\n- **Pagination**: Efficient data loading for large datasets\n\n**Usage Flow:**\n1. Student logs in using their Student ID and password\n2. System redirects to the student dashboard upon successful authentication\n3. Dashboard displays personalized statistics and navigation tabs\n4. Students can update their profile, change passwords, and manage absent requests\n5. All changes are immediately reflected with toast notifications\n6. System maintains session state until logout or token expiration\n\n**Security Features:**\n- JWT token authentication for all API calls\n- Password updates require current password verification\n- Students can only access their own data\n- Secure logout with token invalidation\n- Client-side validation combined with server-side security\n\n## UI/UX Improvements\n\n### Enhanced Login Page Experience\nThe login page has been enhanced with improved navigation and user experience:\n\n**Features:**\n- **Smart Navigation**: Prominent \"Back to Attendance\" button in the top-left corner\n- **Consistent Design Language**: Navigation button uses the same styling as other interactive elements\n- **Multilingual Support**: Navigation button text supports both English (\"Back to Attendance\") and Indonesian (\"Kembali ke Absensi\")\n- **Accessibility**: Proper ARIA labels and keyboard navigation support\n- **Professional Styling**: Blue-themed button matching the application's design system\n- **Responsive Design**: Navigation adapts properly to mobile and desktop layouts\n\n**Navigation Flow:**\n1. Users accessing the login page can easily return to the attendance marking page\n2. Button uses hash navigation (`#/`) to return to the homepage\n3. Hover effects and focus states provide clear visual feedback\n4. Consistent with other navigation elements throughout the application\n\n**Design Consistency:**\n- Matches the styling of login links found on the student attendance homepage\n- Uses the application's primary blue color scheme\n- Follows the same spacing and typography conventions\n- Integrates seamlessly with the existing header layout (language and theme toggles)\n\n### User Experience Enhancements\n- **Intuitive Navigation**: Users can easily navigate between public attendance marking and authenticated dashboard access\n- **Clear Visual Hierarchy**: Important navigation elements are prominently displayed\n- **Consistent Interactions**: All navigation elements behave predictably across the application\n- **Mobile-Friendly**: All navigation improvements work seamlessly on mobile devices","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fmichaelwp%2Fstudent_attendances","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fmichaelwp%2Fstudent_attendances","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fmichaelwp%2Fstudent_attendances/lists"}