# Admin API Documentation

Base URL: `{{HOST}}/api/admin`

## Authentication

All protected endpoints require a JWT Bearer token in the Authorization header:
```
Authorization: Bearer {token}
```

---

## Public Endpoints (No Authentication Required)

### 1. Admin Login
**Endpoint:** `POST /admin/login`

**Description:** Authenticate admin user and receive JWT token

**Request Body:**
```json
{
  "email": "admin@drjobs.com",
  "password": "admin123"
}
```

**Validation Rules:**
- `email`: required, valid email format
- `password`: required, string, minimum 6 characters

**Success Response (200):**
```json
{
  "status": 200,
  "message": "Login successful",
  "data": {
    "admin": {
      "id": "6944fd88eeafd24f780cf692",
      "name": "Super Admin",
      "email": "admin@drjobs.com",
      "phone": "+971501234567",
      "profile_image": null,
      "user_type": "admin"
    },
    "token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9..."
  }
}
```

**Error Responses:**

- **401 Unauthorized - Invalid Credentials:**
```json
{
  "status": 401,
  "message": "Invalid credentials"
}
```

- **403 Forbidden - Account Deactivated:**
```json
{
  "status": 403,
  "message": "Your account has been deactivated"
}
```

- **422 Validation Failed:**
```json
{
  "status": 422,
  "message": "Validation failed",
  "data": {
    "errors": {
      "email": ["The email field is required."],
      "password": ["The password must be at least 6 characters."]
    }
  }
}
```

---

### 2. Forgot Password
**Endpoint:** `POST /admin/forgot-password`

**Description:** Request password reset link via email

**Request Body:**
```json
{
  "email": "admin@drjobs.com"
}
```

**Validation Rules:**
- `email`: required, valid email format

**Success Response (200):**
```json
{
  "status": 200,
  "message": "Password reset link sent to your email",
  "data": {
    "reset_token": "abc123def456..." // For development only
  }
}
```

**Error Responses:**

- **404 Not Found:**
```json
{
  "status": 404,
  "message": "Admin not found with this email"
}
```

**Notes:**
- Reset token is valid for 1 hour
- Email contains reset link: `{admin_frontend_url}/reset-password?token={reset_token}`

---

### 3. Reset Password
**Endpoint:** `POST /admin/reset-password`

**Description:** Reset password using token from email

**Request Body:**
```json
{
  "token": "abc123def456...",
  "password": "newpassword123",
  "password_confirmation": "newpassword123"
}
```

**Validation Rules:**
- `token`: required, string
- `password`: required, string, minimum 6 characters, must match confirmation
- `password_confirmation`: required

**Success Response (200):**
```json
{
  "status": 200,
  "message": "Password reset successfully"
}
```

**Error Responses:**

- **404 Invalid Token:**
```json
{
  "status": 404,
  "message": "Invalid reset token"
}
```

- **400 Token Expired:**
```json
{
  "status": 400,
  "message": "Reset token has expired"
}
```

---

## Protected Endpoints (Authentication Required)

### 4. Get Admin Profile
**Endpoint:** `GET /admin/profile`

**Description:** Get current authenticated admin's profile details

**Headers:**
```
Authorization: Bearer {token}
```

**Success Response (200):**
```json
{
  "status": 200,
  "message": "Profile retrieved successfully",
  "data": {
    "admin": {
      "id": "6944fd88eeafd24f780cf692",
      "name": "Super Admin",
      "email": "admin@drjobs.com",
      "phone": "+971501234567",
      "address": "Dubai, UAE",
      "profile_image": "admin_photos/1766129806_admin_6944fd88eeafd24f780cf692.jpg",
      "user_type": "admin",
      "status": 1,
      "last_login_at": "2025-12-19T07:30:46.504000Z",
      "created_at": "2025-12-19T07:23:52.340000Z"
    }
  }
}
```

**Error Responses:**

- **401 Unauthorized:**
```json
{
  "error": "Unauthorized",
  "message": "JWT Bearer token not provided"
}
```

---

### 5. Update Admin Profile
**Endpoint:** `POST /admin/update-profile`

**Description:** Update admin profile information (except password and email)

**Headers:**
```
Authorization: Bearer {token}
Content-Type: application/json
```

**Request Body:**
```json
{
  "name": "Super Admin Updated",
  "phone": "+971509876543",
  "address": "Abu Dhabi, UAE",
  "password": "admin123"
}
```

**Validation Rules:**
- `name`: optional, string, max 255 characters
- `phone`: optional, string, max 20 characters
- `address`: optional, string
- `profile_image`: optional, string (path to image)

**Success Response (200):**
```json
{
  "status": 200,
  "message": "Profile updated successfully",
  "data": {
    "admin": {
      "id": "6944fd88eeafd24f780cf692",
      "name": "Super Admin Updated",
      "email": "admin@drjobs.com",
      "phone": "+971509876543",
      "address": "Abu Dhabi, UAE",
      "profile_image": "admin_photos/image_path.jpg"
    }
  }
}
```

**Notes:**
- All fields are optional - send only the fields you want to update
- Email cannot be updated through this endpoint

---

### 6. Upload Profile Image
**Endpoint:** `POST /admin/upload-profile-image`

**Description:** Upload admin profile image (file upload)

**Headers:**
```
Authorization: Bearer {token}
Content-Type: multipart/form-data
```

**Request Body (Form Data):**
- `profile_image`: File (required)

**Validation Rules:**
- `profile_image`: required, file, formats: jpeg/jpg/png/gif, max size: 2MB

**Success Response (200):**
```json
{
  "status": 200,
  "message": "Profile image uploaded successfully",
  "data": {
    "admin": {
      "id": "6944fd88eeafd24f780cf692",
      "name": "Super Admin",
      "email": "admin@drjobs.com",
      "profile_image": "admin_photos/1766129806_admin_6944fd88eeafd24f780cf692.jpg"
    },
    "profile_image_url": "http://localhost:8000/storage/admin_photos/1766129806_admin_6944fd88eeafd24f780cf692.jpg"
  }
}
```

**Error Responses:**

- **422 Validation Failed:**
```json
{
  "status": 422,
  "message": "Validation failed",
  "data": {
    "errors": {
      "profile_image": ["The profile image must be a file of type: jpeg, jpg, png, gif."]
    }
  }
}
```

**Notes:**
- Old profile image is automatically deleted when uploading new one
- Image is stored in: `storage/app/public/admin_photos/`
- Filename format: `{timestamp}_admin_{admin_id}.{extension}`

**cURL Example:**
```bash
curl -X POST {{HOST}}/api/admin/upload-profile-image \
  -H "Authorization: Bearer {token}" \
  -F "profile_image=@/path/to/image.jpg"
```

---

### 7. Change Password
**Endpoint:** `POST /admin/change-password`

**Description:** Change admin password (requires current password)

**Headers:**
```
Authorization: Bearer {token}
Content-Type: application/json
```

**Request Body:**
```json
{
  "current_password": "admin123",
  "new_password": "newpassword123",
  "new_password_confirmation": "newpassword123"
}
```

**Validation Rules:**
- `current_password`: required, string
- `new_password`: required, string, minimum 6 characters, must match confirmation
- `new_password_confirmation`: required

**Success Response (200):**
```json
{
  "status": 200,
  "message": "Password changed successfully"
}
```

**Error Responses:**

- **401 Incorrect Current Password:**
```json
{
  "status": 401,
  "message": "Current password is incorrect"
}
```

- **422 Validation Failed:**
```json
{
  "status": 422,
  "message": "Validation failed",
  "data": {
    "errors": {
      "new_password": ["The new password confirmation does not match."]
    }
  }
}
```

---

### 8. Logout
**Endpoint:** `POST /admin/logout`

**Description:** Logout admin user (invalidate token)

**Headers:**
```
Authorization: Bearer {token}
```

**Success Response (200):**
```json
{
  "status": 200,
  "message": "Logged out successfully"
}
```

**Notes:**
- Token invalidation is currently handled on the frontend
- Backend endpoint provided for future token blacklisting implementation

---

## Error Responses

### Common Authentication Errors

**401 Unauthorized - No Token:**
```json
{
  "error": "Unauthorized",
  "message": "JWT Bearer token not provided"
}
```

**401 Unauthorized - Invalid Token:**
```json
{
  "error": "Unauthorized",
  "message": "Invalid or expired JWT token"
}
```

**403 Forbidden - Not Admin:**
```json
{
  "error": "Unauthorized",
  "message": "Access denied. Admin privileges required."
}
```

**403 Forbidden - Deactivated Account:**
```json
{
  "error": "Forbidden",
  "message": "Your account has been deactivated"
}
```

### Server Error

**500 Internal Server Error:**
```json
{
  "status": 500,
  "message": "Internal server error",
  "data": {
    "error": "Error message details"
  }
}
```

---

## Admin Model Schema

```javascript
{
  "_id": "ObjectId",
  "id": "string (unique)",
  "name": "string",
  "email": "string (unique)",
  "phone": "string",
  "address": "string",
  "profile_image": "string (path)",
  "password": "string (hashed)",
  "user_type": "admin",
  "status": 1, // 1 = active, 0 = inactive
  "last_login_at": "datetime",
  "reset_token": "string (nullable)",
  "reset_token_expires_at": "datetime (nullable)",
  "created_at": "datetime",
  "updated_at": "datetime"
}
```

---

## Default Admin Credentials

**Email:** `admin@drjobs.com`  
**Password:** `admin123`

**Note:** Change password immediately after first login in production environment.

---

## JWT Token Details

**Token Type:** JWT (JSON Web Token)  
**Algorithm:** HS256  
**Expiration:** 7 days (604800 seconds)  
**Secret Key:** Configured in `.env` as `JWT_SECRET`

**Token Payload:**
```json
{
  "user_id": "6944fd88eeafd24f780cf692",
  "email": "admin@drjobs.com",
  "name": "Super Admin",
  "user_type": "admin",
  "iat": 1766129371,
  "exp": 1797665371,
  "nbf": 1766129371
}
```

---

## Complete API Endpoint Summary

| Method | Endpoint | Auth Required | Description |
|--------|----------|---------------|-------------|
| POST | `/admin/login` | ❌ No | Admin login |
| POST | `/admin/forgot-password` | ❌ No | Request password reset |
| POST | `/admin/reset-password` | ❌ No | Reset password with token |
| GET | `/admin/profile` | ✅ Yes | Get admin profile |
| POST | `/admin/update-profile` | ✅ Yes | Update profile info |
| POST | `/admin/upload-profile-image` | ✅ Yes | Upload profile image |
| POST | `/admin/change-password` | ✅ Yes | Change password |
| POST | `/admin/logout` | ✅ Yes | Logout admin |

---

## Postman Collection Example

### Environment Variables
```json
{
  "HOST": "http://localhost:8000",
  "ADMIN_TOKEN": ""
}
```

### Login Request
```
POST {{HOST}}/api/admin/login
Content-Type: application/json

{
  "email": "admin@drjobs.com",
  "password": "admin123"
}
```

### Get Profile (with token)
```
GET {{HOST}}/api/admin/profile
Authorization: Bearer {{ADMIN_TOKEN}}
```

---

## Notes for Frontend Integration

1. **Store JWT Token Securely:**
   - Use httpOnly cookies or secure localStorage
   - Never expose token in URL parameters

2. **Token Refresh:**
   - Current implementation: 7-day expiration
   - Re-login required after expiration
   - Consider implementing refresh token mechanism for production

3. **Error Handling:**
   - Handle 401 errors → redirect to login
   - Handle 403 errors → show access denied message
   - Handle 422 errors → display validation errors to user

4. **File Upload:**
   - Use `multipart/form-data` for profile image upload
   - Display image preview before upload
   - Show upload progress indicator

5. **Password Requirements:**
   - Minimum 6 characters
   - Consider enforcing stronger password policy in production

---

## Security Considerations

1. **HTTPS Required:** Always use HTTPS in production
2. **CORS Configuration:** Configure allowed origins properly
3. **Rate Limiting:** Implement rate limiting on login endpoint
4. **Password Hashing:** Passwords are auto-hashed using bcrypt
5. **Token Expiration:** Tokens expire after 7 days
6. **File Upload Security:** Only allowed image formats, max 2MB
7. **SQL Injection Prevention:** Using MongoDB Eloquent ORM
8. **XSS Prevention:** Sanitize all user inputs

---

## Testing Examples

### Using cURL

**Login:**
```bash
curl -X POST http://localhost:8000/api/admin/login \
  -H "Content-Type: application/json" \
  -d '{"email":"admin@drjobs.com","password":"admin123"}'
```

**Get Profile:**
```bash
curl -X GET http://localhost:8000/api/admin/profile \
  -H "Authorization: Bearer YOUR_TOKEN_HERE"
```

**Update Profile:**
```bash
curl -X POST http://localhost:8000/api/admin/update-profile \
  -H "Authorization: Bearer YOUR_TOKEN_HERE" \
  -H "Content-Type: application/json" \
  -d '{"name":"Admin Updated","phone":"+971501234567"}'
```

**Upload Profile Image:**
```bash
curl -X POST http://localhost:8000/api/admin/upload-profile-image \
  -H "Authorization: Bearer YOUR_TOKEN_HERE" \
  -F "profile_image=@/path/to/image.jpg"
```

**Change Password:**
```bash
curl -X POST http://localhost:8000/api/admin/change-password \
  -H "Authorization: Bearer YOUR_TOKEN_HERE" \
  -H "Content-Type: application/json" \
  -d '{
    "current_password":"admin123",
    "new_password":"newpass123",
    "new_password_confirmation":"newpass123"
  }'
```

---

## Support

For issues or questions regarding the Admin API:
- Repository: drjob-cv-parsing-api
- Branch: dreamztech
- Contact: Development Team

---

**Last Updated:** December 19, 2025
