# 🔀 Role-Based Redirect - Dokumentasi

Sistem redirect otomatis berdasarkan role user untuk pengalaman yang optimal.

---

## 🎯 Konsep

### Alur Redirect:

```
Login
  ↓
Check Role
  ↓
  ├─→ Admin → Dashboard Desktop (dashboard.html)
  └─→ User  → Dashboard Mobile (dashboard-mobile.html)
```

---

## 📋 Alur Detail

### 1. Login Process (`login.php`)

**Saat User Login:**
```php
if ($user['is_admin']) {
    // Admin → Dashboard Desktop
    header('Location: dashboard.html');
} else {
    // User → Dashboard Mobile
    header('Location: dashboard-mobile.html');
}
```

**Saat Sudah Login (akses login.php lagi):**
```php
if (isset($_SESSION['is_admin']) && $_SESSION['is_admin']) {
    header('Location: dashboard.html');
} else {
    header('Location: dashboard-mobile.html');
}
```

### 2. Index Page (`index.php`)

**Root URL redirect:**
```php
if (isset($_SESSION['user_id'])) {
    if (isset($_SESSION['is_admin']) && $_SESSION['is_admin']) {
        header('Location: dashboard.html');
    } else {
        header('Location: dashboard-mobile.html');
    }
} else {
    header('Location: login.php');
}
```

### 3. Dashboard Desktop (`dashboard.html`)

**JavaScript check saat load:**
```javascript
async function checkUserRole() {
    const response = await fetch('get-session.php');
    const data = await response.json();
    
    if (data.success && data.user) {
        // If user is not admin, redirect to mobile
        if (!data.user.isAdmin) {
            window.location.href = 'dashboard-mobile.html';
            return false;
        }
    }
    return true;
}
```

### 4. Dashboard Mobile (`dashboard-mobile.html`)

**Menu visibility:**
```javascript
if (currentUser.isAdmin) {
    // Show desktop menu link
    desktopMenu.style.display = 'flex';
} else {
    // Hide desktop menu link
    desktopMenu.style.display = 'none';
}
```

---

## 🔐 Access Control Matrix

| Role | Dashboard Desktop | Dashboard Mobile | Admin Panel | Display Mode |
|------|-------------------|------------------|-------------|--------------|
| Admin | ✅ Full Access | ✅ Can Access | ✅ Full Access | ✅ Can Access |
| User | ❌ Auto Redirect | ✅ Full Access | ❌ No Access | ✅ Can Access |
| Guest | ❌ Redirect Login | ❌ Redirect Login | ❌ Redirect Login | ✅ Read Only |

---

## 📱 User Experience

### Admin Login Flow:

1. **Login** → Enter credentials
2. **Redirect** → dashboard.html (Desktop)
3. **Features**:
   - Edit all positions
   - Access admin panel
   - View desktop dashboard
   - Can switch to mobile view

### User Login Flow:

1. **Login** → Enter credentials
2. **Redirect** → dashboard-mobile.html (Mobile)
3. **Features**:
   - Edit own position only
   - Mobile-optimized UI
   - Touch-friendly interface
   - Cannot access admin panel
   - Cannot access desktop dashboard (auto-redirect)

### Guest Flow:

1. **Access** → Any page
2. **Redirect** → login.php
3. **Exception**: display3.html (read-only)

---

## 🛡️ Security Features

### Session Validation

**Server-side (PHP):**
```php
// Check if logged in
if (!isset($_SESSION['user_id'])) {
    header('Location: login.php');
    exit();
}

// Check if admin
if ($requireAdmin && !$_SESSION['is_admin']) {
    header('Location: dashboard-mobile.html');
    exit();
}
```

**Client-side (JavaScript):**
```javascript
// Check role before allowing actions
if (!currentUser || (!currentUser.isAdmin && index !== userPositionIndex)) {
    // Prevent unauthorized edit
    return;
}
```

### API Validation

**Backend (`api/attendance.php`):**
```php
// Admin can edit all, user can only edit own
if (!$user['is_admin'] && $user['position_id'] != $position_id) {
    jsonResponse(['error' => 'Access denied'], 403);
}
```

---

## 🔧 Configuration

### Change Default Redirect

**For Admin:**
Edit `login.php` line ~25:
```php
if ($user['is_admin']) {
    header('Location: dashboard.html'); // Change this
}
```

**For User:**
Edit `login.php` line ~28:
```php
} else {
    header('Location: dashboard-mobile.html'); // Change this
}
```

### Disable Auto-Redirect

**Dashboard Desktop:**
Comment out in `dashboard.html`:
```javascript
// const canAccess = await checkUserRole();
// if (!canAccess) return false;
```

**Allow User to Desktop:**
Remove redirect check entirely from `dashboard.html`

---

## 📊 Flow Diagram

```
┌─────────────┐
│   Browser   │
└──────┬──────┘
       │
       ↓
┌─────────────┐
│  index.php  │
└──────┬──────┘
       │
       ├─→ Not Logged In → login.php
       │
       └─→ Logged In
           │
           ├─→ Admin → dashboard.html
           │            │
           │            ├─→ Edit All Positions
           │            ├─→ Access Admin Panel
           │            └─→ View Stats
           │
           └─→ User → dashboard-mobile.html
                       │
                       ├─→ Edit Own Position
                       ├─→ Mobile UI
                       └─→ Limited Access
```

---

## 🧪 Testing

### Test Admin Login:

1. Login dengan user admin
2. Verify redirect ke `dashboard.html`
3. Check dapat edit semua posisi
4. Check dapat akses admin panel
5. Check dapat switch ke mobile view

### Test User Login:

1. Login dengan user biasa
2. Verify redirect ke `dashboard-mobile.html`
3. Check hanya bisa edit posisi sendiri
4. Check tidak bisa akses admin panel
5. Check tidak bisa akses desktop dashboard

### Test Auto-Redirect:

1. Login sebagai user biasa
2. Manually navigate ke `dashboard.html`
3. Verify auto-redirect ke `dashboard-mobile.html`
4. Check console log untuk redirect message

### Test Session:

1. Login sebagai admin
2. Close browser
3. Open browser dan akses `index.php`
4. Verify redirect ke login (session cleared)

---

## 🐛 Troubleshooting

### User Tidak Redirect ke Mobile

**Solusi:**
1. Clear browser cache
2. Check `get-session.php` response
3. Verify `isAdmin` field in session
4. Check JavaScript console for errors

### Admin Redirect ke Mobile

**Solusi:**
1. Check database: `SELECT is_admin FROM users WHERE username = 'admin'`
2. Verify session: `var_dump($_SESSION['is_admin'])`
3. Clear session: `session_destroy()`
4. Login again

### Redirect Loop

**Solusi:**
1. Check for circular redirects
2. Verify session is set correctly
3. Clear browser cookies
4. Check server error logs

### Desktop Menu Tidak Muncul di Mobile

**Solusi:**
1. Verify user is admin
2. Check `currentUser.isAdmin` in console
3. Verify `desktopMenu` element exists
4. Check CSS display property

---

## 📝 Best Practices

### For Developers:

1. ✅ Always check role on both client and server
2. ✅ Use session validation for sensitive operations
3. ✅ Implement proper error handling
4. ✅ Log redirect actions for debugging
5. ✅ Test with different user roles

### For Admins:

1. ✅ Create separate accounts for admin and user testing
2. ✅ Regularly audit user roles in database
3. ✅ Monitor access logs for unauthorized attempts
4. ✅ Keep admin credentials secure
5. ✅ Use strong passwords

### For Users:

1. ✅ Always logout after use
2. ✅ Don't share credentials
3. ✅ Report any access issues to admin
4. ✅ Use mobile dashboard for quick updates
5. ✅ Clear browser cache if issues occur

---

## 🔄 Future Enhancements

### Planned Features:

- 🔜 Role-based permissions (viewer, editor, admin)
- 🔜 Custom redirect URLs per user
- 🔜 Remember last visited page
- 🔜 Multi-factor authentication
- 🔜 Session timeout configuration
- 🔜 Activity logging
- 🔜 IP-based access control

---

## 📚 Related Files

| File | Purpose |
|------|---------|
| `login.php` | Login handler with role-based redirect |
| `index.php` | Root redirect based on session |
| `get-session.php` | Session data API |
| `check-access.php` | Access control helper |
| `dashboard.html` | Desktop dashboard (admin) |
| `dashboard-mobile.html` | Mobile dashboard (user) |
| `assets/app.js` | Desktop dashboard logic |
| `assets/app-mobile.js` | Mobile dashboard logic |

---

## 🆘 Support

**Issues?**
- Check console for errors
- Review session data
- Verify database user roles
- Contact system administrator

**Questions?**
- Read this documentation
- Check related files
- Test with different roles

---

**Created:** 18 February 2026  
**Version:** 1.0.0  
**Status:** ✅ Production Ready
