AdminController.php 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402
  1. <?php
  2. namespace App\Controllers\Api;
  3. use CodeIgniter\HTTP\ResponseInterface;
  4. class AdminController extends BaseApiController
  5. {
  6. protected $format = 'json';
  7. /**
  8. * Get all admins (관리자 목록)
  9. * GET /api/admin
  10. */
  11. public function index()
  12. {
  13. $auth = $this->requireAuth();
  14. if ($auth instanceof ResponseInterface) {
  15. return $auth;
  16. }
  17. try {
  18. $page = $this->request->getGet('page') ?? 1;
  19. $perPage = $this->request->getGet('per_page') ?? 10;
  20. $offset = ($page - 1) * $perPage;
  21. $db = $this->getDB();
  22. $builder = $db->table('admin_users');
  23. // 'admin' 계정 제외
  24. $builder->where('username !=', 'admin');
  25. // 검색 기능 - 아이디, 이름만 LIKE 검색
  26. $search = $this->request->getGet('search');
  27. if (!empty($search)) {
  28. $builder->groupStart()
  29. ->like('username', $search)
  30. ->orLike('name', $search)
  31. ->groupEnd();
  32. }
  33. // 역할 필터
  34. $role = $this->request->getGet('role');
  35. if (!empty($role)) {
  36. $builder->where('role', $role);
  37. }
  38. // 상태 필터
  39. $status = $this->request->getGet('status');
  40. if (!empty($status)) {
  41. $builder->where('status', $status);
  42. }
  43. // 전체 개수
  44. $total = $builder->countAllResults(false);
  45. // 비밀번호 제외하고 조회 (login_attempts 포함)
  46. $builder->select('id, username, name, email, department, role, status, COALESCE(login_attempts, 0) as login_attempts, last_failed_login, created_at, updated_at');
  47. $builder->orderBy('id', 'DESC');
  48. $builder->limit($perPage, $offset);
  49. // SQL 쿼리 로그
  50. $sql = $builder->getCompiledSelect(false);
  51. log_message('debug', 'AdminController SQL: ' . $sql);
  52. $items = $builder->get()->getResult();
  53. $result = [
  54. 'items' => $items,
  55. 'total' => $total,
  56. 'page' => (int)$page,
  57. 'per_page' => (int)$perPage,
  58. 'total_pages' => ceil($total / $perPage)
  59. ];
  60. return $this->respondSuccess($result);
  61. } catch (\Exception $e) {
  62. log_message('error', 'AdminController index error: ' . $e->getMessage());
  63. return $this->respondError('관리자 목록 조회 중 오류가 발생했습니다: ' . $e->getMessage(), ResponseInterface::HTTP_INTERNAL_SERVER_ERROR);
  64. }
  65. }
  66. /**
  67. * Get single admin (관리자 상세)
  68. * GET /api/admin/:id
  69. */
  70. public function show($id = null)
  71. {
  72. $auth = $this->requireAuth();
  73. if ($auth instanceof ResponseInterface) {
  74. return $auth;
  75. }
  76. if (empty($id)) {
  77. return $this->respondError('관리자 ID가 필요합니다.', ResponseInterface::HTTP_BAD_REQUEST);
  78. }
  79. try {
  80. $admin = $this->getDB()->table('admin_users')
  81. ->select('id, username, name, email, department, role, status, login_attempts, last_failed_login, created_at, updated_at')
  82. ->where('id', $id)
  83. ->get()
  84. ->getRow();
  85. if (!$admin) {
  86. return $this->respondError('관리자를 찾을 수 없습니다.', ResponseInterface::HTTP_NOT_FOUND);
  87. }
  88. return $this->respondSuccess($admin);
  89. } catch (\Exception $e) {
  90. log_message('error', 'AdminController show error: ' . $e->getMessage());
  91. return $this->respondError('관리자 조회 중 오류가 발생했습니다.', ResponseInterface::HTTP_INTERNAL_SERVER_ERROR);
  92. }
  93. }
  94. /**
  95. * Check if username is available (아이디 중복 체크)
  96. * GET /api/admin/check-username
  97. */
  98. public function checkUsername()
  99. {
  100. $auth = $this->requireAuth();
  101. if ($auth instanceof ResponseInterface) {
  102. return $auth;
  103. }
  104. $username = $this->request->getGet('username');
  105. if (empty($username)) {
  106. return $this->respondError('아이디를 입력하세요.');
  107. }
  108. try {
  109. $existing = $this->getDB()->table('admin_users')
  110. ->where('username', $username)
  111. ->get()
  112. ->getRow();
  113. return $this->respondSuccess([
  114. 'available' => !$existing
  115. ]);
  116. } catch (\Exception $e) {
  117. log_message('error', 'AdminController checkUsername error: ' . $e->getMessage());
  118. return $this->respondError('중복 체크 중 오류가 발생했습니다.', ResponseInterface::HTTP_INTERNAL_SERVER_ERROR);
  119. }
  120. }
  121. /**
  122. * Create new admin (관리자 생성)
  123. * POST /api/admin
  124. */
  125. public function create()
  126. {
  127. $auth = $this->requireAuth();
  128. if ($auth instanceof ResponseInterface) {
  129. return $auth;
  130. }
  131. try {
  132. $data = $this->request->getJSON(true);
  133. // 필수 필드 검증
  134. $required = ['username', 'password', 'name', 'email'];
  135. foreach ($required as $field) {
  136. if (empty($data[$field])) {
  137. return $this->respondError("{$field}는 필수 항목입니다.", ResponseInterface::HTTP_BAD_REQUEST);
  138. }
  139. }
  140. // 중복 체크
  141. $existing = $this->getDB()->table('admin_users')
  142. ->where('username', $data['username'])
  143. ->orWhere('email', $data['email'])
  144. ->get()
  145. ->getRow();
  146. if ($existing) {
  147. if ($existing->username === $data['username']) {
  148. return $this->respondError('이미 사용 중인 아이디입니다.', ResponseInterface::HTTP_BAD_REQUEST);
  149. }
  150. if ($existing->email === $data['email']) {
  151. return $this->respondError('이미 사용 중인 이메일입니다.', ResponseInterface::HTTP_BAD_REQUEST);
  152. }
  153. }
  154. // 비밀번호 해싱
  155. $insertData = [
  156. 'username' => $data['username'],
  157. 'password' => password_hash($data['password'], PASSWORD_DEFAULT),
  158. 'name' => $data['name'],
  159. 'email' => $data['email'],
  160. 'department' => $data['department'] ?? '',
  161. 'role' => $data['role'] ?? 'admin',
  162. 'status' => $data['status'] ?? 'active',
  163. 'created_at' => date('Y-m-d H:i:s'),
  164. 'updated_at' => date('Y-m-d H:i:s')
  165. ];
  166. $builder = $this->getDB()->table('admin_users');
  167. $builder->insert($insertData);
  168. $insertId = $this->getDB()->insertID();
  169. // 생성된 관리자 정보 조회 (비밀번호 제외)
  170. $admin = $this->getDB()->table('admin_users')
  171. ->select('id, username, name, email, department, role, status, login_attempts, last_failed_login, created_at, updated_at')
  172. ->where('id', $insertId)
  173. ->get()
  174. ->getRow();
  175. return $this->respondSuccess($admin, '관리자가 생성되었습니다.', ResponseInterface::HTTP_CREATED);
  176. } catch (\Exception $e) {
  177. log_message('error', 'AdminController create error: ' . $e->getMessage());
  178. return $this->respondError('관리자 생성 중 오류가 발생했습니다.', ResponseInterface::HTTP_INTERNAL_SERVER_ERROR);
  179. }
  180. }
  181. /**
  182. * Update admin (관리자 수정)
  183. * PUT /api/admin/:id
  184. */
  185. public function update($id = null)
  186. {
  187. $auth = $this->requireAuth();
  188. if ($auth instanceof ResponseInterface) {
  189. return $auth;
  190. }
  191. if (empty($id)) {
  192. return $this->respondError('관리자 ID가 필요합니다.', ResponseInterface::HTTP_BAD_REQUEST);
  193. }
  194. try {
  195. // 기존 관리자 확인
  196. $existing = $this->getDB()->table('admin_users')->where('id', $id)->get()->getRow();
  197. if (!$existing) {
  198. return $this->respondError('관리자를 찾을 수 없습니다.', ResponseInterface::HTTP_NOT_FOUND);
  199. }
  200. $data = $this->request->getJSON(true);
  201. // email 중복 체크 (자신 제외)
  202. if (!empty($data['email']) && $data['email'] !== $existing->email) {
  203. $duplicate = $this->getDB()->table('admin_users')
  204. ->where('email', $data['email'])
  205. ->where('id !=', $id)
  206. ->get()
  207. ->getRow();
  208. if ($duplicate) {
  209. return $this->respondError('이미 사용 중인 이메일입니다.', ResponseInterface::HTTP_BAD_REQUEST);
  210. }
  211. }
  212. $updateData = [
  213. 'updated_at' => date('Y-m-d H:i:s')
  214. ];
  215. if (isset($data['name'])) {
  216. $updateData['name'] = $data['name'];
  217. }
  218. if (isset($data['email'])) {
  219. $updateData['email'] = $data['email'];
  220. }
  221. if (isset($data['department'])) {
  222. $updateData['department'] = $data['department'];
  223. }
  224. if (isset($data['role'])) {
  225. $updateData['role'] = $data['role'];
  226. }
  227. if (isset($data['status'])) {
  228. $updateData['status'] = $data['status'];
  229. }
  230. $builder = $this->getDB()->table('admin_users');
  231. $builder->where('id', $id)->update($updateData);
  232. // 업데이트된 관리자 정보 조회
  233. $admin = $this->getDB()->table('admin_users')
  234. ->select('id, username, name, email, department, role, status, login_attempts, last_failed_login, created_at, updated_at')
  235. ->where('id', $id)
  236. ->get()
  237. ->getRow();
  238. return $this->respondSuccess($admin, '관리자 정보가 수정되었습니다.');
  239. } catch (\Exception $e) {
  240. log_message('error', 'AdminController update error: ' . $e->getMessage());
  241. return $this->respondError('관리자 수정 중 오류가 발생했습니다.', ResponseInterface::HTTP_INTERNAL_SERVER_ERROR);
  242. }
  243. }
  244. /**
  245. * Delete admin (관리자 삭제)
  246. * DELETE /api/admin/:id
  247. */
  248. public function delete($id = null)
  249. {
  250. $auth = $this->requireAuth();
  251. if ($auth instanceof ResponseInterface) {
  252. return $auth;
  253. }
  254. if (empty($id)) {
  255. return $this->respondError('관리자 ID가 필요합니다.', ResponseInterface::HTTP_BAD_REQUEST);
  256. }
  257. try {
  258. $existing = $this->getDB()->table('admin_users')->where('id', $id)->get()->getRow();
  259. if (!$existing) {
  260. return $this->respondError('관리자를 찾을 수 없습니다.', ResponseInterface::HTTP_NOT_FOUND);
  261. }
  262. $builder = $this->getDB()->table('admin_users');
  263. $builder->where('id', $id)->delete();
  264. // 해당 관리자의 토큰도 삭제
  265. $this->getDB()->table('admin_tokens')->where('admin_id', $id)->delete();
  266. return $this->respondSuccess(null, '관리자가 삭제되었습니다.');
  267. } catch (\Exception $e) {
  268. log_message('error', 'AdminController delete error: ' . $e->getMessage());
  269. return $this->respondError('관리자 삭제 중 오류가 발생했습니다.', ResponseInterface::HTTP_INTERNAL_SERVER_ERROR);
  270. }
  271. }
  272. /**
  273. * Change admin password (비밀번호 변경)
  274. * POST /api/admin/:id/password
  275. */
  276. public function changePassword($id = null)
  277. {
  278. $auth = $this->requireAuth();
  279. if ($auth instanceof ResponseInterface) {
  280. return $auth;
  281. }
  282. if (empty($id)) {
  283. return $this->respondError('관리자 ID가 필요합니다.', ResponseInterface::HTTP_BAD_REQUEST);
  284. }
  285. try {
  286. $data = $this->request->getJSON(true);
  287. if (empty($data['new_password'])) {
  288. return $this->respondError('새 비밀번호가 필요합니다.', ResponseInterface::HTTP_BAD_REQUEST);
  289. }
  290. $existing = $this->getDB()->table('admin_users')->where('id', $id)->get()->getRow();
  291. if (!$existing) {
  292. return $this->respondError('관리자를 찾을 수 없습니다.', ResponseInterface::HTTP_NOT_FOUND);
  293. }
  294. $updateData = [
  295. 'password' => password_hash($data['new_password'], PASSWORD_DEFAULT),
  296. 'password_changed_at' => date('Y-m-d H:i:s'),
  297. 'updated_at' => date('Y-m-d H:i:s')
  298. ];
  299. $this->getDB()->table('admin_users')->where('id', $id)->update($updateData);
  300. return $this->respondSuccess(null, '비밀번호가 변경되었습니다.');
  301. } catch (\Exception $e) {
  302. log_message('error', 'AdminController changePassword error: ' . $e->getMessage());
  303. return $this->respondError('비밀번호 변경 중 오류가 발생했습니다.', ResponseInterface::HTTP_INTERNAL_SERVER_ERROR);
  304. }
  305. }
  306. /**
  307. * Unlock admin account (계정 잠금 해제)
  308. * POST /api/admin/:id/unlock
  309. */
  310. public function unlockAccount($id = null)
  311. {
  312. $auth = $this->requireAuth();
  313. if ($auth instanceof ResponseInterface) {
  314. return $auth;
  315. }
  316. if (empty($id)) {
  317. return $this->respondError('관리자 ID가 필요합니다.', ResponseInterface::HTTP_BAD_REQUEST);
  318. }
  319. try {
  320. $existing = $this->getDB()->table('admin_users')->where('id', $id)->get()->getRow();
  321. if (!$existing) {
  322. return $this->respondError('관리자를 찾을 수 없습니다.', ResponseInterface::HTTP_NOT_FOUND);
  323. }
  324. $updateData = [
  325. 'login_attempts' => 0,
  326. 'last_failed_login' => null,
  327. 'updated_at' => date('Y-m-d H:i:s')
  328. ];
  329. $this->getDB()->table('admin_users')->where('id', $id)->update($updateData);
  330. return $this->respondSuccess(null, '계정 잠금이 해제되었습니다.');
  331. } catch (\Exception $e) {
  332. log_message('error', 'AdminController unlockAccount error: ' . $e->getMessage());
  333. return $this->respondError('계정 잠금 해제 중 오류가 발생했습니다.', ResponseInterface::HTTP_INTERNAL_SERVER_ERROR);
  334. }
  335. }
  336. }