Files
presensi/app/Modules/Auth/Controllers/AuthController.php
mwpn 132b040418 feat: tambah profil akun dan ganti password
Tambahkan halaman /dashboard/profile beserta API ganti password untuk user yang sedang login.
Rapikan AuthSeeder agar idempotent dan bisa ambil admin email/password dari env.
2026-03-06 16:07:10 +07:00

103 lines
2.8 KiB
PHP

<?php
namespace App\Modules\Auth\Controllers;
use App\Core\BaseApiController;
use App\Modules\Auth\Services\AuthService;
use CodeIgniter\HTTP\ResponseInterface;
/**
* Auth Controller
*
* POST /api/auth/login, POST /api/auth/logout, GET /api/auth/me (session-based).
*/
class AuthController extends BaseApiController
{
protected AuthService $authService;
public function __construct()
{
$this->authService = new AuthService();
}
/**
* POST /api/auth/login
* Body: { "email": "", "password": "" }
*/
public function login(): ResponseInterface
{
$input = $this->request->getJSON(true);
$email = $input['email'] ?? '';
$password = $input['password'] ?? '';
if ($email === '' || $password === '') {
return $this->errorResponse('Email and password are required', null, null, 400);
}
$user = $this->authService->login($email, $password);
if (!$user) {
return $this->errorResponse('Invalid email or password', null, null, 401);
}
return $this->successResponse($user, 'Login successful');
}
/**
* POST /api/auth/logout
*/
public function logout(): ResponseInterface
{
$this->authService->logout();
return $this->successResponse(null, 'Logged out');
}
/**
* GET /api/auth/me
*/
public function me(): ResponseInterface
{
$user = $this->authService->currentUser();
if (!$user) {
return $this->errorResponse('Not authenticated', null, null, 401);
}
return $this->successResponse($user, 'Current user');
}
/**
* POST /api/auth/change-password
* Body: { "current_password": "", "new_password": "" }
* User can only change their own password.
*/
public function changePassword(): ResponseInterface
{
$user = $this->authService->currentUser();
if (!$user) {
return $this->errorResponse('Not authenticated', null, null, 401);
}
$input = $this->request->getJSON(true);
$currentPassword = $input['current_password'] ?? '';
$newPassword = $input['new_password'] ?? '';
if ($currentPassword === '' || $newPassword === '') {
return $this->errorResponse('Current password and new password are required', null, null, 400);
}
if (strlen($newPassword) < 6) {
return $this->errorResponse('New password must be at least 6 characters', null, null, 400);
}
$ok = $this->authService->changePassword(
(int) $user['id'],
$currentPassword,
$newPassword
);
if (!$ok) {
return $this->errorResponse('Current password is incorrect', null, null, 400);
}
return $this->successResponse(null, 'Password changed successfully');
}
}