Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
# CLI Administrative User Setup Guide

This document describes the implementation and usage of the server-side CLI administration tool, which replaced the deprecated HTTP-based REST API signup/OTP flow.

---

## 1. Overview & Security Rationale

To reduce the public attack surface of the application, all public HTTP-facing endpoints for administrative signup (`/api/v1/admin/signup`), OTP generation (`/api/v1/admin/generate-otp`), and OTP listing (`/api/v1/admin/active-otps`) have been completely removed.
Comment thread
michael-whyte marked this conversation as resolved.
Resolved

Administrative user setup must now be done directly on the server host or container using the Spring Boot CLI runner. This ensures that:
* **Zero Network Exposure**: No public endpoints exist for brute-forcing admin privileges.
* **DevOps Isolation**: Only users with console or shell access (`SSH`, `kubectl exec`, or secure deployment pipelines) can provision admin accounts.

---

## 2. Command Usage

The CLI command is triggered by passing the `--create-admin` parameter alongside the admin user details.

If any required parameter is missing or invalid, the command displays the correct usage instructions and exits with status code `1`. Upon successful creation, it prints the user details and exits with status code `0`.

### Development (Maven)
Run the following command in your terminal from the project root:

```powershell
mvn spring-boot:run "-Dspring-boot.run.arguments=--create-admin --email=admin@xtraction.xyz --password=SecurePassword123! --first-name=Jane --last-name=Doe --country=US --role=SUPER_ADMIN"
```

### Production (JAR)
Run the compiled executable archive directly:

```bash
java -jar xtraction-api.jar --create-admin \
--email="admin@xtraction.xyz" \
--password="SecurePassword123!" \
--first-name="Jane" \
--last-name="Doe" \
--country="US" \
--role="super_admin"
```

---

## 3. Parameter Reference

| Parameter | Required? | Default | Description |
|:-------------------------------|:----------|:--------|:-------------------------------------------------------------|
| `--create-admin` | **Yes** | *None* | Trigger flag that activates the admin CLI creation sequence. |
| `--email` | **Yes** | *None* | Unique email address for the new administrative user. |
| `--password` | **Yes** | *None* | Secure password for the admin account. |
| `--first-name` / `--firstName` | **Yes** | *None* | First name of the administrator. |
| `--last-name` / `--lastName` | **Yes** | *None* | Last name of the administrator. |
| `--country` | No | `US` | Two-letter country code (e.g., `NG`, `US`, `GB`). |
| `--role` | No | `admin` | Target role. Must be either `admin` or `super_admin`. |

---

## 4. Under-the-Hood Sequence
1. The `AdminCliRunner` bean implements `ApplicationRunner` and executes on startup.
2. It detects the `--create-admin` argument and hijacks the regular application boot loop.
3. It performs validations on required fields and checks that the requested email is not already registered.
4. It calls `CreateAdminService` to hash the password, save the new `User` to the database, assign the default unlimited credit plan and default subscription, and register the transaction commit synchronization.
5. Once the transaction successfully commits, a Kafka `AdminCreatedEvent` is dispatched.
6. The CLI prints a success confirmation table and exits the JVM with code `0`, preventing Tomcat/Netty from binding to network ports.
100 changes: 100 additions & 0 deletions src/main/java/com/xtraction/api/admin/config/AdminCliRunner.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,100 @@
package com.xtraction.api.admin.config;

import com.xtraction.api.admin.interfaces.CreateAdminService;
import com.xtraction.api.identity.auth.datamodel.Role;
import com.xtraction.api.identity.user.model.User;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;

import java.util.List;

@Slf4j
@Component
@RequiredArgsConstructor
public class AdminCliRunner implements ApplicationRunner {

private final CreateAdminService createAdminService;

@Override
public void run(ApplicationArguments args) throws Exception {
if (args.containsOption("create-admin")) {
System.out.println("=================================================");
System.out.println(" XTRACTION CLI ADMIN CREATION ");
System.out.println("=================================================");
Comment thread
michael-whyte marked this conversation as resolved.
Resolved

String email = getOptionValue(args, "email");
String password = getOptionValue(args, "password");
String firstName = getOptionValue(args, "first-name");
if (firstName == null) {
firstName = getOptionValue(args, "firstName");
}
String lastName = getOptionValue(args, "last-name");
if (lastName == null) {
lastName = getOptionValue(args, "lastName");
}
String country = getOptionValue(args, "country");
if (country == null || country.isBlank()) {
country = "US";
}
String roleStr = getOptionValue(args, "role");
Role role = Role.ADMIN;

if (roleStr != null && !roleStr.isBlank()) {
try {
role = Role.fromString(roleStr);
if (role != Role.ADMIN && role != Role.SUPER_ADMIN) {
System.err.println("Error: Role must be either admin or super_admin.");
printUsageAndExit();
}
} catch (Exception e) {
System.err.println("Error: Invalid role value. Allowed values: admin, super_admin");
printUsageAndExit();
}
}

if (email == null || email.isBlank() ||
password == null || password.isBlank() ||
firstName == null || firstName.isBlank() ||
lastName == null || lastName.isBlank()) {
System.err.println("Error: Missing required parameters.");
printUsageAndExit();
}

try {
User admin = createAdminService.createAdminUser(firstName, lastName, email, password, country, role);
System.out.println("SUCCESS: Admin user successfully created!");
System.out.println("ID: " + admin.getId());
System.out.println("Name: " + admin.getFirstName() + " " + admin.getLastName());
System.out.println("Email: " + admin.getEmail());
System.out.println("Role: " + admin.getRole().name());
System.out.println("Country: " + admin.getCountry());
System.out.println("=================================================");
System.exit(0);
} catch (Exception e) {
System.err.println("FAILED: Error creating admin user: " + e.getMessage());
System.err.println("=================================================");
System.exit(1);
}
}
}

private String getOptionValue(ApplicationArguments args, String optionName) {
if (args.containsOption(optionName)) {
List<String> values = args.getOptionValues(optionName);
if (values != null && !values.isEmpty()) {
return values.get(0);
}
}
return null;
}

private void printUsageAndExit() {
System.out.println("Usage:");
System.out.println(" --create-admin --email=<email> --password=<password> --first-name=<first-name> --last-name=<last-name> [--country=<country-code>] [--role=admin|super_admin]");
System.out.println("=================================================");
System.exit(1);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@
import com.xtraction.api.billing.credit.repository.UserCreditBalanceRepository;
import com.xtraction.api.billing.credit.service.CreditBalanceService;
import com.xtraction.api.extraction.documents.utils.SanitizeLogging;
import com.xtraction.api.identity.loginattempts.model.LoginAttempts;
import com.xtraction.api.billing.subscription.datamodel.BillingIntervalUnit;
import com.xtraction.api.billing.subscription.datamodel.SubscriptionCurrency;
import com.xtraction.api.billing.subscription.datamodel.SubscriptionPlans;
Expand Down Expand Up @@ -145,10 +144,6 @@ private User createAdminUser() {
var verification = getVerification(adminUser, now);
adminUser.setUserVerification(verification);

var loginAttempts = new LoginAttempts();
loginAttempts.setUser(adminUser);
adminUser.setLoginAttempts(loginAttempts);

return adminUser;
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -32,22 +32,7 @@
public class AdminController {
private final AdminService adminService;

/**
* Create an admin user if none exists.
*
* @param request The sign-up request containing user details.
* @return ResponseEntity containing the created admin user data.
*/
@Operation(
summary = "Create Admin User",
description = "Allows users to register as an admin to manage the application.")
@PostMapping("/signup")
public ResponseEntity<XtractionResponse<AdminData>> createAdmin(
@Valid @RequestBody AdminSignupRequestDto request
) {
XtractionResponse<AdminData> response = adminService.createAdmin(request);
return ResponseEntity.ok(response);
}


/**
* Change the role of a user to ADMIN or MODERATOR.
Expand Down Expand Up @@ -245,41 +230,7 @@ public ResponseEntity<XtractionResponse<UserListData>> getPlanSubscribers(
return ResponseEntity.ok(adminService.getPlanSubscribers(planId, page, size));
}

/**
* Generate a One-Time Password (OTP) of specified length.
*
* @param request The request containing OTP generation parameters.
* @return ResponseEntity containing the generated OTP.
*/
@Operation(
summary = "Generate OTP",
description = "Generates a One-Time Password (OTP) of specified length.")
@PreAuthorize("hasRole('SUPER_ADMIN')")
@PostMapping("/generate-otp")
public ResponseEntity<XtractionResponse<List<String>>> generateOtp(
@Valid @RequestBody OtpRequestDto request
) {
XtractionResponse<List<String>> response = adminService.generateOtp(request);
return ResponseEntity.ok(response);
}

/**
* Fetch all active OTPs.
*
* @return ResponseEntity containing the list of active OTPs.
*/
@Operation(
summary = "Fetch Active OTPs",
description = "Fetches all active One-Time Passwords (OTPs).")
@PreAuthorize("hasRole('SUPER_ADMIN') or hasRole('ADMIN')")
@GetMapping("/active-otps")
public ResponseEntity<XtractionResponse<ActiveOtpListData>> fetchActiveOtps(
@RequestParam(defaultValue = "0") int page,
@RequestParam(defaultValue = "5") int size
) {
XtractionResponse<ActiveOtpListData> response = adminService.fetchActiveOtpCodes(page, size);
return ResponseEntity.ok(response);
}

// ==========================================
// PROMO_CODE STATISTICS
Expand Down
19 changes: 0 additions & 19 deletions src/main/java/com/xtraction/api/admin/dto/ActiveOtpData.java

This file was deleted.

This file was deleted.

This file was deleted.

This file was deleted.

Loading
Loading