@nestbox-ai/cli 1.0.21 → 1.0.23

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,64 @@
1
+ import chalk from "chalk";
2
+ import { Configuration } from "@nestbox-ai/admin";
3
+ import { getAuthToken } from "./auth";
4
+
5
+ export interface AuthResult {
6
+ authToken: {
7
+ token: string;
8
+ serverUrl: string;
9
+ accessToken?: string;
10
+ };
11
+ configuration: Configuration;
12
+ }
13
+
14
+ /**
15
+ * Common authentication and configuration setup
16
+ * Returns authentication token and configured API client
17
+ * Exits the process if authentication fails
18
+ */
19
+ export function setupAuthAndConfig(): AuthResult | null {
20
+ const authToken = getAuthToken();
21
+
22
+ if (!authToken) {
23
+ console.error(chalk.red('No authentication token found. Please login first.'));
24
+ return null;
25
+ }
26
+
27
+ const configuration = new Configuration({
28
+ basePath: authToken.serverUrl,
29
+ baseOptions: {
30
+ headers: {
31
+ "Authorization": authToken.token,
32
+ }
33
+ }
34
+ });
35
+
36
+ return {
37
+ authToken,
38
+ configuration
39
+ };
40
+ }
41
+
42
+ /**
43
+ * Wrapper function that ensures authentication is set up before executing a callback
44
+ * Automatically handles authentication errors and provides configured API instances
45
+ */
46
+ export async function withAuth<T>(
47
+ callback: (authResult: AuthResult) => Promise<T>
48
+ ): Promise<T | void> {
49
+ const authResult = setupAuthAndConfig();
50
+
51
+ if (!authResult) {
52
+ return;
53
+ }
54
+
55
+ try {
56
+ return await callback(authResult);
57
+ } catch (error: any) {
58
+ if (error.response && error.response.status === 401) {
59
+ console.error(chalk.red('Authentication token has expired. Please login again using "nestbox login <domain>".'));
60
+ } else {
61
+ throw error; // Re-throw non-auth errors
62
+ }
63
+ }
64
+ }