File size: 1,720 Bytes
4782147
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import { getSession } from "auth/server";
import { workflowRepository } from "lib/db/repository";
import { canCreateWorkflow, canEditWorkflow } from "lib/auth/permissions";

export async function GET() {
  const session = await getSession();
  if (!session) {
    return Response.json([]);
  }
  const workflows = await workflowRepository.selectAll(session.user.id);
  return Response.json(workflows);
}

export async function POST(request: Request) {
  const {
    name,
    description,
    icon,
    id,
    isPublished,
    visibility,
    noGenerateInputNode,
  } = await request.json();

  const session = await getSession();
  if (!session) {
    return new Response("Unauthorized", { status: 401 });
  }

  // Check if user has permission to create/edit workflows
  if (id) {
    // Editing existing workflow
    const canEdit = await canEditWorkflow();
    if (!canEdit) {
      return Response.json(
        { error: "You don't have permission to edit workflows" },
        { status: 403 },
      );
    }
    const hasAccess = await workflowRepository.checkAccess(
      id,
      session.user.id,
      false,
    );
    if (!hasAccess) {
      return new Response("Unauthorized", { status: 401 });
    }
  } else {
    // Creating new workflow
    const canCreate = await canCreateWorkflow();
    if (!canCreate) {
      return Response.json(
        { error: "You don't have permission to create workflows" },
        { status: 403 },
      );
    }
  }

  const workflow = await workflowRepository.save(
    {
      name,
      description,
      id,
      isPublished,
      visibility,
      icon,
      userId: session.user.id,
    },
    noGenerateInputNode,
  );

  return Response.json(workflow);
}