string('sort', 'username')->toString(); $dir = $request->string('dir', 'asc')->toString() === 'desc' ? 'desc' : 'asc'; $search = $request->string('q')->trim()->toString(); $groupFilter = $request->string('group')->trim()->toString(); $allowedSort = ['username', 'display_name', 'email', 'enabled', 'last_logon', 'groups', 'groups_count']; if (! in_array($sort, $allowedSort, true)) { $sort = 'username'; } $result = $this->ldapUsers->listUsers($sort, $dir, $search, $groupFilter); if ($result['error'] ?? null) { return $this->fail($result['error'], 'service_error', 503); } return $this->ok($result['rows'], $result['meta']); } public function show(string $username): JsonResponse { try { return $this->ok($this->ldapUsers->getUser($username)); } catch (InvalidArgumentException $e) { return $this->fail($e->getMessage(), 'not_found', 404); } } public function update(Request $request, string $username): JsonResponse { $data = $request->validate([ 'display_name' => ['required', 'string', 'max:255'], 'email' => ['nullable', 'email', 'max:255'], ]); try { $this->ldapUsers->updateProfile($username, $data['display_name'], $data['email'] ?? null); return $this->ok($this->ldapUsers->getUser($username)); } catch (InvalidArgumentException|RuntimeException $e) { return $this->fail($e->getMessage(), 'validation_error', 422); } catch (Throwable) { return $this->fail('Failed to update user.', 'server_error', 500); } } public function addToGroup(Request $request, string $username): JsonResponse { $data = $request->validate(['group' => ['required', 'string', 'max:255']]); try { $this->ldapGroups->addMember($data['group'], $username); return $this->ok($this->ldapUsers->getUser($username)); } catch (InvalidArgumentException|RuntimeException $e) { return $this->fail($e->getMessage(), 'validation_error', 422); } catch (Throwable) { return $this->fail('Failed to add user to group.', 'server_error', 500); } } public function removeFromGroup(string $username, string $group): JsonResponse { try { $this->ldapGroups->removeMember($group, $username); return $this->ok($this->ldapUsers->getUser($username)); } catch (InvalidArgumentException|RuntimeException $e) { return $this->fail($e->getMessage(), 'validation_error', 422); } catch (Throwable) { return $this->fail('Failed to remove user from group.', 'server_error', 500); } } }