Pre-built Routes
The @elcto/api library includes pre-built route functions for common API operations. These functions handle GraphQL queries internally and provide typed responses.
User Routes
Functions for fetching user data.
import {
getUserProfile,
getUserPermissions,
getUserAccounts,
checkUserExists,
} from "@elcto/api";
getUserProfile
Get a user's profile information.
const profile = await getUserProfile(userId, headers);
Parameters:
| Parameter | Type | Description |
|---|---|---|
userId | string | User ID |
headers | Record<string, string> | Optional headers (Authorization) |
Returns: Promise<UserProfile>
getUserPermissions
Get a user's roles and permissions.
const permissions = await getUserPermissions(userId, headers);
if (permissions.is_super_admin) {
// Full access
}
if (permissions.role_ids.includes("role_admin")) {
// Admin access
}
Parameters:
| Parameter | Type | Description |
|---|---|---|
userId | string | User ID |
headers | Record<string, string> | Optional headers |
Returns: Promise<UserPermissions>
getUserAccounts
Get a user's connected platform accounts.
const accounts = await getUserAccounts(userId, headers);
const discordAccount = accounts.find(a => a.platform_slug === "discord");
Parameters:
| Parameter | Type | Description |
|---|---|---|
userId | string | User ID |
headers | Record<string, string> | Optional headers |
Returns: Promise<PlatformAccount[]>
checkUserExists
Check if a user exists by ID.
const exists = await checkUserExists(userId, headers);
if (!exists) {
return { error: "User not found" };
}
Parameters:
| Parameter | Type | Description |
|---|---|---|
userId | string | User ID |
headers | Record<string, string> | Optional headers |
Returns: Promise<boolean>
Session Routes
Functions for managing user sessions.
import {
getActiveSessions,
revokeSession,
revokeAllOtherSessions,
} from "@elcto/api";
getActiveSessions
Get all active sessions for a user.
const { sessions, currentSessionId } = await getActiveSessions(userId, headers);
// Mark current session
const sessionsWithCurrent = sessions.map(s => ({
...s,
isCurrent: s.id === currentSessionId,
}));
Parameters:
| Parameter | Type | Description |
|---|---|---|
userId | string | User ID |
headers | Record<string, string> | Optional headers |
Returns: Promise<ActiveSessionsResponse>
interface ActiveSessionsResponse {
sessions: ActiveSession[];
currentSessionId: string | null;
}
revokeSession
Revoke a specific session.
const result = await revokeSession(sessionToken, reason, headers);
if (result.success) {
console.log("Session revoked");
}
Parameters:
| Parameter | Type | Description |
|---|---|---|
sessionToken | string | Session token to revoke |
reason | string | Revocation reason (e.g., "user_initiated") |
headers | Record<string, string> | Optional headers |
Returns: Promise<RevokeSessionResponse>
interface RevokeSessionResponse {
success: boolean;
error?: string;
}
revokeAllOtherSessions
Revoke all sessions except the current one.
const result = await revokeAllOtherSessions(userId, currentSessionId, headers);
console.log(`Revoked ${result.revokedCount} sessions`);
Parameters:
| Parameter | Type | Description |
|---|---|---|
userId | string | User ID |
currentSessionId | string | Current session ID to keep |
headers | Record<string, string> | Optional headers |
Returns: Promise<RevokeAllSessionsResponse>
interface RevokeAllSessionsResponse {
success: boolean;
revokedCount: number;
error?: string;
}
Audit Routes
Functions for accessing and managing audit logs.
import {
getMyAuditLog,
getUserAuditLog,
getAllAuditEvents,
logAuditEvent,
reportAuditEvent,
getMyAuditReports,
} from "@elcto/api";
getMyAuditLog
Get the current user's activity log.
const auditPage = await getMyAuditLog(
{
page: 1,
limit: 20,
eventType: "login",
status: "success",
},
headers
);
console.log(`Found ${auditPage.totalCount} events`);
Parameters:
| Parameter | Type | Description |
|---|---|---|
query | AuditEventQuery | Query parameters |
headers | Record<string, string> | Optional headers |
Returns: Promise<AuditEventPage>
getUserAuditLog
Get audit log for a specific user (admin only).
const auditPage = await getUserAuditLog(
userId,
{ page: 1, limit: 50 },
headers
);
Parameters:
| Parameter | Type | Description |
|---|---|---|
userId | string | Target user ID |
query | AuditEventQuery | Query parameters |
headers | Record<string, string> | Optional headers |
Returns: Promise<AuditEventPage>
Required Permission: audit:read
getAllAuditEvents
Get all audit events with advanced filtering (admin only).
const auditPage = await getAllAuditEvents(
{
page: 1,
limit: 50,
eventType: "login_failed",
sourceService: "id",
startDate: "2024-01-01T00:00:00Z",
endDate: "2024-01-31T23:59:59Z",
sortField: "createdAt",
sortDirection: "desc",
isReported: true,
},
headers
);
Query Parameters:
| Parameter | Type | Description |
|---|---|---|
page | number | Page number (1-indexed) |
limit | number | Items per page |
eventType | string | Filter by event type |
eventTypes | string | Comma-separated event types |
userId | string | Filter by user ID |
userSearch | string | Search by username |
resourceType | string | Filter by resource type |
status | string | Filter by status ("success" or "failure") |
sourceService | string | Filter by source service |
startDate | string | Start date (ISO 8601) |
endDate | string | End date (ISO 8601) |
sortField | string | Sort field |
sortDirection | string | "asc" or "desc" |
isReported | boolean | Filter reported events |
Required Permission: audit:read
logAuditEvent
Log an audit event programmatically.
import { AuditEventTypes, AuditResourceTypes, AuditSourceServices } from "@elcto/api";
const event = await logAuditEvent(
{
userId: user.id,
eventType: AuditEventTypes.CUSTOM_ACTION,
resourceType: AuditResourceTypes.USER,
resourceId: targetUserId,
description: "Custom action performed",
metadata: { action: "example" },
ipAddress: clientIp,
userAgent: userAgent,
status: "success",
sourceService: AuditSourceServices.BACKEND,
},
headers
);
Parameters:
| Field | Type | Required | Description |
|---|---|---|---|
userId | string | No | User ID (optional for system events) |
eventType | string | Yes | Event type constant |
resourceType | string | No | Resource type |
resourceId | string | No | Resource ID |
actorId | string | No | Actor user ID (if different from userId) |
description | string | No | Human-readable description |
metadata | object | No | Additional data |
ipAddress | string | No | Client IP address |
userAgent | string | No | Client user agent |
status | string | No | "success" or "failure" |
errorMessage | string | No | Error message (if failure) |
sourceService | string | No | Source service identifier |
reportAuditEvent
Report an audit event as suspicious activity.
const result = await reportAuditEvent(
{
auditEventId: event.id,
reason: "not_me",
description: "I didn't perform this action",
},
headers
);
if (result.success) {
console.log("Report submitted:", result.report?.id);
}
Input:
| Field | Type | Required | Description |
|---|---|---|---|
auditEventId | string | Yes | Audit event ID to report |
reason | string | Yes | Reason: "not_me", "suspicious", "unknown_device", "unknown_location", "other" |
description | string | No | Additional details |
Returns: Promise<ReportAuditEventResponse>
getMyAuditReports
Get the current user's submitted reports.
const reports = await getMyAuditReports(headers);
const pendingReports = reports.filter(r => r.status === "pending");
Returns: Promise<AuditEventReport[]>
Admin Audit Routes
Additional audit functions for administrators.
import {
getAllAuditReports,
updateAuditReport,
} from "@elcto/api";
getAllAuditReports
Get all audit reports (admin only).
const reportPage = await getAllAuditReports(
{
page: 1,
limit: 20,
status: "pending",
},
headers
);
Query Parameters:
| Parameter | Type | Description |
|---|---|---|
page | number | Page number |
limit | number | Items per page |
status | string | Filter by status: "pending", "reviewed", "resolved", "dismissed" |
Required Permission: audit:read
updateAuditReport
Update an audit report status (admin only).
const result = await updateAuditReport(
{
reportId: report.id,
status: "resolved",
resolutionNotes: "Confirmed unauthorized access. User notified and security measures taken.",
},
headers
);
Input:
| Field | Type | Required | Description |
|---|---|---|---|
reportId | string | Yes | Report ID |
status | string | Yes | New status: "reviewed", "resolved", "dismissed" |
resolutionNotes | string | No | Notes about resolution |
Required Permission: audit:write
Usage in Next.js API Routes
Example: Session Management
// src/app/api/sessions/route.ts
import { NextRequest, NextResponse } from "next/server";
import { getServerSession } from "next-auth";
import { authOptions } from "@/lib/auth";
import { getActiveSessions, handleApiError } from "@elcto/api";
export async function GET(request: NextRequest) {
try {
const session = await getServerSession(authOptions);
if (!session?.user?.id) {
return NextResponse.json(
{ error: "Unauthorized", code: "UNAUTHORIZED" },
{ status: 401 }
);
}
const headers = {
Authorization: `Bearer ${session.accessToken}`,
};
const result = await getActiveSessions(session.user.id, headers);
return NextResponse.json(result);
} catch (error) {
return handleApiError(request, error, {
route: "sessions/list",
defaultMessage: "Failed to fetch sessions",
});
}
}
Example: Audit Activity Page
// src/app/api/account/activity/route.ts
import { NextRequest, NextResponse } from "next/server";
import { getServerSession } from "next-auth";
import { authOptions } from "@/lib/auth";
import { getMyAuditLog, handleApiError } from "@elcto/api";
export async function GET(request: NextRequest) {
try {
const session = await getServerSession(authOptions);
if (!session?.user?.id) {
return NextResponse.json(
{ error: "Unauthorized", code: "UNAUTHORIZED" },
{ status: 401 }
);
}
const { searchParams } = new URL(request.url);
const page = parseInt(searchParams.get("page") || "1");
const limit = parseInt(searchParams.get("limit") || "20");
const eventType = searchParams.get("eventType") || undefined;
const headers = {
Authorization: `Bearer ${session.accessToken}`,
};
const result = await getMyAuditLog(
{ page, limit, eventType },
headers
);
return NextResponse.json(result);
} catch (error) {
return handleApiError(request, error, {
route: "account/activity",
defaultMessage: "Failed to fetch activity log",
});
}
}