# Google Authentication API Documentation

## Overview
API untuk autentikasi menggunakan Google OAuth di sistem Rikod Lite.

## 🔑 Credentials & Setup

### Backend (Laravel)
**❌ TIDAK PERLU Google Credentials di backend**

Implementasi ini menggunakan **Client-Side Authentication**:
- Frontend/App yang handle Google OAuth
- Backend hanya menerima data user yang sudah terautentikasi
- Tidak perlu setup Laravel Socialite
- Tidak perlu Google Client ID/Secret di backend

### Frontend/Mobile App
**✅ PERLU Google Client ID di app**

Setup yang dibutuhkan di app:

**1. Untuk Android:**
```
- Download google-services.json dari Google Console
- Tambahkan Google Sign-In dependency
- Konfigurasi OAuth 2.0 Client ID (Android)
```

**2. Untuk iOS:**
```
- Download GoogleService-Info.plist dari Google Console
- Tambahkan Google Sign-In SDK
- Konfigurasi OAuth 2.0 Client ID (iOS)
```

**3. Untuk Web/React:**
```javascript
// Install: npm install @react-oauth/google
import { GoogleOAuthProvider, GoogleLogin } from '@react-oauth/google';

<GoogleOAuthProvider clientId="YOUR_GOOGLE_CLIENT_ID">
  <GoogleLogin
    onSuccess={credentialResponse => {
      // Decode JWT token dan kirim ke backend
    }}
  />
</GoogleOAuthProvider>
```

**Cara dapatkan Google Client ID:**
1. Buka [Google Cloud Console](https://console.cloud.google.com)
2. Create project baru atau pilih existing
3. Enable Google+ API
4. Credentials → Create OAuth 2.0 Client ID
5. Pilih platform (Android/iOS/Web)
6. Copy Client ID untuk digunakan di app

## Implementasi Baru

### 1. Signup with Google

**Endpoint:** `POST /api/signupWithGoogle`

**Description:** Membuat akun baru menggunakan Google authentication

**Request Body:**
```json
{
  "user_name": "John Doe",
  "user_email": "john.doe@gmail.com",
  "google_id": "1234567890",
  "user_photo": "https://lh3.googleusercontent.com/...",
  "user_telp": "+60123456789",
  "user_address": "Kuala Lumpur, Malaysia",
  "user_birthdate": "1990-01-01",
  "user_gender": "MALE"
}
```

**Required Fields:**
- `user_name` (string) - Nama lengkap user
- `user_email` (string) - Email dari Google account (harus unique)

**Optional Fields:**
- `google_id` (string) - Google User ID
- `user_photo` (string) - URL foto profile dari Google
- `user_telp` (string) - Nomor telepon
- `user_address` (string) - Alamat
- `user_birthdate` (date) - Tanggal lahir (format: YYYY-MM-DD)
- `user_gender` (string) - Gender (MALE/FEMALE)

**Success Response:**
```json
{
  "isSuccess": true,
  "message": "Google signup successful!",
  "emailVerified": true,
  "data": {
    "user": {
      "id_user": 123,
      "user_name": "John Doe",
      "user_email": "john.doe@gmail.com",
      "user_code": "ABC12345",
      "company_id": 456,
      "auth_provider": "google",
      "google_id": "1234567890",
      ...
    },
    "company": {
      "id_company": 456,
      "company_code": "XYZAB12345678900",
      "company_name": "John Doe",
      ...
    },
    "access_token": "eyJ0eXAiOiJKV1QiLCJhbGc..."
  }
}
```

**Error Response (Email sudah terdaftar):**
```json
{
  "isSuccess": false,
  "message": "Account with this email already exists. Please login instead.",
  "errors": null
}
```

**Error Response (Validation failed):**
```json
{
  "isSuccess": false,
  "message": "Validation failed!",
  "errors": {
    "user_email": ["The user email field is required."]
  }
}
```

---

### 2. Login with Google (Updated)

**Endpoint:** `POST /api/login`

**Description:** Login menggunakan Google authentication

**Request Body:**
```json
{
  "email": "john.doe@gmail.com",
  "is_google": true
}
```

**Required Fields:**
- `email` (string) - Email yang terdaftar
- `is_google` (boolean) - Set ke `true` untuk Google login

**Success Response:**
```json
{
  "isSuccess": true,
  "message": "Login successful",
  "emailVerified": true,
  "data": {
    "user": { ... },
    "company": { ... },
    "access_token": "..."
  }
}
```

**Error Responses:**

User not found:
```json
{
  "isSuccess": false,
  "accountExist": false,
  "message": "User not found. Please sign up first."
}
```

Account tidak menggunakan Google:
```json
{
  "isSuccess": false,
  "message": "This account is registered with email/password. Please login with password."
}
```

---

## Database Changes

### Migration
File: `database/migrations/2026_02_05_113553_add_google_auth_fields_to_tb_user_table.php`

**Kolom baru di tabel `tb_user`:**
- `google_id` (string, nullable) - Google User ID
- `auth_provider` (string, nullable, default: 'email') - Provider autentikasi (email, google, etc)

**Menjalankan Migration:**
```bash
php artisan migrate
```

**Rollback Migration:**
```bash
php artisan migrate:rollback
```

---

## Model Changes

### UserCompany Model
File: `app/Models/UserCompany.php`

**Kolom baru di `$fillable`:**
- `google_id`
- `auth_provider`

---

## Flow Diagram

### Signup Flow
```
1. User klik "Sign up with Google" di app
2. App mendapatkan user info dari Google OAuth
3. App kirim request ke POST /api/signupWithGoogle
4. Backend validasi dan cek email unique
5. Backend create Company dan UserCompany
6. Backend auto-verify email (karena dari Google)
7. Backend auto-login user
8. Return user data + access token
```

### Login Flow
```
1. User klik "Login with Google" di app
2. App mendapatkan user info dari Google OAuth
3. App kirim request ke POST /api/login dengan is_google=true
4. Backend cek user exists dan auth_provider
5. Backend auto-login user
6. Return user data + access token
```

---

## Notes

1. **Password**: Untuk user Google, sistem generate random password yang secure. User tidak perlu tahu password ini.

2. **Email Verification**: Email otomatis terverifikasi untuk Google users (set `email_verified_at` saat signup).

3. **Auto Login**: Setelah signup, user langsung di-login dan mendapat access token.

4. **Company Creation**: Sistem otomatis membuat Company untuk setiap user baru.

5. **User Code**: User code di-generate otomatis menggunakan `generateUserCompanyCode()`.

6. **Auth Provider**: Field `auth_provider` membedakan antara user yang signup via email/password (`email`) vs Google (`google`).

---

## Testing

### Test Signup with Google
```bash
curl -X POST http://localhost:8000/api/signupWithGoogle \
  -H "Content-Type: application/json" \
  -d '{
    "user_name": "Test User",
    "user_email": "test@gmail.com",
    "google_id": "123456789",
    "user_photo": "https://example.com/photo.jpg"
  }'
```

### Test Login with Google
```bash
curl -X POST http://localhost:8000/api/login \
  -H "Content-Type: application/json" \
  -d '{
    "email": "test@gmail.com",
    "is_google": true
  }'
```

---

## Security Considerations

### Current Implementation (Client-Side Auth)
1. ✅ Password di-hash dengan bcrypt
2. ✅ Email validation
3. ✅ Unique email check
4. ✅ Auth provider verification
5. ✅ CSRF token protection
6. ✅ Secure random password generation

### Optional: Google ID Token Verification (Recommended)

Untuk keamanan tambahan, Anda bisa verify Google ID Token:

**1. App kirim `id_token` dari Google:**
```json
{
  "user_name": "John Doe",
  "user_email": "john.doe@gmail.com",
  "google_id": "1234567890",
  "id_token": "eyJhbGciOiJSUzI1NiIsImtpZCI..."
}
```

**2. Backend verify token (uncomment di signupWithGoogle):**
```php
// Uncomment di app/Http/Controllers/ApiController.php
if ($request->has('id_token')) {
    $verification = GoogleTokenVerifier::verifyIdToken($request->id_token);

    if (!$verification['valid']) {
        $this->isSuccess = false;
        $this->message = "Invalid Google token";
        return $this->commitResponseJson();
    }

    // Ensure email dari token match dengan email yang dikirim
    if ($verification['email'] !== $request->user_email) {
        $this->isSuccess = false;
        $this->message = "Email mismatch";
        return $this->commitResponseJson();
    }
}
```

**File helper:** `app/Http/Controllers/GoogleTokenVerifier.php`

**Tidak perlu credentials di backend**, method ini verify langsung ke Google API.

---

## Future Improvements

1. Add Google ID verification dengan Google API
2. Support untuk provider lain (Facebook, Apple, etc)
3. Link/unlink social accounts
4. Two-factor authentication
5. Session management improvements
