File size: 9,940 Bytes
05c5ed5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
import "server-only";
import { getSession } from "./auth-instance";
import { getIsUserAdmin } from "lib/user/utils";
import { admin, editor, user as userRole } from "./roles";
import type { BetterAuthRole } from "./types";
import { parseRoleString, isBetterAuthRole } from "./types";

/**
 * Simple permission helpers that wrap Better Auth's role system
 *
 * Philosophy:
 * - Keep it simple and clear
 * - Users can always manage themselves
 * - Only admins can manage other users
 * - Easy to show/hide UI elements
 * - Easy to extend for workflows, etc. later
 */

/**
 * Check if user has admin permissions (for showing/hiding admin areas)
 */
export async function hasAdminPermission(): Promise<boolean> {
  try {
    const session = await getSession();
    if (!session?.user) return false;

    const isAdmin = getIsUserAdmin(session.user);
    return isAdmin;
  } catch (error) {
    console.error("Error checking admin permission:", error);
    return false;
  }
}

/**
 * Check if user can list other users
 * Currently: only admins can list users
 */
export async function canListUsers(): Promise<boolean> {
  return await hasAdminPermission();
}

/**
 * Check if user can manage other users (create, edit, delete, etc.)
 * Currently: only admins can manage other users
 */
export async function canManageUsers(): Promise<boolean> {
  return await hasAdminPermission();
}

/**
 * Check if user can manage a specific user (themselves OR has manage permission)
 */
export async function canManageUser(targetUserId: string): Promise<boolean> {
  try {
    const session = await getSession();
    if (!session?.user) return false;

    // Can always manage own profile
    if (session.user.id === targetUserId) return true;

    // Or has admin permissions to manage other users
    return await canManageUsers();
  } catch (error) {
    console.error("Error checking user management permission:", error);
    return false;
  }
}

/**
 * Require admin permissions or throw error
 */
export async function requireAdminPermission(
  action: string = "perform this action",
): Promise<void> {
  const hasPermission = await hasAdminPermission();
  if (!hasPermission) {
    throw new Error(`Unauthorized: Admin access required to ${action}`);
  }
}

/**
 * Require user list permissions or throw error
 */
export async function requireUserListPermission(
  action: string = "list users",
): Promise<void> {
  const hasPermission = await canListUsers();
  if (!hasPermission) {
    throw new Error(`Unauthorized: Permission required to ${action}`);
  }
}

/**
 * Require user management permissions or throw error
 */
export async function requireUserManagePermission(
  action: string = "manage users",
): Promise<void> {
  const hasPermission = await canManageUsers();
  if (!hasPermission) {
    throw new Error(`Unauthorized: Permission required to ${action}`);
  }
}

/**
 * Require permission to manage specific user or throw error
 */
export async function requireUserManagePermissionFor(
  targetUserId: string,
  action: string = "manage this user",
): Promise<void> {
  const hasPermission = await canManageUser(targetUserId);
  if (!hasPermission) {
    throw new Error(`Unauthorized: Permission required to ${action}`);
  }
}

/**
 * Get current user session or null
 */
export async function getCurrentUser() {
  try {
    const session = await getSession();
    return session?.user || null;
  } catch {
    return null;
  }
}

/**
 * Check if user is editor or admin (can create/edit resources)
 */
export async function hasEditorPermission(): Promise<boolean> {
  try {
    const session = await getSession();
    if (!session?.user) return false;

    // Check if user is admin or editor
    return session.user.role === "admin" || session.user.role === "editor";
  } catch (error) {
    console.error("Error checking editor permission:", error);
    return false;
  }
}

/**
 * Get the role permissions based on user's role string
 */
function getRolePermissions(role: string | undefined | null): BetterAuthRole {
  const cleanRole = parseRoleString(role);

  switch (cleanRole) {
    case "admin":
      return admin as BetterAuthRole;
    case "editor":
      return editor as BetterAuthRole;
    case "user":
    default:
      return userRole as BetterAuthRole;
  }
}

/**
 * Check if role has specific permission for a resource
 */
function hasPermission(
  userRoleString: string | undefined | null,
  permission:
    | "use"
    | "create"
    | "list"
    | "delete"
    | "update"
    | "view"
    | "share",
  resource: "agent" | "workflow" | "mcp",
): boolean {
  const roleObject = getRolePermissions(userRoleString);

  // Validate role object structure
  if (!isBetterAuthRole(roleObject)) {
    console.error("Invalid role object structure");
    return false;
  }

  const statements = roleObject.statements;
  const resourcePermissions = statements[resource] || [];
  return (
    Array.isArray(resourcePermissions) &&
    resourcePermissions.includes(permission)
  );
}

/**
 * Check if user can create agents
 */
export async function canCreateAgent(): Promise<boolean> {
  try {
    const session = await getSession();
    if (!session?.user) return false;

    return hasPermission(session.user.role, "create", "agent");
  } catch (error) {
    console.error("Error checking agent create permission:", error);
    return false;
  }
}

/**
 * Check if user can edit agents
 */
export async function canEditAgent(): Promise<boolean> {
  try {
    const session = await getSession();
    if (!session?.user) return false;

    return hasPermission(session.user.role, "update", "agent");
  } catch (error) {
    console.error("Error checking agent edit permission:", error);
    return false;
  }
}

/**
 * Check if user can delete agents
 */
export async function canDeleteAgent(): Promise<boolean> {
  try {
    const session = await getSession();
    if (!session?.user) return false;

    return hasPermission(session.user.role, "delete", "agent");
  } catch (error) {
    console.error("Error checking agent delete permission:", error);
    return false;
  }
}

/**
 * Check if user can create workflows
 */
export async function canCreateWorkflow(): Promise<boolean> {
  try {
    const session = await getSession();
    if (!session?.user) return false;

    return hasPermission(session.user.role, "create", "workflow");
  } catch (error) {
    console.error("Error checking workflow create permission:", error);
    return false;
  }
}

/**
 * Check if user can edit workflows
 */
export async function canEditWorkflow(): Promise<boolean> {
  try {
    const session = await getSession();
    if (!session?.user) return false;

    return hasPermission(session.user.role, "update", "workflow");
  } catch (error) {
    console.error("Error checking workflow edit permission:", error);
    return false;
  }
}

/**
 * Check if user can delete workflows
 */
export async function canDeleteWorkflow(): Promise<boolean> {
  try {
    const session = await getSession();
    if (!session?.user) return false;

    return hasPermission(session.user.role, "delete", "workflow");
  } catch (error) {
    console.error("Error checking workflow delete permission:", error);
    return false;
  }
}

/**
 * Check if user can create MCP connections
 */
export async function canCreateMCP(): Promise<boolean> {
  try {
    const session = await getSession();
    if (!session?.user) return false;

    return hasPermission(session.user.role, "create", "mcp");
  } catch (error) {
    console.error("Error checking MCP create permission:", error);
    return false;
  }
}

/**
 * Check if user can edit MCP connections
 */
export async function canEditMCP(): Promise<boolean> {
  try {
    const session = await getSession();
    if (!session?.user) return false;

    return hasPermission(session.user.role, "update", "mcp");
  } catch (error) {
    console.error("Error checking MCP edit permission:", error);
    return false;
  }
}

/**
 * Check if user can change visibility of MCP connections
 */
export async function canChangeVisibilityMCP(): Promise<boolean> {
  try {
    const session = await getSession();
    if (!session?.user) return false;

    return hasPermission(session.user.role, "share", "mcp");
  } catch (error) {
    console.error("Error checking MCP visibility change permission:", error);
    return false;
  }
}

/**
 * Check if user can delete MCP connections
 */
export async function canDeleteMCP(): Promise<boolean> {
  try {
    const session = await getSession();
    if (!session?.user) return false;

    return hasPermission(session.user.role, "delete", "mcp");
  } catch (error) {
    console.error("Error checking MCP delete permission:", error);
    return false;
  }
}

/**
 * Require editor permissions or throw error
 */
export async function requireEditorPermission(
  action: string = "perform this action",
): Promise<void> {
  const hasPermission = await hasEditorPermission();
  if (!hasPermission) {
    throw new Error(
      `Unauthorized: Editor or Admin access required to ${action}`,
    );
  }
}

/**
 * Check if user can manage a specific MCP server
 * Users can manage their own servers, admins can manage all
 */
export async function canManageMCPServer(
  mcpOwnerId: string,
  visibility: string = "private",
): Promise<boolean> {
  try {
    const session = await getSession();
    if (!session?.user) return false;

    // Admins can manage all MCP servers
    if (session.user.role === "admin") return true;

    // Users can only manage their own private MCP servers
    if (session.user.id === mcpOwnerId && visibility === "private") return true;

    return false;
  } catch (error) {
    console.error("Error checking MCP management permission:", error);
    return false;
  }
}

/**
 * Check if user can share MCP servers (admin only)
 */
export async function canShareMCPServer(): Promise<boolean> {
  return await hasAdminPermission();
}