133 lines
6.2 KiB
PHP
133 lines
6.2 KiB
PHP
<?php
|
|
// ================================================================
|
|
// API: User Management (CRUD)
|
|
// Hanya bisa diakses oleh admin
|
|
// ================================================================
|
|
require_once __DIR__ . '/../config/database.php';
|
|
require_once __DIR__ . '/../config/config.php';
|
|
require_once __DIR__ . '/../includes/auth.php';
|
|
require_once __DIR__ . '/../includes/functions.php';
|
|
|
|
header('Content-Type: application/json; charset=utf-8');
|
|
header('Access-Control-Allow-Origin: *');
|
|
header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS');
|
|
header('Access-Control-Allow-Headers: Content-Type');
|
|
|
|
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') { http_response_code(204); exit; }
|
|
|
|
// Auth check — hanya admin
|
|
session_name(SESSION_NAME);
|
|
session_start();
|
|
$sessionRole = $_SESSION['user']['role'] ?? $_SESSION['user_role'] ?? null;
|
|
$sessionUserId = $_SESSION['user']['id'] ?? $_SESSION['user_id'] ?? null;
|
|
if (!$sessionUserId || $sessionRole !== 'admin') {
|
|
jsonResponse(['success' => false, 'message' => 'Akses ditolak: hanya admin'], 403);
|
|
}
|
|
|
|
$db = getDB();
|
|
$method = $_SERVER['REQUEST_METHOD'];
|
|
$id = isset($_GET['id']) ? (int)$_GET['id'] : null;
|
|
|
|
// ── GET ────────────────────────────────────────────────────────
|
|
if ($method === 'GET') {
|
|
if ($id) {
|
|
$stmt = $db->prepare("SELECT id, nama, email, role, created_at FROM users WHERE id = ?");
|
|
$stmt->execute([$id]);
|
|
$row = $stmt->fetch();
|
|
if (!$row) jsonResponse(['success' => false, 'message' => 'User tidak ditemukan'], 404);
|
|
jsonResponse(['success' => true, 'data' => $row]);
|
|
}
|
|
$rows = $db->query("SELECT id, nama, email, role, created_at FROM users ORDER BY role DESC, nama")->fetchAll();
|
|
jsonResponse(['success' => true, 'data' => $rows, 'total' => count($rows)]);
|
|
}
|
|
|
|
// ── POST (Tambah user baru) ────────────────────────────────────
|
|
if ($method === 'POST') {
|
|
$body = json_decode(file_get_contents('php://input'), true) ?? [];
|
|
$nama = trim($body['nama'] ?? '');
|
|
$email = trim($body['email'] ?? '');
|
|
$pwd = $body['password'] ?? '';
|
|
$role = in_array($body['role'] ?? '', ['admin','operator']) ? $body['role'] : 'operator';
|
|
|
|
if (!$nama || !$email || !$pwd) {
|
|
jsonResponse(['success' => false, 'message' => 'Nama, email, dan password wajib diisi'], 422);
|
|
}
|
|
if (strlen($pwd) < 6) {
|
|
jsonResponse(['success' => false, 'message' => 'Password minimal 6 karakter'], 422);
|
|
}
|
|
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
|
|
jsonResponse(['success' => false, 'message' => 'Format email tidak valid'], 422);
|
|
}
|
|
|
|
// Cek duplikat email
|
|
$check = $db->prepare("SELECT id FROM users WHERE email = ?");
|
|
$check->execute([$email]);
|
|
if ($check->fetch()) {
|
|
jsonResponse(['success' => false, 'message' => 'Email sudah terdaftar'], 409);
|
|
}
|
|
|
|
$hash = password_hash($pwd, PASSWORD_BCRYPT);
|
|
$stmt = $db->prepare("INSERT INTO users (nama, email, password, role) VALUES (?, ?, ?, ?)");
|
|
$stmt->execute([$nama, $email, $hash, $role]);
|
|
$newId = $db->lastInsertId();
|
|
$new = $db->query("SELECT id, nama, email, role, created_at FROM users WHERE id = $newId")->fetch();
|
|
jsonResponse(['success' => true, 'message' => 'Pengguna berhasil ditambahkan', 'data' => $new], 201);
|
|
}
|
|
|
|
// ── PUT (Edit user) ────────────────────────────────────────────
|
|
if ($method === 'PUT') {
|
|
if (!$id) jsonResponse(['success' => false, 'message' => 'ID wajib disertakan'], 400);
|
|
$body = json_decode(file_get_contents('php://input'), true) ?? [];
|
|
|
|
$existing = $db->prepare("SELECT * FROM users WHERE id = ?");
|
|
$existing->execute([$id]);
|
|
$user = $existing->fetch();
|
|
if (!$user) jsonResponse(['success' => false, 'message' => 'User tidak ditemukan'], 404);
|
|
|
|
$nama = trim($body['nama'] ?? $user['nama']);
|
|
$email = trim($body['email'] ?? $user['email']);
|
|
$role = in_array($body['role'] ?? '', ['admin','operator']) ? $body['role'] : $user['role'];
|
|
$pwd = $body['password'] ?? '';
|
|
|
|
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
|
|
jsonResponse(['success' => false, 'message' => 'Format email tidak valid'], 422);
|
|
}
|
|
|
|
// Cek duplikat email (kecuali user ini sendiri)
|
|
$checkEmail = $db->prepare("SELECT id FROM users WHERE email = ? AND id != ?");
|
|
$checkEmail->execute([$email, $id]);
|
|
if ($checkEmail->fetch()) {
|
|
jsonResponse(['success' => false, 'message' => 'Email sudah digunakan oleh user lain'], 409);
|
|
}
|
|
|
|
if ($pwd) {
|
|
if (strlen($pwd) < 6) jsonResponse(['success' => false, 'message' => 'Password minimal 6 karakter'], 422);
|
|
$hash = password_hash($pwd, PASSWORD_BCRYPT);
|
|
$stmt = $db->prepare("UPDATE users SET nama=?, email=?, role=?, password=? WHERE id=?");
|
|
$stmt->execute([$nama, $email, $role, $hash, $id]);
|
|
} else {
|
|
$stmt = $db->prepare("UPDATE users SET nama=?, email=?, role=? WHERE id=?");
|
|
$stmt->execute([$nama, $email, $role, $id]);
|
|
}
|
|
|
|
$updated = $db->query("SELECT id, nama, email, role, created_at FROM users WHERE id = $id")->fetch();
|
|
jsonResponse(['success' => true, 'message' => 'Data pengguna berhasil diperbarui', 'data' => $updated]);
|
|
}
|
|
|
|
// ── DELETE ─────────────────────────────────────────────────────
|
|
if ($method === 'DELETE') {
|
|
if (!$id) jsonResponse(['success' => false, 'message' => 'ID wajib disertakan'], 400);
|
|
|
|
// Tidak boleh hapus diri sendiri
|
|
if ($id == $sessionUserId) {
|
|
jsonResponse(['success' => false, 'message' => 'Tidak bisa menghapus akun sendiri'], 403);
|
|
}
|
|
|
|
$stmt = $db->prepare("DELETE FROM users WHERE id = ?");
|
|
$stmt->execute([$id]);
|
|
if ($stmt->rowCount() === 0) jsonResponse(['success' => false, 'message' => 'User tidak ditemukan'], 404);
|
|
jsonResponse(['success' => true, 'message' => 'Pengguna berhasil dihapus']);
|
|
}
|
|
|
|
jsonResponse(['success' => false, 'message' => 'Method tidak didukung'], 405);
|