# Voter List API - Laravel Backend

A robust RESTful API built with Laravel 12 and MySQL for a mobile voter list application featuring user registration, admin approval workflow, and role-based access control.

## 🚀 Features

- **User Registration**: Email, phone number, and password-based registration
- **Admin Approval System**: New users require admin approval before accessing the system
- **Role-Based Access Control**: Separate admin and user roles with different permissions
- **Secure Authentication**: Token-based authentication using Laravel Sanctum
- **RESTful API**: Well-structured API endpoints following REST principles
- **MySQL Database**: Reliable data storage with proper migrations
- **Input Validation**: Comprehensive validation for all endpoints
- **Error Handling**: Consistent error responses across the API

## 📋 Requirements

- PHP >= 8.2
- Composer
- MySQL 5.7+ or MariaDB
- Laravel 12.x
- XAMPP (or any PHP/MySQL environment)

## 🛠️ Quick Setup

### Option 1: Using Setup Script (Recommended)

1. Open Command Prompt and navigate to the project directory:

```bash
cd "d:\xampp\htdocs\New folder\voter-list-api"
```

2. Ensure MySQL is running in XAMPP Control Panel

3. Create the database:
    - Open phpMyAdmin: http://localhost/phpmyadmin
    - Create a new database named: `voter_list`

4. Run the setup script:

```bash
setup.bat
```

5. Start the server:

```bash
php artisan serve
```

The API will be available at: `http://localhost:8000`

### Option 2: Manual Setup

```bash
# 1. Navigate to project directory
cd "d:\xampp\htdocs\New folder\voter-list-api"

# 2. Install dependencies
composer install

# 3. Generate application key
php artisan key:generate

# 4. Create database 'voter_list' in MySQL

# 5. Run migrations
php artisan migrate

# 6. Seed database (creates default admin user)
php artisan db:seed

# 7. Start development server
php artisan serve
```

## 👥 Default Users

After running the seeder (`php artisan db:seed`), you'll have:

### Admin User

- **Email**: `admin@voterlist.com`
- **Phone**: `+1234567890`
- **Password**: `admin123`
- **Role**: admin
- **Status**: Approved ✅

### Test User

- **Email**: `user@example.com`
- **Phone**: `+9876543210`
- **Password**: `user123`
- **Role**: user
- **Status**: Not Approved ❌

## 📚 API Documentation

Comprehensive API documentation is available in [`API_DOCUMENTATION.md`](API_DOCUMENTATION.md)

### Quick Reference

**Base URL**: `http://localhost:8000/api`

#### Public Endpoints

- `POST /register` - Register new user
- `POST /login` - User login

#### Protected Endpoints (Require Token)

- `GET /me` - Get current user info
- `POST /logout` - Logout user

#### Admin Endpoints (Require Admin Role)

- `GET /admin/users` - Get all users
- `GET /admin/users/pending` - Get pending approval users
- `POST /admin/users/{id}/approve` - Approve user
- `POST /admin/users/{id}/reject` - Reject user
- `DELETE /admin/users/{id}` - Delete user

#### User Endpoints (Require Approved Status)

- `GET /user/profile` - Get user profile
- `PUT /user/profile` - Update user profile

## 🧪 Testing with Postman

1. Import the Postman collection: `Voter_List_API.postman_collection.json`
2. The collection includes all API endpoints with example requests
3. Variables are automatically set for tokens after login

### Testing Flow

1. **Login as Admin**
    - Use the "Login Admin" request
    - Token is automatically saved

2. **Register New User**
    - Use "Register User" request
    - Note the user ID from response

3. **View Pending Users**
    - Use "Get Pending Users" request
    - See the newly registered user

4. **Approve User**
    - Use "Approve User" request with user ID
    - User can now login

5. **Login as User**
    - Use "Login User" request
    - Access user profile endpoints

## 📁 Project Structure

```
voter-list-api/
├── app/
│   ├── Http/
│   │   ├── Controllers/
│   │   │   ├── AuthController.php      # Authentication logic
│   │   │   ├── AdminController.php     # Admin operations
│   │   │   └── UserController.php      # User profile operations
│   │   └── Middleware/
│   │       ├── AdminMiddleware.php     # Admin role verification
│   │       └── ApprovedUserMiddleware.php # Approval status check
│   └── Models/
│       └── User.php                    # User model
├── config/
│   └── cors.php                        # CORS configuration
├── database/
│   ├── migrations/
│   │   └── 0001_01_01_000000_create_users_table.php
│   └── seeders/
│       └── DatabaseSeeder.php          # Default users seeder
├── routes/
│   └── api.php                         # API routes definition
├── .env                                # Environment configuration
├── API_DOCUMENTATION.md                # Detailed API docs
├── Voter_List_API.postman_collection.json # Postman collection
└── setup.bat                           # Quick setup script
```

## 🔐 Security Features

- ✅ Password hashing using bcrypt
- ✅ Token-based authentication (Laravel Sanctum)
- ✅ Role-based access control via middleware
- ✅ Approval status verification
- ✅ Input validation on all endpoints
- ✅ Protected admin routes
- ✅ CORS configuration for mobile apps
- ✅ SQL injection protection (Eloquent ORM)
- ✅ XSS protection

## 📱 Mobile App Integration Guide

### Authentication Flow

```
1. User registers via /api/register
   └─> Receives success message
   └─> Cannot login (not approved)

2. Admin approves user via /api/admin/users/{id}/approve
   └─> User status changes to approved

3. User logs in via /api/login
   └─> Receives authentication token
   └─> Store token securely (Keychain/Keystore)

4. User accesses protected endpoints
   └─> Include: Authorization: Bearer {token}
```

### Token Management

**iOS (Swift)**:

```swift
// Store token in Keychain
let token = response.token
KeychainWrapper.standard.set(token, forKey: "authToken")
```

**Android (Kotlin)**:

```kotlin
// Store token in SharedPreferences (use EncryptedSharedPreferences)
val sharedPref = getSharedPreferences("app_prefs", Context.MODE_PRIVATE)
sharedPref.edit().putString("auth_token", token).apply()
```

**Making API Calls**:

```
Authorization: Bearer {stored_token}
Content-Type: application/json
```

## 🔧 Configuration

### Database Configuration

Edit `.env` file:

```env
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=voter_list
DB_USERNAME=root
DB_PASSWORD=
```

### CORS Configuration

CORS is configured to allow all origins for development. For production, update `config/cors.php`:

```php
'allowed_origins' => ['https://your-mobile-app-domain.com'],
```

## 🐛 Troubleshooting

### Issue: "Class 'Laravel\Sanctum\HasApiTokens' not found"

**Solution**: Run `composer install` or `composer require laravel/sanctum`

### Issue: MySQL connection refused

**Solution**:

1. Start MySQL in XAMPP Control Panel
2. Verify database credentials in `.env`
3. Ensure database `voter_list` exists

### Issue: 500 Internal Server Error

**Solution**:

1. Check `storage/logs/laravel.log`
2. Run `php artisan config:clear`
3. Ensure proper permissions on `storage/` folder

### Issue: Token not working

**Solution**:

1. Ensure header format: `Authorization: Bearer {token}`
2. Verify token hasn't been revoked via logout
3. Check if user is approved

## 📝 Development Commands

```bash
# Clear all cache
php artisan cache:clear
php artisan config:clear
php artisan route:clear

# View all routes
php artisan route:list

# Create new migration
php artisan make:migration create_table_name

# Rollback last migration
php artisan migrate:rollback

# Fresh migration with seed
php artisan migrate:fresh --seed

# Run code formatter
./vendor/bin/pint
```

## 🚀 Deployment

### Production Checklist

- [ ] Change `APP_ENV=production` in `.env`
- [ ] Set `APP_DEBUG=false`
- [ ] Generate new `APP_KEY`
- [ ] Update CORS allowed origins
- [ ] Configure proper database credentials
- [ ] Set up SSL certificate (HTTPS)
- [ ] Enable rate limiting
- [ ] Set up backup system
- [ ] Configure logging
- [ ] Optimize autoloader: `composer install --optimize-autoloader --no-dev`
- [ ] Cache configuration: `php artisan config:cache`
- [ ] Cache routes: `php artisan route:cache`

## 📄 License

This project is open-sourced software licensed under the MIT license.

## 👨‍💻 Support

For issues, questions, or contributions:

1. Check the [API_DOCUMENTATION.md](API_DOCUMENTATION.md)
2. Review troubleshooting section
3. Create an issue with detailed information

## 🎯 Future Enhancements

- [ ] Email verification
- [ ] Forgot password functionality
- [ ] User profile photos
- [ ] Pagination for user lists
- [ ] Advanced search and filtering
- [ ] Activity logs
- [ ] Rate limiting
- [ ] API versioning
- [ ] Unit and feature tests
- [ ] API response caching

---

**Built with ❤️ using Laravel 12**
