# Auth, Password & Profile Module Documentation

## Overview

This document explains the authentication, password management, and profile management cycles in the base project. The system uses **JWT (JSON Web Tokens)** for authentication and supports two user types:

- **Admin**: Uses email for authentication
- **Client**: Uses phone number for authentication

---

## Table of Contents

1. [Architecture Overview](#1-architecture-overview)
2. [Authentication Flow](#2-authentication-flow)
3. [Password Management](#3-password-management)
4. [Profile Management](#4-profile-management)
5. [API Endpoints Summary](#5-api-endpoints-summary)
6. [Key Files Reference](#6-key-files-reference)
7. [Database Schema](#7-database-schema)
8. [Security Considerations](#8-security-considerations)

---

## 1. Architecture Overview

### Key Components

| Component | Description |
|-----------|-------------|
| **JWT Auth** | Token-based authentication via `tymon/jwt-auth` package |
| **User Type Header** | Distinguishes between Client (phone) and Admin (email) |
| **OTP Verification** | 4-6 digit codes for account activation and password reset |
| **Device Tracking** | Manages multiple login sessions per user |

### User Types (from `app/Enums/UserTypeEnum.php`)

```php
Admin  -> Uses EMAIL for authentication
Client -> Uses PHONE for authentication
```

---

## 2. Authentication Flow

### 2.1 Registration Flow

```
[User] --> POST /api/auth/register --> [AuthController::register]
                                              |
                                              v
                                     [AuthService::register]
                                              |
                                              v
                                     Generate OTP (4-6 digits)
                                              |
                                              v
                                     Create User (is_active = false)
                                              |
                                              v
                                     Send OTP (Email/SMS)
                                              |
                                              v
                                     Return "Code was sent"
```

**Request Body:**
```json
{
  "email": "user@example.com",      // For Admin
  "phone": "1234567890",            // For Client
  "phone_code": "country-uuid",     // For Client
  "password": "password123",        // 8-16 characters
  "full_name": "John Doe"           // Optional
}
```

**Response:**
```json
{
  "message": "Account created successfully, code was sent"
}
```

### 2.2 Verification (OTP) Flow

```
[User] --> POST /api/auth/verify --> [AuthController::verify]
                                            |
                                            v
                                   [AuthService::verify]
                                            |
                                            v
                                   Validate OTP Code
                                            |
                                            v
                                   Update User (is_active = true)
                                            |
                                            v
                                   Create Device Record (optional)
                                            |
                                            v
                                   Issue JWT Token
                                            |
                                            v
                                   Return Profile + Token
```

**Request Body:**
```json
{
  "email": "user@example.com",      // or phone + phone_code
  "code": "123456",
  "device_token": "fcm-token",      // Optional
  "type": "android"                 // android|ios|huawei|web
}
```

**Response:**
```json
{
  "data": {
    "id": "user-uuid",
    "full_name": "John Doe",
    "user_type": "client",
    "email": "user@example.com",
    "phone": "1234567890",
    "is_active": true,
    "locale": "ar",
    "is_notify": false,
    "token": "eyJ0eXAiOiJKV1QiLCJhbGc..."
  },
  "message": "Your account has been activated successfully"
}
```

### 2.3 Login Flow

```
[User] --> POST /api/auth/login --> [AuthController::login]
                                           |
                                           v
                                  [AuthService::login]
                                           |
                                           v
                                  Validate Credentials
                                           |
                              +------------+------------+
                              |                         |
                    [is_active = false]        [is_active = true]
                              |                         |
                              v                         v
                    Generate & Send OTP          Check if Banned
                              |                         |
                              v                         v
                    Return "Verify account"      Issue JWT Token
                                                        |
                                                        v
                                                Return Profile + Token
```

**Request Body:**
```json
{
  "email": "user@example.com",      // or phone + phone_code
  "password": "password123",
  "device_token": "fcm-token",      // Optional
  "type": "android"                 // Optional
}
```

### 2.4 Resend OTP Flow

```
[User] --> POST /api/auth/send --> [AuthController::resendOtp]
                                          |
                                          v
                                 Generate New OTP
                                          |
                                          v
                                 Update reset_code
                                          |
                                          v
                                 Send via Email/SMS
```

### 2.5 Token Refresh Flow

```
[User] --> POST /api/token/refresh --> [AuthController::refreshToken]
                                              |
                                              v
                                     [AuthService::refreshToken]
                                              |
                                              v
                                     Refresh JWT Token
                                              |
                                              v
                                     Return New Token + TTL
```

**Response:**
```json
{
  "data": {
    "token": "new-jwt-token",
    "token_type": "bearer",
    "expires_in": 3600
  },
  "message": "Token refreshed successfully"
}
```

### 2.6 Logout Flow

```
[User] --> POST /api/logout --> [AuthController::logout]
                                       |
                                       v
                              [AuthService::logout]
                                       |
                                       v
                              Deactivate Device
                                       |
                                       v
                              Invalidate JWT Token
```

---

## 3. Password Management

### 3.1 Forget Password Flow

```
[User] --> POST /api/password/forget --> [PasswordController::forget]
                                                |
                                                v
                                       [AuthService::forget]
                                                |
                                                v
                                       Find User by Email/Phone
                                                |
                                                v
                                       Generate OTP
                                                |
                                                v
                                       Send via Email/SMS
```

**Request Body:**
```json
{
  "email": "user@example.com"       // or phone + phone_code
}
```

**Response:**
```json
{
  "message": "Code has been sent to you."
}
```

### 3.2 Verify Forget Password Flow

```
[User] --> POST /api/password/verify --> [PasswordController::verify]
                                                |
                                                v
                                       Validate OTP Code
                                                |
                                                v
                                       Return "Verified successfully"
```

**Request Body:**
```json
{
  "email": "user@example.com",
  "code": "123456"
}
```

### 3.3 Reset Password Flow

```
[User] --> POST /api/password/reset --> [PasswordController::reset]
                                               |
                                               v
                                      [AuthService::reset]
                                               |
                                               v
                                      Validate OTP + New Password
                                               |
                                               v
                                      Update Password (Hashed)
                                               |
                                               v
                                      Clear reset_code
```

**Request Body:**
```json
{
  "email": "user@example.com",
  "code": "123456",
  "password": "newpassword123"      // 8-16 characters
}
```

**Response:**
```json
{
  "message": "Password updated successfully"
}
```

---

## 4. Profile Management

### 4.1 Show Profile

```
GET /api/profile --> [ProfileController::show] --> Return User Profile
```

**Response:**
```json
{
  "data": {
    "id": "user-uuid",
    "full_name": "John Doe",
    "user_type": "client",
    "email": "user@example.com",
    "phone": "1234567890",
    "avatar": "media-url",
    "is_active": true,
    "locale": "ar",
    "is_notify": true
  }
}
```

### 4.2 Update Profile

```
PUT /api/profile --> [ProfileController::update] --> Return Updated Profile
```

**Request Body:**
```json
{
  "full_name": "New Name",
  "avatar": "media-uuid"            // Must exist in media table
}
```

### 4.3 Update Password (Authenticated)

```
[User] --> PUT /api/profile/update-password --> [ProfileController::updatePassword]
                                                       |
                                                       v
                                              Validate Current Password
                                                       |
                                                       v
                                              Update to New Password
```

**Request Body:**
```json
{
  "current_password": "oldpassword",
  "password": "newpassword123"
}
```

### 4.4 Change Email/Phone (Two-Step Process)

#### Step 1: Send OTP

```
[User] --> POST /api/profile/send/otp --> [ProfileController::sendOtp]
                                                 |
                                                 v
                                        Generate OTP
                                                 |
                                                 v
                                        Save to auth_verifications
                                                 |
                                                 v
                                        Send via Email/SMS
```

**Request Body:**
```json
{
  "auth_type": "email",             // or "phone"
  "auth": "newemail@example.com",
  "phone_code": "country-uuid"      // Required if auth_type is phone
}
```

#### Step 2: Update Auth

```
[User] --> POST /api/profile/update/auth --> [ProfileController::updateAuth]
                                                    |
                                                    v
                                           Validate OTP
                                                    |
                                                    v
                                           Update Email/Phone
                                                    |
                                                    v
                                           Delete auth_verification
```

**Request Body:**
```json
{
  "auth_type": "email",
  "auth": "newemail@example.com",
  "code": "123456"
}
```

### 4.5 Update Location

```
POST /api/profile/update/location --> [ProfileController::updateLocation]
```

**Request Body:**
```json
{
  "lat": 30.0444,                   // -90 to 90
  "lng": 31.2357                    // -180 to 180
}
```

### 4.6 Switch Language

```
POST /api/profile/language/switch/{locale} --> [ProfileController::updateLocale]
```

**URL Parameter:** `locale` = `ar` or `en`

### 4.7 Toggle Notifications

```
PUT /api/profile/notification/switch --> [ProfileController::switchNotification]
```

Toggles `is_notify` field between `true` and `false`.

### 4.8 Delete Account

```
POST /api/profile/delete/account --> [ProfileController::deleteAccount]
```

Soft deletes the user account (sets `deleted_at` timestamp).

---

## 5. API Endpoints Summary

### Authentication Endpoints

| Method | Endpoint | Middleware | Description |
|--------|----------|------------|-------------|
| POST | `/api/auth/register` | user.type | Register new account |
| POST | `/api/auth/login` | user.type | Login |
| POST | `/api/auth/verify` | user.type | Verify OTP |
| POST | `/api/auth/send` | user.type | Resend OTP |
| POST | `/api/logout` | auth:api | Logout |
| POST | `/api/token/refresh` | auth:api | Refresh token |

### Password Endpoints

| Method | Endpoint | Middleware | Description |
|--------|----------|------------|-------------|
| POST | `/api/password/forget` | user.type | Request password reset |
| POST | `/api/password/verify` | user.type | Verify reset code |
| POST | `/api/password/reset` | user.type | Reset password |

### Profile Endpoints

| Method | Endpoint | Middleware | Description |
|--------|----------|------------|-------------|
| GET | `/api/profile` | auth:api, client | Get profile |
| PUT | `/api/profile` | auth:api, client | Update profile |
| PUT | `/api/profile/update-password` | auth:api, client | Change password |
| POST | `/api/profile/update/location` | auth:api, client | Update location |
| POST | `/api/profile/language/switch/{locale}` | auth:api, client | Change language |
| POST | `/api/profile/send/otp` | auth:api, client | Send OTP for auth change |
| POST | `/api/profile/update/auth` | auth:api, client | Update email/phone |
| PUT | `/api/profile/notification/switch` | auth:api, client | Toggle notifications |
| POST | `/api/profile/delete/account` | auth:api, client | Delete account |

---

## 6. Key Files Reference

### Controllers

| File | Description |
|------|-------------|
| `app/Http/Controllers/Api/Client/Auth/AuthController.php` | Login, Register, Verify, Logout |
| `app/Http/Controllers/Api/Client/Auth/PasswordController.php` | Forget, Verify, Reset password |
| `app/Http/Controllers/Api/Client/Profile/ProfileController.php` | All profile operations |

### Services

| File | Description |
|------|-------------|
| `app/Services/General/AuthService.php` | Core authentication logic |

### Request Validators

| File | Description |
|------|-------------|
| `app/Http/Requests/Api/General/Auth/LoginRequest.php` | Login validation |
| `app/Http/Requests/Api/General/Auth/RegisterRequest.php` | Registration validation |
| `app/Http/Requests/Api/General/Auth/VerifyRequest.php` | OTP verification validation |
| `app/Http/Requests/Api/General/Auth/ForgetPasswordRequest.php` | Forget password validation |
| `app/Http/Requests/Api/General/Auth/ResetPasswordRequest.php` | Reset password validation |
| `app/Http/Requests/Api/General/Profile/UpdateProfileRequest.php` | Update profile validation |
| `app/Http/Requests/Api/General/Profile/UpdatePasswordRequest.php` | Change password validation |
| `app/Http/Requests/Api/General/Profile/EditAuthRequest.php` | Send OTP validation |
| `app/Http/Requests/Api/General/Profile/UpdateAuthRequest.php` | Update auth validation |

### Middleware

| File | Description |
|------|-------------|
| `app/Http/Middleware/SetUserTypeMiddleware.php` | Validates user_type header |
| `app/Http/Middleware/ClientMiddleware.php` | Client-only routes protection |
| `app/Http/Middleware/AdminMiddleware.php` | Admin-only routes protection |

### Models

| File | Description |
|------|-------------|
| `app/Models/User.php` | User model with relationships |
| `app/Models/Device.php` | Device tracking model |
| `app/Models/AuthVerification.php` | Auth change verification model |

### Routes

| File | Description |
|------|-------------|
| `routes/api/client.php` | Client API routes |
| `routes/api/dashboard/admin.php` | Admin API routes |

---

## 7. Database Schema

### Users Table

```sql
id              - Primary key
uuid            - Unique identifier
full_name       - User's name
email           - Email address (nullable)
phone_code      - Country code (nullable)
phone           - Phone number (nullable)
password        - Hashed password
locale          - Language preference (default: 'ar')
is_active       - Account activation status (default: false)
is_banned       - Ban status (default: false)
banned_until    - Ban expiration (nullable)
user_type       - 'admin' or 'client'
is_super        - Super admin flag
reset_code      - OTP storage
is_notify       - Notification preference
deleted_at      - Soft delete timestamp
```

### Devices Table

```sql
id              - Primary key
device_token    - Push notification token
agent_token     - Device/browser identifier
type            - 'android', 'ios', 'huawei', 'web'
status          - Active/inactive
user_id         - Foreign key to users
```

### Auth Verifications Table

```sql
id              - Primary key
user_id         - Foreign key to users
email           - New email address (nullable)
phone           - New phone number (nullable)
phone_code      - Country code (nullable)
reset_code      - OTP for verification
```

---

## 8. Security Considerations

| Feature | Implementation |
|---------|----------------|
| **Password Hashing** | Laravel's built-in Bcrypt hashing |
| **JWT Tokens** | Secure token-based authentication |
| **OTP Verification** | 4-6 digit codes for critical operations |
| **Account Banning** | Temporary and permanent ban support |
| **Device Tracking** | Multiple sessions management |
| **User Type Validation** | Header-based segregation |
| **Soft Deletes** | Data retention on deletion |
| **Password Validation** | 8-16 characters required |
| **Email/Phone Uniqueness** | Per user_type validation |

---

## Flow Diagrams Summary

### Complete Registration to Login Flow

```
                    REGISTRATION
                         |
                         v
          +-----------------------------+
          |   POST /api/auth/register   |
          |   (email/phone + password)  |
          +-----------------------------+
                         |
                         v
          +-----------------------------+
          |     Create User Record      |
          |     (is_active = false)     |
          +-----------------------------+
                         |
                         v
          +-----------------------------+
          |   Generate & Send OTP       |
          |   (Email for Admin)         |
          |   (SMS for Client)          |
          +-----------------------------+
                         |
                         v
                   VERIFICATION
                         |
                         v
          +-----------------------------+
          |   POST /api/auth/verify     |
          |   (email/phone + OTP code)  |
          +-----------------------------+
                         |
                         v
          +-----------------------------+
          |   Activate User Account     |
          |   (is_active = true)        |
          +-----------------------------+
                         |
                         v
          +-----------------------------+
          |      Issue JWT Token        |
          +-----------------------------+
                         |
                         v
                USER IS LOGGED IN
                         |
          +--------------+--------------+
          |              |              |
          v              v              v
     [Profile]    [Password]      [Logout]
     Operations    Change        Session End
```

---

## Notes

- All API responses follow the format: `{ "data": {}, "message": "", "status": "" }`
- The `user_type` header is required for all auth-related routes
- JWT tokens should be included in the `Authorization: Bearer {token}` header
- OTP codes expire when used or when a new code is generated
- Device tokens are used for push notifications (Firebase/APNS/Huawei)