# API Authentication Guide - Hướng dẫn API Xác thực

## Tổng quan
API sử dụng Laravel Passport để xác thực với Bearer Token. Người dùng đăng nhập bằng `ten_dang_nhap` và `mat_khau`, sau đó nhận token để truy cập các endpoint được bảo vệ.

## Endpoints

### 1. Đăng nhập (Login)
**POST** `/api/auth/login`

**Request Body:**
```json
{
    "ten_dang_nhap": "admin",
    "mat_khau": "password123"
}
```

**Response Success (200):**
```json
{
    "success": true,
    "message": "Đăng nhập thành công",
    "data": {
        "token": "eyJ0eXAiOiJKV1QiLCJhbGc...",
        "token_type": "Bearer",
        "user": {
            "id": 1,
            "ten_dang_nhap": "admin",
            "ho_ten": "Quản trị viên",
            "email": "admin@example.com",
            "don_vi_id": 1,
            "ngay_tao": "2024-01-01T00:00:00.000000Z",
            "ngay_cap_nhat": "2024-01-01T00:00:00.000000Z"
        }
    }
}
```

**Response Error (422):**
```json
{
    "message": "The given data was invalid.",
    "errors": {
        "ten_dang_nhap": [
            "Tên đăng nhập hoặc mật khẩu không chính xác."
        ]
    }
}
```

**cURL Example:**
```bash
curl -X POST http://localhost:8000/api/auth/login \
  -H "Content-Type: application/json" \
  -H "Accept: application/json" \
  -d '{
    "ten_dang_nhap": "admin",
    "mat_khau": "password123"
  }'
```

---

### 2. Lấy thông tin người dùng (Get User Info)
**GET** `/api/auth/user`

**Headers:**
```
Authorization: Bearer {token}
Accept: application/json
```

**Response Success (200):**
```json
{
    "success": true,
    "data": {
        "id": 1,
        "ten_dang_nhap": "admin",
        "ho_ten": "Quản trị viên",
        "email": "admin@example.com",
        "don_vi_id": 1,
        "ngay_tao": "2024-01-01T00:00:00.000000Z",
        "ngay_cap_nhat": "2024-01-01T00:00:00.000000Z"
    }
}
```

**Response Error (401):**
```json
{
    "message": "Unauthenticated."
}
```

**cURL Example:**
```bash
curl -X GET http://localhost:8000/api/auth/user \
  -H "Authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGc..." \
  -H "Accept: application/json"
```

---

### 3. Đăng xuất (Logout)
**POST** `/api/auth/logout`

**Headers:**
```
Authorization: Bearer {token}
Accept: application/json
```

**Response Success (200):**
```json
{
    "success": true,
    "message": "Đăng xuất thành công"
}
```

**cURL Example:**
```bash
curl -X POST http://localhost:8000/api/auth/logout \
  -H "Authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGc..." \
  -H "Accept: application/json"
```

---

## Cách sử dụng Token

### 1. Lưu token sau khi đăng nhập
```javascript
// JavaScript/Frontend
const response = await fetch('/api/auth/login', {
    method: 'POST',
    headers: {
        'Content-Type': 'application/json',
        'Accept': 'application/json'
    },
    body: JSON.stringify({
        ten_dang_nhap: 'admin',
        mat_khau: 'password123'
    })
});

const data = await response.json();
const token = data.data.token;

// Lưu token vào localStorage hoặc sessionStorage
localStorage.setItem('auth_token', token);
```

### 2. Sử dụng token cho các request tiếp theo
```javascript
// JavaScript/Frontend
const token = localStorage.getItem('auth_token');

const response = await fetch('/api/auth/user', {
    method: 'GET',
    headers: {
        'Authorization': `Bearer ${token}`,
        'Accept': 'application/json'
    }
});
```

### 3. PHP/Laravel Client
```php
use Illuminate\Support\Facades\Http;

$response = Http::withHeaders([
    'Authorization' => 'Bearer ' . $token,
    'Accept' => 'application/json',
])->get('http://localhost:8000/api/auth/user');

$userData = $response->json();
```

---

## Testing với Postman

### 1. Login Request
1. Method: POST
2. URL: `http://localhost:8000/api/auth/login`
3. Headers:
   - `Content-Type: application/json`
   - `Accept: application/json`
4. Body (raw JSON):
```json
{
    "ten_dang_nhap": "admin",
    "mat_khau": "password123"
}
```
5. Send → Copy token từ response

### 2. Get User Request
1. Method: GET
2. URL: `http://localhost:8000/api/auth/user`
3. Headers:
   - `Authorization: Bearer {paste_token_here}`
   - `Accept: application/json`
4. Send

### 3. Logout Request
1. Method: POST
2. URL: `http://localhost:8000/api/auth/logout`
3. Headers:
   - `Authorization: Bearer {paste_token_here}`
   - `Accept: application/json`
4. Send

---

## Các bước Setup

### 1. Chạy Migration
```bash
php artisan migrate
```

### 2. Cài đặt Laravel Passport
```bash
php artisan passport:install
```

### 3. Tạo user test
```bash
php artisan tinker
```

Trong tinker:
```php
use App\Models\User;
use Illuminate\Support\Facades\Hash;

User::create([
    'ten_dang_nhap' => 'admin',
    'mat_khau' => Hash::make('password123'),
    'ho_ten' => 'Quản trị viên',
    'email' => 'admin@example.com',
    'don_vi_id' => 1,
]);
```

### 4. Khởi động server
```bash
php artisan serve
```

---

## Error Handling

### Common Errors:

1. **401 Unauthenticated**
   - Token không hợp lệ hoặc đã hết hạn
   - Giải pháp: Đăng nhập lại để lấy token mới

2. **422 Validation Error**
   - Dữ liệu đầu vào không hợp lệ
   - Kiểm tra lại `ten_dang_nhap` và `mat_khau`

3. **500 Internal Server Error**
   - Lỗi server
   - Kiểm tra log: `storage/logs/laravel.log`

---

## Security Best Practices

1. **HTTPS**: Luôn sử dụng HTTPS trong production
2. **Token Storage**: 
   - Frontend: Lưu trong httpOnly cookie hoặc secure storage
   - Mobile: Sử dụng secure storage (Keychain/Keystore)
3. **Token Expiration**: Cấu hình thời gian hết hạn token trong `config/passport.php`
4. **Rate Limiting**: Thêm throttle middleware cho login endpoint
5. **CORS**: Cấu hình CORS đúng cách trong `config/cors.php`

---

## Troubleshooting

### Token không hoạt động?
```bash
# Clear cache
php artisan config:clear
php artisan cache:clear

# Reinstall Passport
php artisan passport:install --force
```

### Database connection error?
```bash
# Kiểm tra .env file
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=your_database
DB_USERNAME=your_username
DB_PASSWORD=your_password
