Skip to content

Self-hosted, plugin-based server management.

7.7 KB
Raw Blame
import { authApi, handleApiError, type UserInfo } from "@/main-axios";
import { getConnectedRemoteApi } from "@/lib/remote-server-api";

// USER MANAGEMENT
// ============================================================================

export type UserListOptions = {
  /** Case-insensitive username substring filter. */
  search?: string;
  /** Page size. Omit to fetch every user (what the share pickers want). */
  limit?: number;
  offset?: number;
};

export async function getUserList(
  options: UserListOptions = {},
): Promise<{ users: UserInfo[]; total?: number }> {
  try {
    const api = (await getConnectedRemoteApi()) ?? authApi;
    const response = await api.get("/users/list", {
      params: {
        ...(options.search ? { search: options.search } : {}),
        ...(options.limit ? { limit: options.limit } : {}),
        ...(options.offset ? { offset: options.offset } : {}),
      },
    });
    return response.data;
  } catch (error) {
    handleApiError(error, "fetch user list");
  }
}

export async function getSessions(): Promise<{
  sessions: {
    id: string;
    userId: string;
    username?: string;
    deviceType: string;
    deviceInfo: string;
    createdAt: string;
    expiresAt: string;
    lastActiveAt: string;
    isRevoked?: boolean;
    isCurrentSession?: boolean;
  }[];
}> {
  try {
    const response = await authApi.get("/users/sessions");
    return response.data;
  } catch (error) {
    handleApiError(error, "fetch sessions");
  }
}

export async function revokeSession(
  sessionId: string,
): Promise<{ success: boolean; message: string }> {
  try {
    const response = await authApi.delete(`/users/sessions/${sessionId}`);
    return response.data;
  } catch (error) {
    handleApiError(error, "revoke session");
  }
}

export async function revokeAllUserSessions(
  userId: string,
): Promise<{ success: boolean; message: string }> {
  try {
    const response = await authApi.post("/users/sessions/revoke-all", {
      targetUserId: userId,
      exceptCurrent: false,
    });
    return response.data;
  } catch (error) {
    handleApiError(error, "revoke all user sessions");
  }
}

export interface ApiKey {
  id: string;
  name: string;
  userId: string;
  username: string | null;
  tokenPrefix: string;
  createdAt: string;
  expiresAt: string | null;
  lastUsedAt: string | null;
  isActive: boolean;
}

export interface CreatedApiKey extends ApiKey {
  token: string;
}

export async function createApiKey(
  name: string,
  userId: string,
  expiresAt?: string,
): Promise<CreatedApiKey> {
  try {
    const response = await authApi.post("/users/api-keys", {
      name,
      userId,
      expiresAt: expiresAt ?? null,
    });
    return response.data;
  } catch (error) {
    handleApiError(error, "create API key");
  }
}

export async function getApiKeys(): Promise<{ apiKeys: ApiKey[] }> {
  try {
    const response = await authApi.get("/users/api-keys");
    return response.data;
  } catch (error) {
    handleApiError(error, "fetch API keys");
  }
}

export async function deleteApiKey(
  keyId: string,
): Promise<{ success: boolean }> {
  try {
    const response = await authApi.delete(`/users/api-keys/${keyId}`);
    return response.data;
  } catch (error) {
    handleApiError(error, "delete API key");
  }
}

export async function makeUserAdmin(
  userId: string,
): Promise<Record<string, unknown>> {
  try {
    const response = await authApi.post("/users/make-admin", { userId });
    return response.data;
  } catch (error) {
    handleApiError(error, "make user admin");
  }
}

export async function removeAdminStatus(
  userId: string,
): Promise<Record<string, unknown>> {
  try {
    const response = await authApi.post("/users/remove-admin", { userId });
    return response.data;
  } catch (error) {
    handleApiError(error, "remove admin status");
  }
}

export async function deleteUser(
  username: string,
  successorUserId?: string | "none",
): Promise<Record<string, unknown>> {
  try {
    const response = await authApi.delete("/users/delete-user", {
      data: { username, successorUserId },
    });
    return response.data;
  } catch (error) {
    handleApiError(error, "delete user");
  }
}

export async function deleteAccount(
  password: string,
): Promise<Record<string, unknown>> {
  try {
    const response = await authApi.delete("/users/delete-account", {
      data: { password },
    });
    return response.data;
  } catch (error) {
    handleApiError(error, "delete account");
  }
}

// Raw axios errors propagate here so callers can detect the 409
// DATA_WIPE_REQUIRED code and re-submit with confirmDataWipe.
export async function adminResetUserPassword(
  userId: string,
  newPassword: string,
  confirmDataWipe = false,
): Promise<{ message: string; dataWiped?: boolean }> {
  const response = await authApi.post("/users/admin/reset-password", {
    userId,
    newPassword,
    confirmDataWipe,
  });
  return response.data;
}

export async function adminExportUserData(
  userId: string,
): Promise<Record<string, unknown>> {
  try {
    const response = await authApi.get(
      `/users/admin/export/${encodeURIComponent(userId)}`,
      { timeout: 120000 },
    );
    return response.data;
  } catch (error) {
    handleApiError(error, "export user data");
  }
}

export async function updateRegistrationAllowed(
  allowed: boolean,
): Promise<Record<string, unknown>> {
  try {
    const response = await authApi.patch("/users/registration-allowed", {
      allowed,
    });
    return response.data;
  } catch (error) {
    handleApiError(error, "update registration allowed");
  }
}

export async function getExternalAutoProvision(): Promise<{
  enabled: boolean;
}> {
  try {
    const response = await authApi.get("/users/external-auto-provision");
    return response.data;
  } catch (error) {
    handleApiError(error, "check OIDC auto-provision status");
  }
}

export async function updateExternalAutoProvision(
  enabled: boolean,
): Promise<Record<string, unknown>> {
  try {
    const response = await authApi.patch("/users/external-auto-provision", {
      enabled,
    });
    return response.data;
  } catch (error) {
    handleApiError(error, "update OIDC auto-provision");
  }
}

export async function getSecondFactorAfterExternalLogin(): Promise<{
  enabled: boolean;
}> {
  try {
    const response = await authApi.get(
      "/users/second-factor-after-external-login",
    );
    return response.data;
  } catch (error) {
    handleApiError(error, "check second factor after external login status");
  }
}

export async function updateSecondFactorAfterExternalLogin(
  enabled: boolean,
): Promise<Record<string, unknown>> {
  try {
    const response = await authApi.patch(
      "/users/second-factor-after-external-login",
      { enabled },
    );
    return response.data;
  } catch (error) {
    handleApiError(error, "update second factor after external login");
  }
}

export async function updatePasswordLoginAllowed(
  allowed: boolean,
): Promise<{ allowed: boolean }> {
  try {
    const response = await authApi.patch("/users/password-login-allowed", {
      allowed,
    });
    return response.data;
  } catch (error) {
    handleApiError(error, "update password login allowed");
  }
}

export async function getPasswordResetAllowed(): Promise<boolean> {
  try {
    const response = await authApi.get("/users/password-reset-allowed");
    return response.data.allowed;
  } catch (error) {
    handleApiError(error, "get password reset allowed");
  }
}

export async function updatePasswordResetAllowed(
  allowed: boolean,
): Promise<{ allowed: boolean }> {
  try {
    const response = await authApi.patch("/users/password-reset-allowed", {
      allowed,
    });
    return response.data;
  } catch (error) {
    handleApiError(error, "update password reset allowed");
  }
}

// ============================================================================