# DadyCar Auth Service

> JWT-based Authentication & Authorization Microservice for DadyCar Fleet Management System

A Laravel 12 microservice providing secure authentication, role-based authorization, and multi-tenant user management for the DadyCar ecosystem.

## 🚀 Features

- **JWT Authentication** - Secure token-based authentication with refresh tokens
- **Multi-Tenant Architecture** - Company-based user isolation
- **Hierarchical Permissions** - Module → Feature → Permission structure
- **Role-Based Access Control** - Flexible role and permission management
- **Session Management** - Track and manage user sessions
- **RESTful API** - Clean, versioned API design
- **Comprehensive Documentation** - Detailed guides and examples

## 📚 Documentation

### Quick Access

- **[📖 Quick Start Guide](docs/QUICK_START.md)** - Get up and running in 5 minutes
- **[📘 Complete API Documentation](docs/API_DOCUMENTATION.md)** - Comprehensive reference
- **[📂 Documentation Index](docs/README.md)** - All documentation

### What's Included

- Architecture overview
- All API endpoints with examples
- Authentication flow diagrams
- Permission system details
- Multi-tenant architecture guide
- Integration examples for main applications
- Security best practices
- Troubleshooting guide
- Code examples (PHP, JavaScript)

## 🎯 Quick Start

### Prerequisites

- PHP 8.2+
- Composer
- MySQL 8.0+ or PostgreSQL 13+

### Installation

```bash
# 1. Install dependencies
composer install

# 2. Configure environment
cp .env.example .env
php artisan key:generate
php artisan jwt:secret

# 3. Configure database in .env
DB_CONNECTION=mysql
DB_DATABASE=dadycar_auth
DB_USERNAME=root
DB_PASSWORD=

# 4. Run migrations
php artisan migrate
php artisan db:seed --class=ModuleSeeder

# 5. Create test data (optional)
php artisan db:seed --class=TestDataSeeder

# 6. Start server
php artisan serve
```

Server will run at `http://localhost:8000`

### Verify Installation

```bash
curl http://localhost:8000/api/v1/health
```

Expected response:
```json
{
  "status": "ok",
  "service": "auth-service",
  "timestamp": "2025-10-04T10:30:00Z"
}
```

## 🔑 Quick Example

### Login

```bash
curl -X POST http://localhost:8000/api/v1/auth/login \
  -H "Content-Type: application/json" \
  -d '{
    "email": "admin@test.com",
    "password": "password",
    "company_slug": "test-company"
  }'
```

### Use Token

```bash
curl http://localhost:8000/api/v1/auth/me \
  -H "Authorization: Bearer YOUR_ACCESS_TOKEN"
```

### Check Permission

```bash
curl -X POST http://localhost:8000/api/v1/auth/check-permission \
  -H "Authorization: Bearer YOUR_ACCESS_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "permission": "view_vehicles",
    "resource": "vehicles"
  }'
```

## 🏗️ Architecture

### Repository Pattern with Service Layer

```
Controller → Service → Repository → Model → Database
```

### Permission Hierarchy

```
Module (e.g., "Vehicle Management")
  └── Feature (e.g., "Vehicle Operations")
      └── Permission (e.g., "view_vehicles")
```

### Multi-Tenant Design

- Users belong to a company
- Login requires email + password + company_slug
- All data is company-scoped
- JWT includes company context

## 📋 Key API Endpoints

### Authentication

- `POST /api/v1/auth/login` - Login user
- `POST /api/v1/auth/logout` - Logout user
- `POST /api/v1/auth/refresh` - Refresh tokens
- `GET /api/v1/auth/me` - Get current user
- `POST /api/v1/auth/check-permission` - Check permission

### Resources

- `/api/v1/companies` - Company management
- `/api/v1/users` - User management
- `/api/v1/roles` - Role management
- `/api/v1/permissions` - Permission listing
- `/api/v1/modules` - Module listing
- `/api/v1/features` - Feature listing

> **See full endpoint documentation**: [API Reference](docs/API_DOCUMENTATION.md#api-reference)

## 🔌 Integration

### For Main Application

```php
// 1. Add to config/services.php
'auth' => [
    'url' => env('AUTH_SERVICE_URL', 'http://localhost:8000'),
],

// 2. Create service client
use Illuminate\Support\Facades\Http;

class AuthService {
    public function login($email, $password, $companySlug) {
        return Http::post(config('services.auth.url') . '/api/v1/auth/login', [
            'email' => $email,
            'password' => $password,
            'company_slug' => $companySlug,
        ]);
    }

    public function checkPermission($token, $permissionCode, $resource = null) {
        $response = Http::withToken($token)
            ->post(config('services.auth.url') . '/api/v1/auth/check-permission', [
                'permission' => $permissionCode,
                'resource' => $resource,
            ]);

        return $response->json('data.has_permission', false);
    }
}

// 3. Use in your controllers
public function index(Request $request) {
    $token = $request->bearerToken();

    if (!$this->authService->checkPermission($token, 'view_vehicles', 'vehicles')) {
        abort(403, 'Forbidden');
    }

    // Your logic here...
}
```

> **See complete integration guide**: [Integration Guide](docs/API_DOCUMENTATION.md#integration-guide)

## 🧪 Development

### Run Development Server

```bash
composer dev  # Runs server + queue + logs + vite
# OR
php artisan serve
```

### Run Tests

```bash
composer test
# OR
php artisan test
```

### Code Quality

```bash
./vendor/bin/pint  # Format code
php artisan config:clear  # Clear config cache
php artisan cache:clear  # Clear application cache
```

### Database

```bash
php artisan migrate:fresh --seed  # Reset database
php artisan db:seed --class=ModuleSeeder  # Seed permissions only
php artisan db:seed --class=TestDataSeeder  # Seed test data
```

## 🔒 Security

### Best Practices Implemented

- ✅ JWT token authentication
- ✅ Refresh token rotation
- ✅ Token blacklisting on logout
- ✅ Session tracking
- ✅ Password hashing (bcrypt)
- ✅ Input validation
- ✅ CORS protection
- ✅ Rate limiting on auth endpoints

### Configuration

```env
JWT_SECRET=your-secret-key
JWT_TTL=60  # Access token: 1 hour
JWT_REFRESH_TTL=43200  # Refresh token: 30 days
JWT_ALGO=HS256
```

> **See security guide**: [Security Best Practices](docs/API_DOCUMENTATION.md#security-best-practices)

## 📊 Tech Stack

- **Framework**: Laravel 12
- **Authentication**: tymon/jwt-auth
- **Database**: MySQL/PostgreSQL
- **Cache**: Redis (optional)
- **PHP**: 8.2+

## 🗂️ Project Structure

```
app/
├── Http/
│   ├── Controllers/Api/     # API controllers
│   ├── Middleware/          # Custom middleware
│   ├── Requests/            # Form requests
│   ├── Resources/           # API resources
│   └── Traits/              # Shared traits
├── Models/                  # Eloquent models
├── Services/                # Business logic
├── Repositories/            # Data access layer
└── Contracts/               # Interfaces

database/
├── migrations/              # Database migrations
└── seeders/                 # Database seeders

docs/                        # Documentation
├── API_DOCUMENTATION.md     # Complete API docs
├── QUICK_START.md          # Quick start guide
└── README.md               # Documentation index
```

## 🔧 Configuration

### Environment Variables

Key variables to configure:

```env
# Application
APP_ENV=production
APP_DEBUG=false
APP_URL=https://auth.dadycar.com

# Database
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_DATABASE=dadycar_auth

# JWT
JWT_SECRET=your-secret-key
JWT_TTL=60
JWT_REFRESH_TTL=43200

# CORS
CORS_ALLOWED_ORIGINS=https://app.dadycar.com
```

## 📈 Performance

- **Caching**: Permission checks cached for 5 minutes
- **Stateless**: JWT allows horizontal scaling
- **Optimized Queries**: Eager loading relationships
- **Queue Support**: Background job processing

## 🐛 Troubleshooting

### Common Issues

**Token Expired**
```php
// Use refresh token
POST /api/v1/auth/refresh
{ "refresh_token": "..." }
```

**Permission Denied**
```bash
# Check user permissions
GET /api/v1/users/{user_id}/permissions
```

**Company Not Found**
```bash
# Verify company slug
GET /api/v1/companies?search={slug}
```

> **See full troubleshooting guide**: [Troubleshooting](docs/API_DOCUMENTATION.md#troubleshooting)

## 📝 Development Commands

```bash
# Development
composer dev                              # Run dev server + queue + logs
php artisan serve                         # Dev server only
php artisan queue:listen                  # Queue worker
php artisan pail                          # Tail logs

# Testing
composer test                             # Run tests
php artisan test --filter=TestName        # Specific test

# Database
php artisan migrate                       # Run migrations
php artisan migrate:fresh --seed          # Fresh DB with seeds

# Code Quality
./vendor/bin/pint                         # Format code
```

## 🤝 Contributing

1. Follow Laravel coding standards
2. Run tests before committing: `composer test`
3. Format code: `./vendor/bin/pint`
4. Update documentation for API changes

## 📜 License

Copyright © 2025 DadyCar. All rights reserved.

---

## 🆘 Support & Resources

- **Documentation**: [docs/](docs/)
- **Quick Start**: [docs/QUICK_START.md](docs/QUICK_START.md)
- **API Reference**: [docs/API_DOCUMENTATION.md](docs/API_DOCUMENTATION.md)
- **Issues**: Create an issue in the repository

---

Built with ❤️ using Laravel
