Skip to content

A modern platform for visual, flexible, and extensible graph-based investigations. For cybersecurity analysts and investigators.

feat: no supabase dependency

dextmorgna6727f123236
diff --git a/.env.example b/.env.example
index 75c60c11..77dc153d 100644
--- a/.env.example
+++ b/.env.example
@@ -1,127 +1,11 @@
-############
-# Secrets
-# YOU MUST CHANGE THESE BEFORE GOING INTO PRODUCTION
-############
-
-POSTGRES_PASSWORD=your-super-secret-and-long-postgres-password
-JWT_SECRET=your-super-secret-jwt-token-with-at-least-32-characters-long
-ANON_KEY=ANON_KEY
-SERVICE_ROLE_KEY=SERVICE_ROLE_KEY
-DASHBOARD_USERNAME=supabase
-DASHBOARD_PASSWORD=this_password_is_insecure_and_should_be_updated
-SECRET_KEY_BASE=SECRET_KEY_BASE
-VAULT_ENC_KEY=your-encryption-key-32-chars-min
-
-
-############
-# Database - You can change these to any PostgreSQL database that has logical replication enabled.
-############
-
-POSTGRES_HOST=db
-POSTGRES_DB=postgres
-POSTGRES_PORT=5432
-# default user is postgres
-
-
-############
-# Supavisor -- Database pooler
-############
-POOLER_PROXY_PORT_TRANSACTION=6543
-POOLER_DEFAULT_POOL_SIZE=20
-POOLER_MAX_CLIENT_CONN=100
-POOLER_TENANT_ID=your-tenant-id
-
-
-############
-# API Proxy - Configuration for the Kong Reverse proxy.
-############
-
-KONG_HTTP_PORT=8000
-KONG_HTTPS_PORT=8443
-
-
-############
-# API - Configuration for PostgREST.
-############
-
-PGRST_DB_SCHEMAS=public,storage,graphql_public
-
-
-############
-# Auth - Configuration for the GoTrue authentication server.
-############
-
-## General
-SITE_URL=http://localhost:3000
-ADDITIONAL_REDIRECT_URLS=
-JWT_EXPIRY=3600
-DISABLE_SIGNUP=false
-API_EXTERNAL_URL=http://localhost:8000
-
-## Mailer Config
-MAILER_URLPATHS_CONFIRMATION="/auth/v1/verify"
-MAILER_URLPATHS_INVITE="/auth/v1/verify"
-MAILER_URLPATHS_RECOVERY="/auth/v1/verify"
-MAILER_URLPATHS_EMAIL_CHANGE="/auth/v1/verify"
-
-## Email auth
-ENABLE_EMAIL_SIGNUP=true
-ENABLE_EMAIL_AUTOCONFIRM=true
-SMTP_HOST=supabase-mail
-SMTP_PORT=2500
-SMTP_USER=fake_mail_user
-SMTP_PASS=fake_mail_password
-SMTP_SENDER_NAME=fake_sender
-ENABLE_ANONYMOUS_USERS=false
-
-## Phone auth
-ENABLE_PHONE_SIGNUP=true
-ENABLE_PHONE_AUTOCONFIRM=true
-
-
-############
-# Studio - Configuration for the Dashboard
-############
-
-STUDIO_DEFAULT_ORGANIZATION=Default Organization
-STUDIO_DEFAULT_PROJECT=Default Project
-
-STUDIO_PORT=3000
-# replace if you intend to use Studio outside of localhost
-SUPABASE_PUBLIC_URL=http://localhost:8000
-
-# Enable webp support
-IMGPROXY_ENABLE_WEBP_DETECTION=true
-
-# Add your OpenAI API key to enable SQL Editor Assistant
-OPENAI_API_KEY=
-
-
-############
-# Functions - Configuration for Functions
-############
-# NOTE: VERIFY_JWT applies to all functions. Per-function VERIFY_JWT is not supported yet.
-FUNCTIONS_VERIFY_JWT=false
-
-
-############
-# Logs - Configuration for Logflare
-# Please refer to https://supabase.com/docs/reference/self-hosting-analytics/introduction
-############
-
-LOGFLARE_LOGGER_BACKEND_API_KEY=your-super-secret-and-long-logflare-key
-
-# Change vector.toml sinks to reflect this change
-LOGFLARE_API_KEY=your-super-secret-and-long-logflare-key
-
-# Docker socket location - this value will differ depending on your OS
-DOCKER_SOCKET_LOCATION=/var/run/docker.sock
-
-# Google Cloud Project details
-GOOGLE_PROJECT_ID=GOOGLE_PROJECT_ID
-GOOGLE_PROJECT_NUMBER=GOOGLE_PROJECT_NUMBER
-
+NODE_ENV=production
+NEXT_PUBLIC_AUTH_REDIRECT=http://app.flowsint.localhost/auth/callback
+HIBP_API_KEY=70b78a3256c84d09b79cd4953d77bdf3
+NEXT_PUBLIC_FLOWSINT_API=https://api.flowsint.localhost/api
+NEXT_PUBLIC_DOCKER_FLOWSINT_API=http://flowsint-api:5000/api
+NEXT_PUBLIC_SUPABASE_ANON_KEY=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6InR5bGhuc2F5eXRhb2FhaXFzZ2RwIiwicm9sZSI6ImFub24iLCJpYXQiOjE3MzgzMzY3MzAsImV4cCI6MjA1MzkxMjczMH0.iVcpz8RpOgzVSamp_tNQQmjdLL9_Olx6m4LfsLVw1bg
+AUTH_SECRET="superscretchangeitplz" # Added by `npx auth`. Read more: https://cli.authjs.dev
+AUTH_TRUST_HOST=true
NEO4J_URI_BOLT=bolt://neo4j:7687
NEO4J_URI_WEB=https://neo4j.flowsint.localhost
NEO4J_USER=neo4j
diff --git a/backend/.env.example b/backend/.env.example
deleted file mode 100644
index 27eefa0d..00000000
--- a/backend/.env.example
+++ /dev/null
@@ -1,135 +0,0 @@
-############
-# Secrets
-# YOU MUST CHANGE THESE BEFORE GOING INTO PRODUCTION
-############
-
-POSTGRES_PASSWORD=your-super-secret-and-long-postgres-password
-JWT_SECRET=your-super-secret-jwt-token-with-at-least-32-characters-long
-ANON_KEY=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyAgCiAgICAicm9sZSI6ICJhbm9uIiwKICAgICJpc3MiOiAic3VwYWJhc2UtZGVtbyIsCiAgICAiaWF0IjogMTY0MTc2OTIwMCwKICAgICJleHAiOiAxNzk5NTM1NjAwCn0.dc_X5iR_VP_qT0zsiyj_I_OZ2T9FtRU2BBNWN8Bu4GE
-SERVICE_ROLE_KEY=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyAgCiAgICAicm9sZSI6ICJzZXJ2aWNlX3JvbGUiLAogICAgImlzcyI6ICJzdXBhYmFzZS1kZW1vIiwKICAgICJpYXQiOiAxNjQxNzY5MjAwLAogICAgImV4cCI6IDE3OTk1MzU2MDAKfQ.DaYlNEoUrrEn2Ig7tqibS-PHK5vgusbcbo7X36XVt4Q
-DASHBOARD_USERNAME=supabase
-DASHBOARD_PASSWORD=this_password_is_insecure_and_should_be_updated
-SECRET_KEY_BASE=UpNVntn3cDxHJpq99YMc1T1AQgQpc8kfYTuRgBiYa15BLrx8etQoXz3gZv1/u2oq
-VAULT_ENC_KEY=your-encryption-key-32-chars-min
-
-
-############
-# Database - You can change these to any PostgreSQL database that has logical replication enabled.
-############
-
-POSTGRES_HOST=db
-POSTGRES_DB=postgres
-POSTGRES_PORT=5432
-# default user is postgres
-
-
-############
-# Supavisor -- Database pooler
-############
-POOLER_PROXY_PORT_TRANSACTION=6543
-POOLER_DEFAULT_POOL_SIZE=20
-POOLER_MAX_CLIENT_CONN=100
-POOLER_TENANT_ID=your-tenant-id
-
-
-############
-# API Proxy - Configuration for the Kong Reverse proxy.
-############
-
-KONG_HTTP_PORT=8000
-KONG_HTTPS_PORT=8443
-
-
-############
-# API - Configuration for PostgREST.
-############
-
-PGRST_DB_SCHEMAS=public,storage,graphql_public
-
-
-############
-# Auth - Configuration for the GoTrue authentication server.
-############
-
-## General
-SITE_URL=http://localhost:3000
-ADDITIONAL_REDIRECT_URLS=
-JWT_EXPIRY=3600
-DISABLE_SIGNUP=false
-API_EXTERNAL_URL=http://localhost:8000
-
-## Mailer Config
-MAILER_URLPATHS_CONFIRMATION="/auth/v1/verify"
-MAILER_URLPATHS_INVITE="/auth/v1/verify"
-MAILER_URLPATHS_RECOVERY="/auth/v1/verify"
-MAILER_URLPATHS_EMAIL_CHANGE="/auth/v1/verify"
-
-## Email auth
-ENABLE_EMAIL_SIGNUP=true
-ENABLE_EMAIL_AUTOCONFIRM=true
-SMTP_HOST=supabase-mail
-SMTP_PORT=2500
-SMTP_USER=fake_mail_user
-SMTP_PASS=fake_mail_password
-SMTP_SENDER_NAME=fake_sender
-ENABLE_ANONYMOUS_USERS=false
-
-## Phone auth
-ENABLE_PHONE_SIGNUP=true
-ENABLE_PHONE_AUTOCONFIRM=true
-
-
-############
-# Studio - Configuration for the Dashboard
-############
-
-STUDIO_DEFAULT_ORGANIZATION=Default Organization
-STUDIO_DEFAULT_PROJECT=Default Project
-
-STUDIO_PORT=3000
-# replace if you intend to use Studio outside of localhost
-SUPABASE_PUBLIC_URL=http://localhost:8000
-
-# Enable webp support
-IMGPROXY_ENABLE_WEBP_DETECTION=true
-
-# Add your OpenAI API key to enable SQL Editor Assistant
-OPENAI_API_KEY=
-
-
-############
-# Functions - Configuration for Functions
-############
-# NOTE: VERIFY_JWT applies to all functions. Per-function VERIFY_JWT is not supported yet.
-FUNCTIONS_VERIFY_JWT=false
-
-
-############
-# Logs - Configuration for Logflare
-# Please refer to https://supabase.com/docs/reference/self-hosting-analytics/introduction
-############
-
-LOGFLARE_LOGGER_BACKEND_API_KEY=your-super-secret-and-long-logflare-key
-
-# Change vector.toml sinks to reflect this change
-LOGFLARE_API_KEY=your-super-secret-and-long-logflare-key
-
-# Docker socket location - this value will differ depending on your OS
-DOCKER_SOCKET_LOCATION=/var/run/docker.sock
-
-# Google Cloud Project details
-GOOGLE_PROJECT_ID=GOOGLE_PROJECT_ID
-GOOGLE_PROJECT_NUMBER=GOOGLE_PROJECT_NUMBER
-
-
-## FLOWSINT-API
-
-SUPABASE_URL=http://localhost:8000
-SUPABASE_KEY=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyAgCiAgICAicm9sZSI6ICJhbm9uIiwKICAgICJpc3MiOiAic3VwYWJhc2UtZGVtbyIsCiAgICAiaWF0IjogMTY0MTc2OTIwMCwKICAgICJleHAiOiAxNzk5NTM1NjAwCn0.dc_X5iR_VP_qT0zsiyj_I_OZ2T9FtRU2BBNWN8Bu4GE
-
-## FLOWSINT-WEB
-
-NEXT_PUBLIC_AUTH_REDIRECT=http://localhost:3000/auth/callback
-NEXT_PUBLIC_SUPABASE_URL=https://tylhnsayytaoaaiqsgdp.supabase.co
-NEXT_PUBLIC_SUPABASE_ANON_KEY=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6InR5bGhuc2F5eXRhb2FhaXFzZ2RwIiwicm9sZSI6ImFub24iLCJpYXQiOjE3MzgzMzY3MzAsImV4cCI6MjA1MzkxMjczMH0.iVcpz8RpOgzVSamp_tNQQmjdLL9_Olx6m4LfsLVw1bg
\ No newline at end of file
diff --git a/backend/.gitignore b/backend/.gitignore
deleted file mode 100644
index a1e9dc61..00000000
--- a/backend/.gitignore
+++ /dev/null
@@ -1,5 +0,0 @@
-volumes/db/data
-volumes/storage
-.env
-test.http
-docker-compose.override.yml
diff --git a/backend/dev/data.sql b/backend/dev/data.sql
deleted file mode 100644
index 23280041..00000000
--- a/backend/dev/data.sql
+++ /dev/null
@@ -1,48 +0,0 @@
-create table profiles (
- id uuid references auth.users not null,
- updated_at timestamp with time zone,
- username text unique,
- avatar_url text,
- website text,
-
- primary key (id),
- unique(username),
- constraint username_length check (char_length(username) >= 3)
-);
-
-alter table profiles enable row level security;
-
-create policy "Public profiles are viewable by the owner."
- on profiles for select
- using ( auth.uid() = id );
-
-create policy "Users can insert their own profile."
- on profiles for insert
- with check ( auth.uid() = id );
-
-create policy "Users can update own profile."
- on profiles for update
- using ( auth.uid() = id );
-
--- Set up Realtime
-begin;
- drop publication if exists supabase_realtime;
- create publication supabase_realtime;
-commit;
-alter publication supabase_realtime add table profiles;
-
--- Set up Storage
-insert into storage.buckets (id, name)
-values ('avatars', 'avatars');
-
-create policy "Avatar images are publicly accessible."
- on storage.objects for select
- using ( bucket_id = 'avatars' );
-
-create policy "Anyone can upload an avatar."
- on storage.objects for insert
- with check ( bucket_id = 'avatars' );
-
-create policy "Anyone can update an avatar."
- on storage.objects for update
- with check ( bucket_id = 'avatars' );
diff --git a/backend/dev/docker-compose.dev.yml b/backend/dev/docker-compose.dev.yml
deleted file mode 100644
index ca19a0ad..00000000
--- a/backend/dev/docker-compose.dev.yml
+++ /dev/null
@@ -1,34 +0,0 @@
-version: "3.8"
-
-services:
- studio:
- build:
- context: ..
- dockerfile: studio/Dockerfile
- target: dev
- ports:
- - 8082:8082
- mail:
- container_name: supabase-mail
- image: inbucket/inbucket:3.0.3
- ports:
- - '2500:2500' # SMTP
- - '9000:9000' # web interface
- - '1100:1100' # POP3
- auth:
- environment:
- - GOTRUE_SMTP_USER=
- - GOTRUE_SMTP_PASS=
- meta:
- ports:
- - 5555:8080
- db:
- restart: 'no'
- volumes:
- # Always use a fresh database when developing
- - /var/lib/postgresql/data
- # Seed data should be inserted last (alphabetical order)
- - ./dev/data.sql:/docker-entrypoint-initdb.d/seed.sql
- storage:
- volumes:
- - /var/lib/storage
diff --git a/backend/supabase/.gitignore b/backend/supabase/.gitignore
deleted file mode 100644
index ad9264f0..00000000
--- a/backend/supabase/.gitignore
+++ /dev/null
@@ -1,8 +0,0 @@
-# Supabase
-.branches
-.temp
-
-# dotenvx
-.env.keys
-.env.local
-.env.*.local
diff --git a/backend/supabase/config.toml b/backend/supabase/config.toml
deleted file mode 100644
index a8abc5da..00000000
--- a/backend/supabase/config.toml
+++ /dev/null
@@ -1,308 +0,0 @@
-# For detailed configuration reference documentation, visit:
-# https://supabase.com/docs/guides/local-development/cli/config
-# A string used to distinguish different Supabase projects on the same host. Defaults to the
-# working directory name when running `supabase init`.
-project_id = "backend"
-
-[api]
-enabled = true
-# Port to use for the API URL.
-port = 54321
-# Schemas to expose in your API. Tables, views and stored procedures in this schema will get API
-# endpoints. `public` and `graphql_public` schemas are included by default.
-schemas = ["public", "graphql_public"]
-# Extra schemas to add to the search_path of every request.
-extra_search_path = ["public", "extensions"]
-# The maximum number of rows returns from a view, table, or stored procedure. Limits payload size
-# for accidental or malicious requests.
-max_rows = 1000
-
-[api.tls]
-# Enable HTTPS endpoints locally using a self-signed certificate.
-enabled = false
-
-[db]
-# Port to use for the local database URL.
-port = 54322
-# Port used by db diff command to initialize the shadow database.
-shadow_port = 54320
-# The database major version to use. This has to be the same as your remote database's. Run `SHOW
-# server_version;` on the remote database to check.
-major_version = 15
-
-[db.pooler]
-enabled = false
-# Port to use for the local connection pooler.
-port = 54329
-# Specifies when a server connection can be reused by other clients.
-# Configure one of the supported pooler modes: `transaction`, `session`.
-pool_mode = "transaction"
-# How many server connections to allow per user/database pair.
-default_pool_size = 20
-# Maximum number of client connections allowed.
-max_client_conn = 100
-
-# [db.vault]
-# secret_key = "env(SECRET_VALUE)"
-
-[db.migrations]
-# Specifies an ordered list of schema files that describe your database.
-# Supports glob patterns relative to supabase directory: "./schemas/*.sql"
-schema_paths = []
-
-[db.seed]
-# If enabled, seeds the database after migrations during a db reset.
-enabled = true
-# Specifies an ordered list of seed files to load during db reset.
-# Supports glob patterns relative to supabase directory: "./seeds/*.sql"
-sql_paths = ["./seed.sql"]
-
-[realtime]
-enabled = true
-# Bind realtime via either IPv4 or IPv6. (default: IPv4)
-# ip_version = "IPv6"
-# The maximum length in bytes of HTTP request headers. (default: 4096)
-# max_header_length = 4096
-
-[studio]
-enabled = true
-# Port to use for Supabase Studio.
-port = 54323
-# External URL of the API server that frontend connects to.
-api_url = "http://127.0.0.1"
-# OpenAI API Key to use for Supabase AI in the Supabase Studio.
-openai_api_key = "env(OPENAI_API_KEY)"
-
-# Email testing server. Emails sent with the local dev setup are not actually sent - rather, they
-# are monitored, and you can view the emails that would have been sent from the web interface.
-[inbucket]
-enabled = true
-# Port to use for the email testing server web interface.
-port = 54324
-# Uncomment to expose additional ports for testing user applications that send emails.
-# smtp_port = 54325
-# pop3_port = 54326
-# admin_email = "[email protected]"
-# sender_name = "Admin"
-
-[storage]
-enabled = true
-# The maximum file size allowed (e.g. "5MB", "500KB").
-file_size_limit = "50MiB"
-
-# Image transformation API is available to Supabase Pro plan.
-# [storage.image_transformation]
-# enabled = true
-
-# Uncomment to configure local storage buckets
-# [storage.buckets.images]
-# public = false
-# file_size_limit = "50MiB"
-# allowed_mime_types = ["image/png", "image/jpeg"]
-# objects_path = "./images"
-
-[auth]
-enabled = true
-# The base URL of your website. Used as an allow-list for redirects and for constructing URLs used
-# in emails.
-site_url = "http://127.0.0.1:3000"
-# A list of *exact* URLs that auth providers are permitted to redirect to post authentication.
-additional_redirect_urls = ["https://127.0.0.1:3000"]
-# How long tokens are valid for, in seconds. Defaults to 3600 (1 hour), maximum 604,800 (1 week).
-jwt_expiry = 3600
-# If disabled, the refresh token will never expire.
-enable_refresh_token_rotation = true
-# Allows refresh tokens to be reused after expiry, up to the specified interval in seconds.
-# Requires enable_refresh_token_rotation = true.
-refresh_token_reuse_interval = 10
-# Allow/disallow new user signups to your project.
-enable_signup = true
-# Allow/disallow anonymous sign-ins to your project.
-enable_anonymous_sign_ins = false
-# Allow/disallow testing manual linking of accounts
-enable_manual_linking = false
-# Passwords shorter than this value will be rejected as weak. Minimum 6, recommended 8 or more.
-minimum_password_length = 6
-# Passwords that do not meet the following requirements will be rejected as weak. Supported values
-# are: `letters_digits`, `lower_upper_letters_digits`, `lower_upper_letters_digits_symbols`
-password_requirements = ""
-
-[auth.rate_limit]
-# Number of emails that can be sent per hour. Requires auth.email.smtp to be enabled.
-email_sent = 2
-# Number of SMS messages that can be sent per hour. Requires auth.sms to be enabled.
-sms_sent = 30
-# Number of anonymous sign-ins that can be made per hour per IP address. Requires enable_anonymous_sign_ins = true.
-anonymous_users = 30
-# Number of sessions that can be refreshed in a 5 minute interval per IP address.
-token_refresh = 150
-# Number of sign up and sign-in requests that can be made in a 5 minute interval per IP address (excludes anonymous users).
-sign_in_sign_ups = 30
-# Number of OTP / Magic link verifications that can be made in a 5 minute interval per IP address.
-token_verifications = 30
-
-# Configure one of the supported captcha providers: `hcaptcha`, `turnstile`.
-# [auth.captcha]
-# enabled = true
-# provider = "hcaptcha"
-# secret = ""
-
-[auth.email]
-# Allow/disallow new user signups via email to your project.
-enable_signup = true
-# If enabled, a user will be required to confirm any email change on both the old, and new email
-# addresses. If disabled, only the new email is required to confirm.
-double_confirm_changes = true
-# If enabled, users need to confirm their email address before signing in.
-enable_confirmations = false
-# If enabled, users will need to reauthenticate or have logged in recently to change their password.
-secure_password_change = false
-# Controls the minimum amount of time that must pass before sending another signup confirmation or password reset email.
-max_frequency = "1s"
-# Number of characters used in the email OTP.
-otp_length = 6
-# Number of seconds before the email OTP expires (defaults to 1 hour).
-otp_expiry = 3600
-
-# Use a production-ready SMTP server
-# [auth.email.smtp]
-# enabled = true
-# host = "smtp.sendgrid.net"
-# port = 587
-# user = "apikey"
-# pass = "env(SENDGRID_API_KEY)"
-# admin_email = "[email protected]"
-# sender_name = "Admin"
-
-# Uncomment to customize email template
-# [auth.email.template.invite]
-# subject = "You have been invited"
-# content_path = "./supabase/templates/invite.html"
-
-[auth.sms]
-# Allow/disallow new user signups via SMS to your project.
-enable_signup = false
-# If enabled, users need to confirm their phone number before signing in.
-enable_confirmations = false
-# Template for sending OTP to users
-template = "Your code is {{ .Code }}"
-# Controls the minimum amount of time that must pass before sending another sms otp.
-max_frequency = "5s"
-
-# Use pre-defined map of phone number to OTP for testing.
-# [auth.sms.test_otp]
-# 4152127777 = "123456"
-
-# Configure logged in session timeouts.
-# [auth.sessions]
-# Force log out after the specified duration.
-# timebox = "24h"
-# Force log out if the user has been inactive longer than the specified duration.
-# inactivity_timeout = "8h"
-
-# This hook runs before a token is issued and allows you to add additional claims based on the authentication method used.
-# [auth.hook.custom_access_token]
-# enabled = true
-# uri = "pg-functions://<database>/<schema>/<hook_name>"
-
-# Configure one of the supported SMS providers: `twilio`, `twilio_verify`, `messagebird`, `textlocal`, `vonage`.
-[auth.sms.twilio]
-enabled = false
-account_sid = ""
-message_service_sid = ""
-# DO NOT commit your Twilio auth token to git. Use environment variable substitution instead:
-auth_token = "env(SUPABASE_AUTH_SMS_TWILIO_AUTH_TOKEN)"
-
-# Multi-factor-authentication is available to Supabase Pro plan.
-[auth.mfa]
-# Control how many MFA factors can be enrolled at once per user.
-max_enrolled_factors = 10
-
-# Control MFA via App Authenticator (TOTP)
-[auth.mfa.totp]
-enroll_enabled = false
-verify_enabled = false
-
-# Configure MFA via Phone Messaging
-[auth.mfa.phone]
-enroll_enabled = false
-verify_enabled = false
-otp_length = 6
-template = "Your code is {{ .Code }}"
-max_frequency = "5s"
-
-# Configure MFA via WebAuthn
-# [auth.mfa.web_authn]
-# enroll_enabled = true
-# verify_enabled = true
-
-# Use an external OAuth provider. The full list of providers are: `apple`, `azure`, `bitbucket`,
-# `discord`, `facebook`, `github`, `gitlab`, `google`, `keycloak`, `linkedin_oidc`, `notion`, `twitch`,
-# `twitter`, `slack`, `spotify`, `workos`, `zoom`.
-[auth.external.apple]
-enabled = false
-client_id = ""
-# DO NOT commit your OAuth provider secret to git. Use environment variable substitution instead:
-secret = "env(SUPABASE_AUTH_EXTERNAL_APPLE_SECRET)"
-# Overrides the default auth redirectUrl.
-redirect_uri = ""
-# Overrides the default auth provider URL. Used to support self-hosted gitlab, single-tenant Azure,
-# or any other third-party OIDC providers.
-url = ""
-# If enabled, the nonce check will be skipped. Required for local sign in with Google auth.
-skip_nonce_check = false
-
-# Use Firebase Auth as a third-party provider alongside Supabase Auth.
-[auth.third_party.firebase]
-enabled = false
-# project_id = "my-firebase-project"
-
-# Use Auth0 as a third-party provider alongside Supabase Auth.
-[auth.third_party.auth0]
-enabled = false
-# tenant = "my-auth0-tenant"
-# tenant_region = "us"
-
-# Use AWS Cognito (Amplify) as a third-party provider alongside Supabase Auth.
-[auth.third_party.aws_cognito]
-enabled = false
-# user_pool_id = "my-user-pool-id"
-# user_pool_region = "us-east-1"
-
-# Use Clerk as a third-party provider alongside Supabase Auth.
-[auth.third_party.clerk]
-enabled = false
-# Obtain from https://clerk.com/setup/supabase
-# domain = "example.clerk.accounts.dev"
-
-[edge_runtime]
-enabled = true
-# Configure one of the supported request policies: `oneshot`, `per_worker`.
-# Use `oneshot` for hot reload, or `per_worker` for load testing.
-policy = "oneshot"
-# Port to attach the Chrome inspector for debugging edge functions.
-inspector_port = 8083
-# The Deno major version to use.
-deno_version = 1
-
-# [edge_runtime.secrets]
-# secret_key = "env(SECRET_VALUE)"
-
-[analytics]
-enabled = true
-port = 54327
-# Configure one of the supported backends: `postgres`, `bigquery`.
-backend = "postgres"
-
-# Experimental features may be deprecated any time
-[experimental]
-# Configures Postgres storage engine to use OrioleDB (S3)
-orioledb_version = ""
-# Configures S3 bucket URL, eg. <bucket_name>.s3-<region>.amazonaws.com
-s3_host = "env(S3_HOST)"
-# Configures S3 bucket region, eg. us-east-1
-s3_region = "env(S3_REGION)"
-# Configures AWS_ACCESS_KEY_ID for S3 bucket
-s3_access_key = "env(S3_ACCESS_KEY)"
-# Configures AWS_SECRET_ACCESS_KEY for S3 bucket
-s3_secret_key = "env(S3_SECRET_KEY)"
diff --git a/backend/supabase/migrations/20250412163409_remote_schema.sql b/backend/supabase/migrations/20250412163409_remote_schema.sql
deleted file mode 100644
index 86e48ad7..00000000
--- a/backend/supabase/migrations/20250412163409_remote_schema.sql
+++ /dev/null
@@ -1,2533 +0,0 @@
-
-
-SET statement_timeout = 0;
-SET lock_timeout = 0;
-SET idle_in_transaction_session_timeout = 0;
-SET client_encoding = 'UTF8';
-SET standard_conforming_strings = on;
-SELECT pg_catalog.set_config('search_path', '', false);
-SET check_function_bodies = false;
-SET xmloption = content;
-SET client_min_messages = warning;
-SET row_security = off;
-
-
-CREATE EXTENSION IF NOT EXISTS "pgsodium";
-
-
-
-
-
-
-COMMENT ON SCHEMA "public" IS 'standard public schema';
-
-
-
-CREATE EXTENSION IF NOT EXISTS "pg_graphql" WITH SCHEMA "graphql";
-
-
-
-
-
-
-CREATE EXTENSION IF NOT EXISTS "pg_stat_statements" WITH SCHEMA "extensions";
-
-
-
-
-
-
-CREATE EXTENSION IF NOT EXISTS "pgcrypto" WITH SCHEMA "extensions";
-
-
-
-
-
-
-CREATE EXTENSION IF NOT EXISTS "pgjwt" WITH SCHEMA "extensions";
-
-
-
-
-
-
-CREATE EXTENSION IF NOT EXISTS "pgmq" WITH SCHEMA "pgmq";
-
-
-
-
-
-
-CREATE EXTENSION IF NOT EXISTS "supabase_vault" WITH SCHEMA "vault";
-
-
-
-
-
-
-CREATE EXTENSION IF NOT EXISTS "uuid-ossp" WITH SCHEMA "extensions";
-
-
-
-
-
-
-CREATE TYPE "public"."investigation_status" AS ENUM (
- 'active',
- 'pending',
- 'archived'
-);
-
-
-ALTER TYPE "public"."investigation_status" OWNER TO "postgres";
-
-
-COMMENT ON TYPE "public"."investigation_status" IS 'Describes the possible statuses of an investigation.';
-
-
-
-CREATE OR REPLACE FUNCTION "public"."handle_new_investigation"() RETURNS "trigger"
- LANGUAGE "plpgsql"
- AS $$BEGIN
- INSERT INTO investigations_profiles (investigation_id, profile_id, role)
- VALUES (NEW.id, auth.uid(), 'owner');
- RETURN NEW;
-END;$$;
-
-
-ALTER FUNCTION "public"."handle_new_investigation"() OWNER TO "postgres";
-
-
-CREATE OR REPLACE FUNCTION "public"."handle_new_project"() RETURNS "trigger"
- LANGUAGE "plpgsql"
- AS $$begin
- insert into projects_profiles (project_id, profile_id)
- values (new.id, auth.uid());
- return new;
-end;$$;
-
-
-ALTER FUNCTION "public"."handle_new_project"() OWNER TO "postgres";
-
-
-CREATE OR REPLACE FUNCTION "public"."handle_new_sketch"() RETURNS "trigger"
- LANGUAGE "plpgsql"
- AS $$BEGIN
- INSERT INTO sketches_profiles (sketch_id, profile_id, role)
- VALUES (NEW.id, auth.uid(), 'owner');
- RETURN NEW;
-END;$$;
-
-
-ALTER FUNCTION "public"."handle_new_sketch"() OWNER TO "postgres";
-
-
-CREATE OR REPLACE FUNCTION "public"."handle_new_user"() RETURNS "trigger"
- LANGUAGE "plpgsql" SECURITY DEFINER
- SET "search_path" TO ''
- AS $$
-begin
- insert into public.profiles (id, first_name, last_name)
- values (new.id, new.raw_user_meta_data ->> 'first_name', new.raw_user_meta_data ->> 'last_name');
- return new;
-end;
-$$;
-
-
-ALTER FUNCTION "public"."handle_new_user"() OWNER TO "postgres";
-
-
-CREATE OR REPLACE FUNCTION "public"."sync_investigation_profile_from_sketch"() RETURNS "trigger"
- LANGUAGE "plpgsql"
- AS $$
-DECLARE
- inv_id UUID;
-BEGIN
- -- Récupère l'investigation_id associé au sketch_id
- SELECT investigation_id INTO inv_id
- FROM sketches
- WHERE id = NEW.sketch_id;
-
- -- Vérifie que ce couple n'existe pas déjà (optionnel selon tes contraintes)
- IF NOT EXISTS (
- SELECT 1 FROM investigations_profiles
- WHERE profile_id = NEW.profile_id AND investigation_id = inv_id
- ) THEN
- -- Insère le lien dans investigations_profiles
- INSERT INTO investigations_profiles(profile_id, investigation_id)
- VALUES (NEW.profile_id, inv_id);
- END IF;
-
- RETURN NEW;
-END;
-$$;
-
-
-ALTER FUNCTION "public"."sync_investigation_profile_from_sketch"() OWNER TO "postgres";
-
-
-CREATE OR REPLACE FUNCTION "public"."update_investigation_last_updated"() RETURNS "trigger"
- LANGUAGE "plpgsql"
- AS $$BEGIN
- -- Si la mise à jour concerne 'investigations', mettre à jour 'projects' uniquement si 10s sont écoulées
- IF TG_TABLE_NAME = 'sketches' THEN
- IF OLD.last_updated_at IS NULL OR OLD.last_updated_at < NOW() - INTERVAL '10 seconds' THEN
- UPDATE investigations
- SET last_updated_at = NOW()
- WHERE id = NEW.investigation_id;
- UPDATE sketches
- SET last_updated_at = NOW()
- WHERE id = NEW.id;
- END IF;
-
- -- Si la mise à jour concerne une table liée, mettre à jour 'investigations' et 'projects' seulement si 10s sont écoulées
- ELSIF TG_TABLE_NAME IN ('emails', 'individuals', 'relationships', 'physical_addresses', 'social_accounts', 'ip_addresses', 'phones') THEN
- IF (SELECT last_updated_at FROM sketches WHERE id = NEW.sketch_id) < NOW() - INTERVAL '10 seconds' THEN
- UPDATE sketches
- SET last_updated_at = NOW()
- WHERE id = NEW.sketch_id;
-
- UPDATE investigations
- SET last_updated_at = NOW()
- WHERE id = (
- SELECT investigation_id FROM sketches WHERE id = NEW.sketch_id
- );
- END IF;
- END IF;
-
- RETURN NEW;
-END;$$;
-
-
-ALTER FUNCTION "public"."update_investigation_last_updated"() OWNER TO "postgres";
-
-
-CREATE OR REPLACE FUNCTION "public"."update_last_updated_at"() RETURNS "trigger"
- LANGUAGE "plpgsql"
- AS $$
-BEGIN
- IF TG_TABLE_NAME = 'sketches' THEN
- IF OLD.last_updated_at IS NULL OR OLD.last_updated_at < NOW() - INTERVAL '10 seconds' THEN
- UPDATE investigations
- SET last_updated_at = NOW()
- WHERE id = NEW.investigation_id;
-
- UPDATE sketches
- SET last_updated_at = NOW()
- WHERE id = NEW.id;
- END IF;
-
- ELSIF TG_TABLE_NAME IN (
- 'emails', 'individuals', 'relationships',
- 'physical_addresses', 'social_accounts',
- 'ip_addresses', 'phones'
- ) THEN
- IF (SELECT last_updated_at FROM sketches WHERE id = NEW.sketch_id) IS NULL OR
- (SELECT last_updated_at FROM sketches WHERE id = NEW.sketch_id) < NOW() - INTERVAL '10 seconds' THEN
- UPDATE sketches
- SET last_updated_at = NOW()
- WHERE id = NEW.sketch_id;
-
- UPDATE investigations
- SET last_updated_at = NOW()
- WHERE id = (
- SELECT investigation_id FROM sketches WHERE id = NEW.sketch_id
- );
- END IF;
- END IF;
-
- RETURN NEW;
-END;
-$$;
-
-
-ALTER FUNCTION "public"."update_last_updated_at"() OWNER TO "postgres";
-
-
-CREATE OR REPLACE FUNCTION "public"."update_sketch_last_updated"() RETURNS "trigger"
- LANGUAGE "plpgsql"
- AS $$BEGIN
- IF (SELECT last_updated_at FROM sketches WHERE id = NEW.id) IS NULL OR
- (SELECT last_updated_at FROM sketches WHERE id = NEW.id) < NOW() - INTERVAL '10 seconds' THEN
- UPDATE investigations
- SET last_updated_at = NOW()
- WHERE id = NEW.investigation_id;
- END IF;
-
- RETURN NEW;
-END;$$;
-
-
-ALTER FUNCTION "public"."update_sketch_last_updated"() OWNER TO "postgres";
-
-SET default_tablespace = '';
-
-SET default_table_access_method = "heap";
-
-
-CREATE TABLE IF NOT EXISTS "public"."accounts_breaches" (
- "id" bigint NOT NULL,
- "created_at" timestamp with time zone DEFAULT "now"() NOT NULL,
- "account" "text",
- "breach_id" bigint
-);
-
-
-ALTER TABLE "public"."accounts_breaches" OWNER TO "postgres";
-
-
-ALTER TABLE "public"."accounts_breaches" ALTER COLUMN "id" ADD GENERATED BY DEFAULT AS IDENTITY (
- SEQUENCE NAME "public"."accounts_breaches_id_seq"
- START WITH 1
- INCREMENT BY 1
- NO MINVALUE
- NO MAXVALUE
- CACHE 1
-);
-
-
-
-CREATE TABLE IF NOT EXISTS "public"."breaches" (
- "id" bigint NOT NULL,
- "created_at" timestamp with time zone DEFAULT "now"() NOT NULL,
- "name" "text" NOT NULL,
- "description" "text",
- "raw_content" "jsonb"
-);
-
-
-ALTER TABLE "public"."breaches" OWNER TO "postgres";
-
-
-ALTER TABLE "public"."breaches" ALTER COLUMN "id" ADD GENERATED BY DEFAULT AS IDENTITY (
- SEQUENCE NAME "public"."breaches_id_seq"
- START WITH 1
- INCREMENT BY 1
- NO MINVALUE
- NO MAXVALUE
- CACHE 1
-);
-
-
-
-CREATE TABLE IF NOT EXISTS "public"."emails" (
- "id" "uuid" DEFAULT "extensions"."uuid_generate_v4"() NOT NULL,
- "individual_id" "uuid",
- "sketch_id" "uuid",
- "email" "text",
- "breach_found" boolean DEFAULT false,
- "organization_id" "uuid",
- "created_at" timestamp with time zone DEFAULT ("now"() AT TIME ZONE 'utc'::"text")
-);
-
-
-ALTER TABLE "public"."emails" OWNER TO "postgres";
-
-
-CREATE TABLE IF NOT EXISTS "public"."feedbacks" (
- "id" bigint NOT NULL,
- "created_at" timestamp with time zone DEFAULT "now"() NOT NULL,
- "content" "text",
- "owner_id" "uuid" DEFAULT "auth"."uid"()
-);
-
-
-ALTER TABLE "public"."feedbacks" OWNER TO "postgres";
-
-
-ALTER TABLE "public"."feedbacks" ALTER COLUMN "id" ADD GENERATED BY DEFAULT AS IDENTITY (
- SEQUENCE NAME "public"."feedbacks_id_seq"
- START WITH 1
- INCREMENT BY 1
- NO MINVALUE
- NO MAXVALUE
- CACHE 1
-);
-
-
-
-CREATE TABLE IF NOT EXISTS "public"."groups" (
- "id" "uuid" DEFAULT "gen_random_uuid"() NOT NULL,
- "created_at" timestamp with time zone DEFAULT "now"() NOT NULL,
- "label" "text",
- "sketch_id" "uuid"
-);
-
-
-ALTER TABLE "public"."groups" OWNER TO "postgres";
-
-
-CREATE TABLE IF NOT EXISTS "public"."individuals" (
- "id" "uuid" DEFAULT "extensions"."uuid_generate_v4"() NOT NULL,
- "sketch_id" "uuid",
- "full_name" "text",
- "birth_date" "date",
- "gender" "text",
- "nationality" "text",
- "notes" "jsonb",
- "image_url" "text",
- "group_id" "uuid",
- "created_at" timestamp with time zone DEFAULT ("now"() AT TIME ZONE 'utc'::"text")
-);
-
-
-ALTER TABLE "public"."individuals" OWNER TO "postgres";
-
-
-CREATE TABLE IF NOT EXISTS "public"."individuals_individuals" (
- "id" "uuid" DEFAULT "extensions"."uuid_generate_v4"() NOT NULL,
- "individual_a" "uuid",
- "individual_b" "uuid",
- "sketch_id" "uuid",
- "relation_type" "text",
- "confidence_level" integer,
- CONSTRAINT "relationships_confidence_level_check" CHECK ((("confidence_level" >= 1) AND ("confidence_level" <= 100)))
-);
-
-
-ALTER TABLE "public"."individuals_individuals" OWNER TO "postgres";
-
-
-CREATE TABLE IF NOT EXISTS "public"."investigations" (
- "id" "uuid" DEFAULT "gen_random_uuid"() NOT NULL,
- "created_at" timestamp with time zone DEFAULT "now"() NOT NULL,
- "name" "text",
- "description" "text",
- "owner_id" "uuid" DEFAULT "auth"."uid"(),
- "last_updated_at" timestamp with time zone DEFAULT ("now"() AT TIME ZONE 'utc'::"text")
-);
-
-
-ALTER TABLE "public"."investigations" OWNER TO "postgres";
-
-
-CREATE TABLE IF NOT EXISTS "public"."investigations_profiles" (
- "id" bigint NOT NULL,
- "created_at" timestamp with time zone DEFAULT "now"() NOT NULL,
- "investigation_id" "uuid" NOT NULL,
- "profile_id" "uuid" NOT NULL,
- "role" "text" DEFAULT 'member'::"text" NOT NULL
-);
-
-
-ALTER TABLE "public"."investigations_profiles" OWNER TO "postgres";
-
-
-CREATE TABLE IF NOT EXISTS "public"."sketches_profiles" (
- "id" bigint NOT NULL,
- "created_at" timestamp with time zone DEFAULT "now"() NOT NULL,
- "profile_id" "uuid",
- "sketch_id" "uuid",
- "role" "text" DEFAULT 'editor'::"text"
-);
-
-
-ALTER TABLE "public"."sketches_profiles" OWNER TO "postgres";
-
-
-ALTER TABLE "public"."sketches_profiles" ALTER COLUMN "id" ADD GENERATED BY DEFAULT AS IDENTITY (
- SEQUENCE NAME "public"."investigations_profiles_id_seq"
- START WITH 1
- INCREMENT BY 1
- NO MINVALUE
- NO MAXVALUE
- CACHE 1
-);
-
-
-
-CREATE TABLE IF NOT EXISTS "public"."ip_addresses" (
- "id" "uuid" DEFAULT "extensions"."uuid_generate_v4"() NOT NULL,
- "individual_id" "uuid",
- "sketch_id" "uuid",
- "ip_address" "text",
- "geolocation" "jsonb",
- "last_seen" timestamp without time zone DEFAULT "now"(),
- "organization_id" "uuid",
- "created_at" timestamp with time zone DEFAULT ("now"() AT TIME ZONE 'utc'::"text")
-);
-
-
-ALTER TABLE "public"."ip_addresses" OWNER TO "postgres";
-
-
-CREATE TABLE IF NOT EXISTS "public"."organizations" (
- "id" "uuid" DEFAULT "gen_random_uuid"() NOT NULL,
- "created_at" timestamp with time zone DEFAULT "now"() NOT NULL,
- "registration_number" "text",
- "founding_date" "text",
- "sketch_id" "uuid",
- "name" "text"
-);
-
-
-ALTER TABLE "public"."organizations" OWNER TO "postgres";
-
-
-CREATE TABLE IF NOT EXISTS "public"."organizations_individuals" (
- "created_at" timestamp with time zone DEFAULT ("now"() AT TIME ZONE 'utc'::"text"),
- "id" "uuid" DEFAULT "gen_random_uuid"() NOT NULL,
- "individual_id" "uuid",
- "organization_id" "uuid",
- "sketch_id" "uuid",
- "relation_type" "text"
-);
-
-
-ALTER TABLE "public"."organizations_individuals" OWNER TO "postgres";
-
-
-CREATE TABLE IF NOT EXISTS "public"."organizations_organizations" (
- "id" bigint NOT NULL,
- "created_at" timestamp with time zone DEFAULT "now"() NOT NULL,
- "organization_a" "uuid",
- "organization_b" "uuid",
- "relation_type" "text" DEFAULT 'subsidiary'::"text",
- "sketch_id" "uuid"
-);
-
-
-ALTER TABLE "public"."organizations_organizations" OWNER TO "postgres";
-
-
-CREATE OR REPLACE VIEW "public"."organization_graph" WITH ("security_invoker"='on') AS
- WITH "related_organizations" AS (
- SELECT "o_1"."id" AS "organization_id",
- "o_1"."name"
- FROM "public"."organizations" "o_1"
- UNION
- SELECT "oo"."organization_b" AS "organization_id",
- "o_1"."name"
- FROM ("public"."organizations_organizations" "oo"
- JOIN "public"."organizations" "o_1" ON (("oo"."organization_b" = "o_1"."id")))
- ), "related_individuals" AS (
- SELECT "i"."id" AS "individual_id",
- "i"."full_name",
- "oi"."organization_id"
- FROM (("public"."organizations_individuals" "oi"
- JOIN "public"."individuals" "i" ON (("oi"."individual_id" = "i"."id")))
- JOIN "related_organizations" "ro" ON (("oi"."organization_id" = "ro"."organization_id")))
- ), "organization_nodes" AS (
- SELECT "ro"."organization_id",
- "jsonb_build_object"('id', ("ro"."organization_id")::"text", 'type', 'custom', 'data', "jsonb_build_object"('id', "ro"."organization_id", 'name', "ro"."name", 'label', "ro"."name", 'type', 'organization'), 'position', "jsonb_build_object"('x', 200, 'y', 0)) AS "node"
- FROM "related_organizations" "ro"
- ), "individual_nodes" AS (
- SELECT "ri"."organization_id",
- "jsonb_build_object"('id', ("ri"."individual_id")::"text", 'type', 'custom', 'data', "jsonb_build_object"('id', "ri"."individual_id", 'full_name', "ri"."full_name", 'label', "ri"."full_name", 'type', 'individual'), 'position', "jsonb_build_object"('x', 0, 'y', 100)) AS "node"
- FROM "related_individuals" "ri"
- ), "organization_edges" AS (
- SELECT "oo"."organization_a" AS "organization_id",
- "jsonb_build_object"('id', "concat"('org-org-', "oo"."id"), 'source', ("oo"."organization_a")::"text", 'target', ("oo"."organization_b")::"text", 'type', 'custom', 'label', COALESCE("oo"."relation_type", 'related'::"text"), 'data', "jsonb_build_object"('relation_type', "oo"."relation_type")) AS "edge"
- FROM "public"."organizations_organizations" "oo"
- WHERE (("oo"."organization_a" IS NOT NULL) AND ("oo"."organization_b" IS NOT NULL) AND (EXISTS ( SELECT 1
- FROM "related_organizations" "ro"
- WHERE ("ro"."organization_id" = "oo"."organization_a"))))
- ), "org_individual_edges" AS (
- SELECT "oi"."organization_id",
- "jsonb_build_object"('id', "concat"('org-ind-', "oi"."id"), 'source', ("oi"."organization_id")::"text", 'target', ("oi"."individual_id")::"text", 'type', 'custom', 'label', COALESCE("oi"."relation_type", 'employee'::"text"), 'data', "jsonb_build_object"('relation_type', "oi"."relation_type")) AS "edge"
- FROM "public"."organizations_individuals" "oi"
- WHERE (EXISTS ( SELECT 1
- FROM "related_organizations" "ro"
- WHERE ("ro"."organization_id" = "oi"."organization_id")))
- ), "individual_edges" AS (
- SELECT "ri"."organization_id",
- "jsonb_build_object"('id', "concat"('ind-ind-', "r"."id"), 'source', ("r"."individual_a")::"text", 'target', ("r"."individual_b")::"text", 'type', 'custom', 'label', COALESCE("r"."relation_type", 'related'::"text"), 'data', "jsonb_build_object"('confidence_level', "r"."confidence_level", 'relation_type', "r"."relation_type")) AS "edge"
- FROM ("public"."individuals_individuals" "r"
- JOIN "related_individuals" "ri" ON (("r"."individual_a" = "ri"."individual_id")))
- WHERE (("r"."individual_a" IS NOT NULL) AND ("r"."individual_b" IS NOT NULL) AND (EXISTS ( SELECT 1
- FROM "related_individuals" "ri2"
- WHERE ("ri2"."individual_id" = "r"."individual_b"))))
- ), "nodes_by_organization" AS (
- SELECT "all_nodes"."organization_id",
- "json_agg"(DISTINCT "all_nodes"."node") AS "nodes"
- FROM ( SELECT "organization_nodes"."organization_id",
- "organization_nodes"."node"
- FROM "organization_nodes"
- UNION ALL
- SELECT "individual_nodes"."organization_id",
- "individual_nodes"."node"
- FROM "individual_nodes") "all_nodes"
- GROUP BY "all_nodes"."organization_id"
- ), "edges_by_organization" AS (
- SELECT "all_edges"."organization_id",
- "json_agg"(DISTINCT "all_edges"."edge") AS "edges"
- FROM ( SELECT "organization_edges"."organization_id",
- "organization_edges"."edge"
- FROM "organization_edges"
- UNION ALL
- SELECT "org_individual_edges"."organization_id",
- "org_individual_edges"."edge"
- FROM "org_individual_edges"
- UNION ALL
- SELECT "individual_edges"."organization_id",
- "individual_edges"."edge"
- FROM "individual_edges") "all_edges"
- GROUP BY "all_edges"."organization_id"
- )
- SELECT "o"."id" AS "organization_id",
- "o"."name" AS "organization_name",
- COALESCE("n"."nodes", '[]'::"json") AS "nodes",
- COALESCE("e"."edges", '[]'::"json") AS "edges"
- FROM (("public"."organizations" "o"
- LEFT JOIN "nodes_by_organization" "n" ON (("n"."organization_id" = "o"."id")))
- LEFT JOIN "edges_by_organization" "e" ON (("e"."organization_id" = "o"."id")));
-
-
-ALTER TABLE "public"."organization_graph" OWNER TO "postgres";
-
-
-ALTER TABLE "public"."organizations_organizations" ALTER COLUMN "id" ADD GENERATED BY DEFAULT AS IDENTITY (
- SEQUENCE NAME "public"."organizations_organizations_id_seq"
- START WITH 1
- INCREMENT BY 1
- NO MINVALUE
- NO MAXVALUE
- CACHE 1
-);
-
-
-
-CREATE TABLE IF NOT EXISTS "public"."phones" (
- "id" "uuid" DEFAULT "extensions"."uuid_generate_v4"() NOT NULL,
- "individual_id" "uuid",
- "sketch_id" "uuid",
- "phone_number" "text",
- "country" "text",
- "organization_id" "uuid",
- "created_at" timestamp with time zone DEFAULT ("now"() AT TIME ZONE 'utc'::"text")
-);
-
-
-ALTER TABLE "public"."phones" OWNER TO "postgres";
-
-
-CREATE TABLE IF NOT EXISTS "public"."physical_addresses" (
- "id" "uuid" DEFAULT "gen_random_uuid"() NOT NULL,
- "created_at" timestamp with time zone DEFAULT "now"() NOT NULL,
- "address" "text",
- "city" "text",
- "country" "text",
- "zip" "text",
- "sketch_id" "uuid",
- "individual_id" "uuid",
- "organization_id" "uuid"
-);
-
-
-ALTER TABLE "public"."physical_addresses" OWNER TO "postgres";
-
-
-CREATE TABLE IF NOT EXISTS "public"."profiles" (
- "id" "uuid" NOT NULL,
- "first_name" "text",
- "last_name" "text",
- "avatar_url" "text"
-);
-
-
-ALTER TABLE "public"."profiles" OWNER TO "postgres";
-
-
-ALTER TABLE "public"."investigations_profiles" ALTER COLUMN "id" ADD GENERATED BY DEFAULT AS IDENTITY (
- SEQUENCE NAME "public"."projects_profiles_id_seq"
- START WITH 1
- INCREMENT BY 1
- NO MINVALUE
- NO MAXVALUE
- CACHE 1
-);
-
-
-
-CREATE TABLE IF NOT EXISTS "public"."scans" (
- "id" "uuid" DEFAULT "gen_random_uuid"() NOT NULL,
- "created_at" timestamp with time zone DEFAULT "now"() NOT NULL,
- "status" "text",
- "scan_name" "text",
- "results" "jsonb",
- "value" "text",
- "sketch_id" "uuid"
-);
-
-
-ALTER TABLE "public"."scans" OWNER TO "postgres";
-
-
-COMMENT ON COLUMN "public"."scans"."value" IS 'The value that was searched for. Can be a username, an email, an IP address, etc.';
-
-
-
-CREATE OR REPLACE VIEW "public"."sketch_graph" AS
-SELECT
- NULL::"uuid" AS "sketch_id",
- NULL::"json" AS "nodes",
- NULL::"json" AS "edges",
- NULL::bigint AS "debug_relationship_count";
-
-
-ALTER TABLE "public"."sketch_graph" OWNER TO "postgres";
-
-
-CREATE TABLE IF NOT EXISTS "public"."social_accounts" (
- "id" "uuid" DEFAULT "extensions"."uuid_generate_v4"() NOT NULL,
- "individual_id" "uuid",
- "sketch_id" "uuid",
- "platform" "text",
- "username" "text",
- "profile_url" "text",
- "last_seen" timestamp with time zone DEFAULT ("now"() AT TIME ZONE 'utc'::"text"),
- "organization_id" "uuid",
- "created_at" timestamp with time zone DEFAULT ("now"() AT TIME ZONE 'utc'::"text")
-);
-
-
-ALTER TABLE "public"."social_accounts" OWNER TO "postgres";
-
-
-CREATE TABLE IF NOT EXISTS "public"."vehicles" (
- "id" "uuid" DEFAULT "gen_random_uuid"() NOT NULL,
- "created_at" timestamp with time zone DEFAULT "now"() NOT NULL,
- "model" "text",
- "brand" "text",
- "year" "text",
- "plate" "text",
- "type" "text",
- "sketch_id" "uuid",
- "individual_id" "uuid",
- "organization_id" "uuid",
- "color" "text"
-);
-
-
-ALTER TABLE "public"."vehicles" OWNER TO "postgres";
-
-
-CREATE TABLE IF NOT EXISTS "public"."websites" (
- "id" "uuid" DEFAULT "gen_random_uuid"() NOT NULL,
- "created_at" timestamp with time zone DEFAULT "now"() NOT NULL,
- "sketch_id" "uuid",
- "individual_id" "uuid",
- "registration_date" "text",
- "url" "text",
- "registrar" "text",
- "ip_address" "text",
- "organization_id" "uuid"
-);
-
-
-ALTER TABLE "public"."websites" OWNER TO "postgres";
-
-
-CREATE OR REPLACE VIEW "public"."sketch_table" WITH ("security_invoker"='on') AS
- SELECT "all_entities"."sketch_id",
- "jsonb_agg"("jsonb_build_object"('id', "all_entities"."id", 'data', "all_entities"."data")) AS "data"
- FROM ( SELECT "organizations"."id",
- "organizations"."sketch_id",
- "jsonb_build_object"('id', "organizations"."id", 'type', 'organization', 'label', "organizations"."name", 'name', "organizations"."name", 'registration_number', "organizations"."registration_number", 'founding_date', "organizations"."founding_date", 'created_at', "organizations"."created_at") AS "data"
- FROM "public"."organizations"
- UNION ALL
- SELECT "individuals"."id",
- "individuals"."sketch_id",
- "jsonb_build_object"('id', "individuals"."id", 'type', 'individual', 'label', "individuals"."full_name", 'full_name', "individuals"."full_name", 'birth_date', "individuals"."birth_date", 'gender', "individuals"."gender", 'nationality', "individuals"."nationality", 'notes', "individuals"."notes", 'image_url', "individuals"."image_url", 'created_at', "individuals"."created_at") AS "data"
- FROM "public"."individuals"
- UNION ALL
- SELECT "emails"."id",
- "emails"."sketch_id",
- "jsonb_build_object"('id', "emails"."id", 'type', 'email', 'label', "emails"."email", 'email', "emails"."email", 'breach_found', "emails"."breach_found", 'created_at', "emails"."created_at") AS "data"
- FROM "public"."emails"
- UNION ALL
- SELECT "phones"."id",
- "phones"."sketch_id",
- "jsonb_build_object"('id', "phones"."id", 'type', 'phone', 'label', "phones"."phone_number", 'phone_number', "phones"."phone_number", 'country', "phones"."country", 'created_at', "phones"."created_at") AS "data"
- FROM "public"."phones"
- UNION ALL
- SELECT "websites"."id",
- "websites"."sketch_id",
- "jsonb_build_object"('id', "websites"."id", 'type', 'website', 'label', "websites"."url", 'url', "websites"."url", 'registration_date', "websites"."registration_date", 'registrar', "websites"."registrar", 'ip_address', "websites"."ip_address", 'created_at', "websites"."created_at") AS "data"
- FROM "public"."websites"
- UNION ALL
- SELECT "social_accounts"."id",
- "social_accounts"."sketch_id",
- "jsonb_build_object"('id', "social_accounts"."id", 'type', 'social', 'label', "concat"("social_accounts"."username", '(', "social_accounts"."platform", ')'), 'platform', "social_accounts"."platform", 'username', "social_accounts"."username", 'profile_url', "social_accounts"."profile_url", 'last_seen', "social_accounts"."last_seen", 'created_at', "social_accounts"."created_at") AS "data"
- FROM "public"."social_accounts"
- UNION ALL
- SELECT "ip_addresses"."id",
- "ip_addresses"."sketch_id",
- "jsonb_build_object"('id', "ip_addresses"."id", 'type', 'ip', 'label', "ip_addresses"."ip_address", 'ip_address', "ip_addresses"."ip_address", 'geolocation', "ip_addresses"."geolocation", 'last_seen', "ip_addresses"."last_seen", 'created_at', "ip_addresses"."created_at") AS "data"
- FROM "public"."ip_addresses"
- UNION ALL
- SELECT "vehicles"."id",
- "vehicles"."sketch_id",
- "jsonb_build_object"('id', "vehicles"."id", 'type', 'vehicle', 'label', "concat"("vehicles"."brand", '', "vehicles"."model", ': ', "vehicles"."plate"), 'plate', "vehicles"."plate", 'brand', "vehicles"."brand", 'model', "vehicles"."model", 'color', "vehicles"."color", 'created_at', "vehicles"."created_at") AS "data"
- FROM "public"."vehicles"
- UNION ALL
- SELECT "physical_addresses"."id",
- "physical_addresses"."sketch_id",
- "jsonb_build_object"('id', "physical_addresses"."id", 'type', 'address', 'label', "concat"("physical_addresses"."address", ' ', "physical_addresses"."city", ' ', "physical_addresses"."country"), 'address', "physical_addresses"."address", 'city', "physical_addresses"."city", 'country', "physical_addresses"."country", 'zip', "physical_addresses"."zip", 'created_at', "physical_addresses"."created_at") AS "data"
- FROM "public"."physical_addresses") "all_entities"
- GROUP BY "all_entities"."sketch_id";
-
-
-ALTER TABLE "public"."sketch_table" OWNER TO "postgres";
-
-
-CREATE TABLE IF NOT EXISTS "public"."sketches" (
- "id" "uuid" DEFAULT "extensions"."uuid_generate_v4"() NOT NULL,
- "title" "text",
- "description" "text",
- "created_at" timestamp without time zone DEFAULT CURRENT_TIMESTAMP,
- "owner_id" "uuid" DEFAULT "auth"."uid"(),
- "status" "public"."investigation_status" DEFAULT 'active'::"public"."investigation_status",
- "investigation_id" "uuid" NOT NULL,
- "last_updated_at" timestamp with time zone DEFAULT ("now"() AT TIME ZONE 'utc'::"text")
-);
-
-
-ALTER TABLE "public"."sketches" OWNER TO "postgres";
-
-
-ALTER TABLE ONLY "public"."accounts_breaches"
- ADD CONSTRAINT "accounts_breaches_pkey" PRIMARY KEY ("id");
-
-
-
-ALTER TABLE ONLY "public"."breaches"
- ADD CONSTRAINT "breaches_name_key" UNIQUE ("name");
-
-
-
-ALTER TABLE ONLY "public"."breaches"
- ADD CONSTRAINT "breaches_pkey" PRIMARY KEY ("id");
-
-
-
-ALTER TABLE ONLY "public"."emails"
- ADD CONSTRAINT "emails_pkey" PRIMARY KEY ("id");
-
-
-
-ALTER TABLE ONLY "public"."feedbacks"
- ADD CONSTRAINT "feedbacks_pkey" PRIMARY KEY ("id");
-
-
-
-ALTER TABLE ONLY "public"."groups"
- ADD CONSTRAINT "groups_pkey" PRIMARY KEY ("id");
-
-
-
-ALTER TABLE ONLY "public"."individuals"
- ADD CONSTRAINT "individuals_pkey" PRIMARY KEY ("id");
-
-
-
-ALTER TABLE ONLY "public"."sketches"
- ADD CONSTRAINT "investigations_pkey" PRIMARY KEY ("id");
-
-
-
-ALTER TABLE ONLY "public"."sketches_profiles"
- ADD CONSTRAINT "investigations_profiles_pkey" PRIMARY KEY ("id");
-
-
-
-ALTER TABLE ONLY "public"."sketches_profiles"
- ADD CONSTRAINT "investigations_profiles_unique_profile_investigation" UNIQUE ("profile_id", "sketch_id");
-
-
-
-ALTER TABLE ONLY "public"."ip_addresses"
- ADD CONSTRAINT "ip_addresses_pkey" PRIMARY KEY ("id");
-
-
-
-ALTER TABLE ONLY "public"."organizations_individuals"
- ADD CONSTRAINT "organizations_individuals_pkey" PRIMARY KEY ("id");
-
-
-
-ALTER TABLE ONLY "public"."organizations_organizations"
- ADD CONSTRAINT "organizations_organizations_pkey" PRIMARY KEY ("id");
-
-
-
-ALTER TABLE ONLY "public"."organizations"
- ADD CONSTRAINT "organizations_pkey" PRIMARY KEY ("id");
-
-
-
-ALTER TABLE ONLY "public"."phones"
- ADD CONSTRAINT "phones_phone_number_key" UNIQUE ("phone_number");
-
-
-
-ALTER TABLE ONLY "public"."phones"
- ADD CONSTRAINT "phones_pkey" PRIMARY KEY ("id");
-
-
-
-ALTER TABLE ONLY "public"."physical_addresses"
- ADD CONSTRAINT "physical_addresses_pkey" PRIMARY KEY ("id");
-
-
-
-ALTER TABLE ONLY "public"."profiles"
- ADD CONSTRAINT "profiles_pkey" PRIMARY KEY ("id");
-
-
-
-ALTER TABLE ONLY "public"."investigations"
- ADD CONSTRAINT "projects_pkey" PRIMARY KEY ("id");
-
-
-
-ALTER TABLE ONLY "public"."investigations_profiles"
- ADD CONSTRAINT "projects_profiles_pkey" PRIMARY KEY ("id");
-
-
-
-ALTER TABLE ONLY "public"."investigations_profiles"
- ADD CONSTRAINT "projects_profiles_unique_profile_project" UNIQUE ("profile_id", "investigation_id");
-
-
-
-ALTER TABLE ONLY "public"."individuals_individuals"
- ADD CONSTRAINT "relationships_pkey" PRIMARY KEY ("id");
-
-
-
-ALTER TABLE ONLY "public"."scans"
- ADD CONSTRAINT "scans_pkey" PRIMARY KEY ("id");
-
-
-
-ALTER TABLE ONLY "public"."social_accounts"
- ADD CONSTRAINT "social_accounts_pkey" PRIMARY KEY ("id");
-
-
-
-ALTER TABLE ONLY "public"."individuals_individuals"
- ADD CONSTRAINT "unique_relationship" UNIQUE ("individual_a", "individual_b");
-
-
-
-ALTER TABLE ONLY "public"."accounts_breaches"
- ADD CONSTRAINT "unique_relationship_breaches" UNIQUE ("breach_id", "account");
-
-
-
-ALTER TABLE ONLY "public"."individuals_individuals"
- ADD CONSTRAINT "unique_relationship_individuals" UNIQUE ("individual_a", "individual_b");
-
-
-
-ALTER TABLE ONLY "public"."vehicles"
- ADD CONSTRAINT "vehicles_pkey" PRIMARY KEY ("id");
-
-
-
-ALTER TABLE ONLY "public"."websites"
- ADD CONSTRAINT "websites_pkey" PRIMARY KEY ("id");
-
-
-
-CREATE INDEX "idx_emails_sketch_id" ON "public"."emails" USING "btree" ("sketch_id");
-
-
-
-CREATE INDEX "idx_individuals_individuals_sketch_id" ON "public"."individuals_individuals" USING "btree" ("sketch_id");
-
-
-
-CREATE INDEX "idx_individuals_sketch_id" ON "public"."individuals" USING "btree" ("sketch_id");
-
-
-
-CREATE INDEX "idx_investigations_id" ON "public"."investigations" USING "btree" ("id");
-
-
-
-CREATE INDEX "idx_investigations_owner_id" ON "public"."investigations" USING "btree" ("owner_id");
-
-
-
-CREATE INDEX "idx_investigations_profiles_investigation_id" ON "public"."investigations_profiles" USING "btree" ("investigation_id");
-
-
-
-CREATE INDEX "idx_investigations_profiles_profile_id" ON "public"."investigations_profiles" USING "btree" ("profile_id");
-
-
-
-CREATE INDEX "idx_ip_addresses_sketch_id" ON "public"."ip_addresses" USING "btree" ("sketch_id");
-
-
-
-CREATE INDEX "idx_organizations_individuals_sketch_id" ON "public"."organizations_individuals" USING "btree" ("sketch_id");
-
-
-
-CREATE INDEX "idx_organizations_organizations_sketch_id" ON "public"."organizations_organizations" USING "btree" ("sketch_id");
-
-
-
-CREATE INDEX "idx_organizations_sketch_id" ON "public"."organizations" USING "btree" ("sketch_id");
-
-
-
-CREATE INDEX "idx_phones_sketch_id" ON "public"."phones" USING "btree" ("sketch_id");
-
-
-
-CREATE INDEX "idx_scans_sketch_id" ON "public"."scans" USING "btree" ("sketch_id");
-
-
-
-CREATE INDEX "idx_sketches_investigation_id" ON "public"."sketches" USING "btree" ("investigation_id");
-
-
-
-CREATE INDEX "idx_sketches_owner_id" ON "public"."sketches" USING "btree" ("owner_id");
-
-
-
-CREATE INDEX "idx_sketches_profiles_profile_id" ON "public"."sketches_profiles" USING "btree" ("profile_id");
-
-
-
-CREATE INDEX "idx_sketches_profiles_sketch_id" ON "public"."sketches_profiles" USING "btree" ("sketch_id");
-
-
-
-CREATE INDEX "idx_social_accounts_sketch_id" ON "public"."social_accounts" USING "btree" ("sketch_id");
-
-
-
-CREATE INDEX "idx_vehicles_sketch_id" ON "public"."vehicles" USING "btree" ("sketch_id");
-
-
-
-CREATE INDEX "idx_websites_sketch_id" ON "public"."websites" USING "btree" ("sketch_id");
-
-
-
-CREATE OR REPLACE VIEW "public"."sketch_graph" WITH ("security_invoker"='on') AS
- WITH "individual_data" AS (
- SELECT "i"."id",
- "i"."full_name",
- "i"."sketch_id",
- "json_agg"(DISTINCT "jsonb_build_object"('id', "e_1"."id", 'email', "e_1"."email")) FILTER (WHERE ("e_1"."id" IS NOT NULL)) AS "emails",
- "json_agg"(DISTINCT "jsonb_build_object"('id', "p"."id", 'phone_number', "p"."phone_number")) FILTER (WHERE ("p"."id" IS NOT NULL)) AS "phones",
- "json_agg"(DISTINCT "jsonb_build_object"('id', "s"."id", 'platform', "s"."platform", 'username', "s"."username")) FILTER (WHERE ("s"."id" IS NOT NULL)) AS "social_accounts",
- "json_agg"(DISTINCT "jsonb_build_object"('id', "ip"."id", 'ip_address', "ip"."ip_address")) FILTER (WHERE ("ip"."id" IS NOT NULL)) AS "ip_addresses",
- "json_agg"(DISTINCT "jsonb_build_object"('id', "v"."id", 'plate', "v"."plate", 'model', "v"."model", 'brand', "v"."brand", 'type', "v"."type")) FILTER (WHERE ("v"."id" IS NOT NULL)) AS "vehicles",
- "json_agg"(DISTINCT "jsonb_build_object"('id', "w"."id", 'url', "w"."url", 'registration_date', "w"."registration_date", 'registrar', "w"."registrar", 'ip_address', "w"."ip_address")) FILTER (WHERE ("w"."id" IS NOT NULL)) AS "websites",
- "json_agg"(DISTINCT "jsonb_build_object"('id', "pa"."id", 'address', "pa"."address", 'city', "pa"."city", 'country', "pa"."country")) FILTER (WHERE ("pa"."id" IS NOT NULL)) AS "physical_addresses"
- FROM ((((((("public"."individuals" "i"
- LEFT JOIN "public"."emails" "e_1" ON (("i"."id" = "e_1"."individual_id")))
- LEFT JOIN "public"."phones" "p" ON (("i"."id" = "p"."individual_id")))
- LEFT JOIN "public"."social_accounts" "s" ON (("i"."id" = "s"."individual_id")))
- LEFT JOIN "public"."ip_addresses" "ip" ON (("i"."id" = "ip"."individual_id")))
- LEFT JOIN "public"."vehicles" "v" ON (("i"."id" = "v"."individual_id")))
- LEFT JOIN "public"."websites" "w" ON (("i"."id" = "w"."individual_id")))
- LEFT JOIN "public"."physical_addresses" "pa" ON (("i"."id" = "pa"."individual_id")))
- GROUP BY "i"."id"
- ), "organization_data" AS (
- SELECT "o"."id",
- "o"."name",
- "o"."registration_number",
- "o"."founding_date",
- "o"."sketch_id",
- "json_agg"(DISTINCT "jsonb_build_object"('id', "poa"."id", 'address', "poa"."address", 'city', "poa"."city", 'country', "poa"."country")) FILTER (WHERE ("poa"."id" IS NOT NULL)) AS "addresses",
- "json_agg"(DISTINCT "jsonb_build_object"('id', "op"."id", 'phone_number', "op"."phone_number")) FILTER (WHERE ("op"."id" IS NOT NULL)) AS "phones",
- "json_agg"(DISTINCT "jsonb_build_object"('id', "e_1"."id", 'email', "e_1"."email")) FILTER (WHERE ("e_1"."id" IS NOT NULL)) AS "emails",
- "json_agg"(DISTINCT "jsonb_build_object"('id', "s"."id", 'platform', "s"."platform", 'username', "s"."username")) FILTER (WHERE ("s"."id" IS NOT NULL)) AS "social_accounts",
- "json_agg"(DISTINCT "jsonb_build_object"('id', "ip"."id", 'ip_address', "ip"."ip_address")) FILTER (WHERE ("ip"."id" IS NOT NULL)) AS "ip_addresses",
- "json_agg"(DISTINCT "jsonb_build_object"('id', "v"."id", 'plate', "v"."plate", 'model', "v"."model", 'type', "v"."type", 'brand', "v"."brand")) FILTER (WHERE ("v"."id" IS NOT NULL)) AS "vehicles",
- "json_agg"(DISTINCT "jsonb_build_object"('id', "w"."id", 'url', "w"."url", 'registration_date', "w"."registration_date", 'registrar', "w"."registrar", 'ip_address', "w"."ip_address")) FILTER (WHERE ("w"."id" IS NOT NULL)) AS "websites"
- FROM ((((((("public"."organizations" "o"
- LEFT JOIN "public"."physical_addresses" "poa" ON (("poa"."organization_id" = "o"."id")))
- LEFT JOIN "public"."phones" "op" ON (("op"."organization_id" = "o"."id")))
- LEFT JOIN "public"."emails" "e_1" ON (("e_1"."organization_id" = "o"."id")))
- LEFT JOIN "public"."social_accounts" "s" ON (("s"."organization_id" = "o"."id")))
- LEFT JOIN "public"."ip_addresses" "ip" ON (("ip"."organization_id" = "o"."id")))
- LEFT JOIN "public"."vehicles" "v" ON (("v"."organization_id" = "o"."id")))
- LEFT JOIN "public"."websites" "w" ON (("w"."organization_id" = "o"."id")))
- GROUP BY "o"."id"
- ), "individual_nodes" AS (
- SELECT "id"."sketch_id",
- "jsonb_build_object"('id', ("id"."id")::"text", 'type', 'custom', 'data', "jsonb_build_object"('id', "id"."id", 'full_name', "id"."full_name", 'label', "id"."full_name", 'type', 'individual'), 'position', "jsonb_build_object"('x', 0, 'y', 100)) AS "node"
- FROM "individual_data" "id"
- UNION ALL
- SELECT "id"."sketch_id",
- "jsonb_build_object"('id', ("e_1"."value" ->> 'id'::"text"), 'type', 'custom', 'data', "jsonb_build_object"('id', ("e_1"."value" ->> 'id'::"text"), 'email', ("e_1"."value" ->> 'email'::"text"), 'label', ("e_1"."value" ->> 'email'::"text"), 'type', 'email'), 'position', "jsonb_build_object"('x', 100, 'y', 100)) AS "node"
- FROM "individual_data" "id",
- LATERAL "json_array_elements"("id"."emails") "e_1"("value")
- WHERE (("e_1"."value" ->> 'id'::"text") IS NOT NULL)
- UNION ALL
- SELECT "id"."sketch_id",
- "jsonb_build_object"('id', ("p"."value" ->> 'id'::"text"), 'type', 'custom', 'data', "jsonb_build_object"('id', ("p"."value" ->> 'id'::"text"), 'phone_number', ("p"."value" ->> 'phone_number'::"text"), 'label', ("p"."value" ->> 'phone_number'::"text"), 'type', 'phone'), 'position', "jsonb_build_object"('x', '-100'::integer, 'y', 100)) AS "node"
- FROM "individual_data" "id",
- LATERAL "json_array_elements"("id"."phones") "p"("value")
- WHERE (("p"."value" ->> 'id'::"text") IS NOT NULL)
- UNION ALL
- SELECT "id"."sketch_id",
- "jsonb_build_object"('id', ("s"."value" ->> 'id'::"text"), 'type', 'custom', 'data', "jsonb_build_object"('id', ("s"."value" ->> 'id'::"text"), 'platform', ("s"."value" ->> 'platform'::"text"), 'username', ("s"."value" ->> 'username'::"text"), 'label', "concat"(("s"."value" ->> 'platform'::"text"), ': ', ("s"."value" ->> 'username'::"text")), 'type', 'social'), 'position', "jsonb_build_object"('x', 100, 'y', '-100'::integer)) AS "node"
- FROM "individual_data" "id",
- LATERAL "json_array_elements"("id"."social_accounts") "s"("value")
- WHERE (("s"."value" ->> 'id'::"text") IS NOT NULL)
- UNION ALL
- SELECT "id"."sketch_id",
- "jsonb_build_object"('id', ("ip"."value" ->> 'id'::"text"), 'type', 'custom', 'data', "jsonb_build_object"('id', ("ip"."value" ->> 'id'::"text"), 'ip_address', ("ip"."value" ->> 'ip_address'::"text"), 'label', ("ip"."value" ->> 'ip_address'::"text"), 'type', 'ip'), 'position', "jsonb_build_object"('x', '-100'::integer, 'y', '-100'::integer)) AS "node"
- FROM "individual_data" "id",
- LATERAL "json_array_elements"("id"."ip_addresses") "ip"("value")
- WHERE (("ip"."value" ->> 'id'::"text") IS NOT NULL)
- UNION ALL
- SELECT "id"."sketch_id",
- "jsonb_build_object"('id', ("v"."value" ->> 'id'::"text"), 'type', 'custom', 'data', "jsonb_build_object"('id', ("v"."value" ->> 'id'::"text"), 'plate', ("v"."value" ->> 'plate'::"text"), 'brand', ("v"."value" ->> 'brand'::"text"), 'model', ("v"."value" ->> 'model'::"text"), 'label', "concat"(("v"."value" ->> 'brand'::"text"), ' ', ("v"."value" ->> 'model'::"text"), ': ', ("v"."value" ->> 'plate'::"text")), 'type', 'vehicle'), 'position', "jsonb_build_object"('x', '-100'::integer, 'y', '-100'::integer)) AS "node"
- FROM "individual_data" "id",
- LATERAL "json_array_elements"("id"."vehicles") "v"("value")
- WHERE (("v"."value" ->> 'id'::"text") IS NOT NULL)
- UNION ALL
- SELECT "id"."sketch_id",
- "jsonb_build_object"('id', ("pa"."value" ->> 'id'::"text"), 'type', 'custom', 'data', "jsonb_build_object"('id', ("pa"."value" ->> 'id'::"text"), 'address', ("pa"."value" ->> 'address'::"text"), 'city', ("pa"."value" ->> 'city'::"text"), 'country', ("pa"."value" ->> 'country'::"text"), 'label', "concat"(("pa"."value" ->> 'address'::"text"), ', ', ("pa"."value" ->> 'city'::"text"), ', ', ("pa"."value" ->> 'country'::"text")), 'type', 'address'), 'position', "jsonb_build_object"('x', 100, 'y', 100)) AS "node"
- FROM "individual_data" "id",
- LATERAL "json_array_elements"("id"."physical_addresses") "pa"("value")
- WHERE (("pa"."value" ->> 'id'::"text") IS NOT NULL)
- UNION ALL
- SELECT "id"."sketch_id",
- "jsonb_build_object"('id', ("w"."value" ->> 'id'::"text"), 'type', 'custom', 'data', "jsonb_build_object"('id', ("w"."value" ->> 'id'::"text"), 'url', ("w"."value" ->> 'url'::"text"), 'registration_date', ("w"."value" ->> 'registration_date'::"text"), 'registrar', ("w"."value" ->> 'registrar'::"text"), 'ip_address', ("w"."value" ->> 'ip_address'::"text"), 'label', ("w"."value" ->> 'url'::"text"), 'type', 'website'), 'position', "jsonb_build_object"('x', 200, 'y', '-50'::integer)) AS "node"
- FROM "individual_data" "id",
- LATERAL "json_array_elements"("id"."websites") "w"("value")
- WHERE (("w"."value" ->> 'id'::"text") IS NOT NULL)
- ), "organization_nodes" AS (
- SELECT "od"."sketch_id",
- "jsonb_build_object"('id', ("od"."id")::"text", 'type', 'custom', 'data', "jsonb_build_object"('id', "od"."id", 'name', "od"."name", 'registration_number', "od"."registration_number", 'founding_date', "od"."founding_date", 'label', "od"."name", 'type', 'organization'), 'position', "jsonb_build_object"('x', 200, 'y', 0)) AS "node"
- FROM "organization_data" "od"
- UNION ALL
- SELECT "od"."sketch_id",
- "jsonb_build_object"('id', ("a"."value" ->> 'id'::"text"), 'type', 'custom', 'data', "jsonb_build_object"('id', ("a"."value" ->> 'id'::"text"), 'address', ("a"."value" ->> 'address'::"text"), 'city', ("a"."value" ->> 'city'::"text"), 'country', ("a"."value" ->> 'country'::"text"), 'label', "concat"(("a"."value" ->> 'address'::"text"), ', ', ("a"."value" ->> 'city'::"text"), ', ', ("a"."value" ->> 'country'::"text")), 'type', 'address'), 'position', "jsonb_build_object"('x', 100, 'y', 100)) AS "node"
- FROM "organization_data" "od",
- LATERAL "json_array_elements"("od"."addresses") "a"("value")
- WHERE (("a"."value" ->> 'id'::"text") IS NOT NULL)
- UNION ALL
- SELECT "od"."sketch_id",
- "jsonb_build_object"('id', ("p"."value" ->> 'id'::"text"), 'type', 'custom', 'data', "jsonb_build_object"('id', ("p"."value" ->> 'id'::"text"), 'phone_number', ("p"."value" ->> 'phone_number'::"text"), 'label', ("p"."value" ->> 'phone_number'::"text"), 'type', 'phone'), 'position', "jsonb_build_object"('x', '-100'::integer, 'y', 100)) AS "node"
- FROM "organization_data" "od",
- LATERAL "json_array_elements"("od"."phones") "p"("value")
- WHERE (("p"."value" ->> 'id'::"text") IS NOT NULL)
- UNION ALL
- SELECT "od"."sketch_id",
- "jsonb_build_object"('id', ("e_1"."value" ->> 'id'::"text"), 'type', 'custom', 'data', "jsonb_build_object"('id', ("e_1"."value" ->> 'id'::"text"), 'email', ("e_1"."value" ->> 'email'::"text"), 'label', ("e_1"."value" ->> 'email'::"text"), 'type', 'email'), 'position', "jsonb_build_object"('x', 100, 'y', 100)) AS "node"
- FROM "organization_data" "od",
- LATERAL "json_array_elements"("od"."emails") "e_1"("value")
- WHERE (("e_1"."value" ->> 'id'::"text") IS NOT NULL)
- UNION ALL
- SELECT "od"."sketch_id",
- "jsonb_build_object"('id', ("s"."value" ->> 'id'::"text"), 'type', 'custom', 'data', "jsonb_build_object"('id', ("s"."value" ->> 'id'::"text"), 'platform', ("s"."value" ->> 'platform'::"text"), 'username', ("s"."value" ->> 'username'::"text"), 'label', "concat"(("s"."value" ->> 'platform'::"text"), ': ', ("s"."value" ->> 'username'::"text")), 'type', 'social'), 'position', "jsonb_build_object"('x', 100, 'y', '-100'::integer)) AS "node"
- FROM "organization_data" "od",
- LATERAL "json_array_elements"("od"."social_accounts") "s"("value")
- WHERE (("s"."value" ->> 'id'::"text") IS NOT NULL)
- UNION ALL
- SELECT "od"."sketch_id",
- "jsonb_build_object"('id', ("ip"."value" ->> 'id'::"text"), 'type', 'custom', 'data', "jsonb_build_object"('id', ("ip"."value" ->> 'id'::"text"), 'ip_address', ("ip"."value" ->> 'ip_address'::"text"), 'label', ("ip"."value" ->> 'ip_address'::"text"), 'type', 'ip'), 'position', "jsonb_build_object"('x', '-100'::integer, 'y', '-100'::integer)) AS "node"
- FROM "organization_data" "od",
- LATERAL "json_array_elements"("od"."ip_addresses") "ip"("value")
- WHERE (("ip"."value" ->> 'id'::"text") IS NOT NULL)
- UNION ALL
- SELECT "od"."sketch_id",
- "jsonb_build_object"('id', ("v"."value" ->> 'id'::"text"), 'type', 'custom', 'data', "jsonb_build_object"('id', ("v"."value" ->> 'id'::"text"), 'plate', ("v"."value" ->> 'plate'::"text"), 'brand', ("v"."value" ->> 'brand'::"text"), 'model', ("v"."value" ->> 'model'::"text"), 'label', "concat"(("v"."value" ->> 'brand'::"text"), ' ', ("v"."value" ->> 'model'::"text"), ': ', ("v"."value" ->> 'plate'::"text")), 'type', 'vehicle'), 'position', "jsonb_build_object"('x', '-100'::integer, 'y', '-100'::integer)) AS "node"
- FROM "organization_data" "od",
- LATERAL "json_array_elements"("od"."vehicles") "v"("value")
- WHERE (("v"."value" ->> 'id'::"text") IS NOT NULL)
- UNION ALL
- SELECT "od"."sketch_id",
- "jsonb_build_object"('id', ("w"."value" ->> 'id'::"text"), 'type', 'custom', 'data', "jsonb_build_object"('id', ("w"."value" ->> 'id'::"text"), 'url', ("w"."value" ->> 'url'::"text"), 'registration_date', ("w"."value" ->> 'registration_date'::"text"), 'registrar', ("w"."value" ->> 'registrar'::"text"), 'ip_address', ("w"."value" ->> 'ip_address'::"text"), 'label', ("w"."value" ->> 'url'::"text"), 'type', 'website'), 'position', "jsonb_build_object"('x', 200, 'y', '-50'::integer)) AS "node"
- FROM "organization_data" "od",
- LATERAL "json_array_elements"("od"."websites") "w"("value")
- WHERE (("w"."value" ->> 'id'::"text") IS NOT NULL)
- ), "individual_edges" AS (
- SELECT "id"."sketch_id",
- "jsonb_build_object"('id', "concat"("id"."id", '-', ("e_1"."value" ->> 'id'::"text")), 'source', ("id"."id")::"text", 'target', ("e_1"."value" ->> 'id'::"text"), 'type', 'custom', 'label', 'email') AS "edge"
- FROM "individual_data" "id",
- LATERAL "json_array_elements"("id"."emails") "e_1"("value")
- WHERE (("e_1"."value" ->> 'id'::"text") IS NOT NULL)
- UNION ALL
- SELECT "id"."sketch_id",
- "jsonb_build_object"('id', "concat"("id"."id", '-', ("p"."value" ->> 'id'::"text")), 'source', ("id"."id")::"text", 'target', ("p"."value" ->> 'id'::"text"), 'type', 'custom', 'label', 'phone') AS "edge"
- FROM "individual_data" "id",
- LATERAL "json_array_elements"("id"."phones") "p"("value")
- WHERE (("p"."value" ->> 'id'::"text") IS NOT NULL)
- UNION ALL
- SELECT "id"."sketch_id",
- "jsonb_build_object"('id', "concat"("id"."id", '-', ("s"."value" ->> 'id'::"text")), 'source', ("id"."id")::"text", 'target', ("s"."value" ->> 'id'::"text"), 'type', 'custom', 'label', 'social') AS "edge"
- FROM "individual_data" "id",
- LATERAL "json_array_elements"("id"."social_accounts") "s"("value")
- WHERE (("s"."value" ->> 'id'::"text") IS NOT NULL)
- UNION ALL
- SELECT "id"."sketch_id",
- "jsonb_build_object"('id', "concat"("id"."id", '-', ("ip"."value" ->> 'id'::"text")), 'source', ("id"."id")::"text", 'target', ("ip"."value" ->> 'id'::"text"), 'type', 'custom', 'label', 'IP') AS "edge"
- FROM "individual_data" "id",
- LATERAL "json_array_elements"("id"."ip_addresses") "ip"("value")
- WHERE (("ip"."value" ->> 'id'::"text") IS NOT NULL)
- UNION ALL
- SELECT "id"."sketch_id",
- "jsonb_build_object"('id', "concat"("id"."id", '-', ("v"."value" ->> 'id'::"text")), 'source', ("id"."id")::"text", 'target', ("v"."value" ->> 'id'::"text"), 'type', 'custom', 'label', ("v"."value" ->> 'type'::"text")) AS "edge"
- FROM "individual_data" "id",
- LATERAL "json_array_elements"("id"."vehicles") "v"("value")
- WHERE (("v"."value" ->> 'id'::"text") IS NOT NULL)
- UNION ALL
- SELECT "id"."sketch_id",
- "jsonb_build_object"('id', "concat"("id"."id", '-', ("pa"."value" ->> 'id'::"text")), 'source', ("id"."id")::"text", 'target', ("pa"."value" ->> 'id'::"text"), 'type', 'custom', 'label', 'address') AS "edge"
- FROM "individual_data" "id",
- LATERAL "json_array_elements"("id"."physical_addresses") "pa"("value")
- WHERE (("pa"."value" ->> 'id'::"text") IS NOT NULL)
- UNION ALL
- SELECT "id"."sketch_id",
- "jsonb_build_object"('id', "concat"("id"."id", '-', ("w"."value" ->> 'id'::"text")), 'source', ("id"."id")::"text", 'target', ("w"."value" ->> 'id'::"text"), 'type', 'custom', 'label', 'website') AS "edge"
- FROM "individual_data" "id",
- LATERAL "json_array_elements"("id"."websites") "w"("value")
- WHERE (("w"."value" ->> 'id'::"text") IS NOT NULL)
- ), "organization_edges" AS (
- SELECT "od"."sketch_id",
- "jsonb_build_object"('id', "concat"("od"."id", '-', ("a"."value" ->> 'id'::"text")), 'source', ("od"."id")::"text", 'target', ("a"."value" ->> 'id'::"text"), 'type', 'custom', 'label', 'address') AS "edge"
- FROM "organization_data" "od",
- LATERAL "json_array_elements"("od"."addresses") "a"("value")
- WHERE (("a"."value" ->> 'id'::"text") IS NOT NULL)
- UNION ALL
- SELECT "od"."sketch_id",
- "jsonb_build_object"('id', "concat"("od"."id", '-', ("p"."value" ->> 'id'::"text")), 'source', ("od"."id")::"text", 'target', ("p"."value" ->> 'id'::"text"), 'type', 'custom', 'label', 'phone') AS "edge"
- FROM "organization_data" "od",
- LATERAL "json_array_elements"("od"."phones") "p"("value")
- WHERE (("p"."value" ->> 'id'::"text") IS NOT NULL)
- UNION ALL
- SELECT "od"."sketch_id",
- "jsonb_build_object"('id', "concat"("od"."id", '-', ("e_1"."value" ->> 'id'::"text")), 'source', ("od"."id")::"text", 'target', ("e_1"."value" ->> 'id'::"text"), 'type', 'custom', 'label', 'email') AS "edge"
- FROM "organization_data" "od",
- LATERAL "json_array_elements"("od"."emails") "e_1"("value")
- WHERE (("e_1"."value" ->> 'id'::"text") IS NOT NULL)
- UNION ALL
- SELECT "od"."sketch_id",
- "jsonb_build_object"('id', "concat"("od"."id", '-', ("s"."value" ->> 'id'::"text")), 'source', ("od"."id")::"text", 'target', ("s"."value" ->> 'id'::"text"), 'type', 'custom', 'label', 'social') AS "edge"
- FROM "organization_data" "od",
- LATERAL "json_array_elements"("od"."social_accounts") "s"("value")
- WHERE (("s"."value" ->> 'id'::"text") IS NOT NULL)
- UNION ALL
- SELECT "od"."sketch_id",
- "jsonb_build_object"('id', "concat"("od"."id", '-', ("ip"."value" ->> 'id'::"text")), 'source', ("od"."id")::"text", 'target', ("ip"."value" ->> 'id'::"text"), 'type', 'custom', 'label', 'IP') AS "edge"
- FROM "organization_data" "od",
- LATERAL "json_array_elements"("od"."ip_addresses") "ip"("value")
- WHERE (("ip"."value" ->> 'id'::"text") IS NOT NULL)
- UNION ALL
- SELECT "od"."sketch_id",
- "jsonb_build_object"('id', "concat"("od"."id", '-', ("v"."value" ->> 'id'::"text")), 'source', ("od"."id")::"text", 'target', ("v"."value" ->> 'id'::"text"), 'type', 'custom', 'label', ("v"."value" ->> 'type'::"text")) AS "edge"
- FROM "organization_data" "od",
- LATERAL "json_array_elements"("od"."vehicles") "v"("value")
- WHERE (("v"."value" ->> 'id'::"text") IS NOT NULL)
- UNION ALL
- SELECT "od"."sketch_id",
- "jsonb_build_object"('id', "concat"("od"."id", '-', ("w"."value" ->> 'id'::"text")), 'source', ("od"."id")::"text", 'target', ("w"."value" ->> 'id'::"text"), 'type', 'custom', 'label', 'website') AS "edge"
- FROM "organization_data" "od",
- LATERAL "json_array_elements"("od"."websites") "w"("value")
- WHERE (("w"."value" ->> 'id'::"text") IS NOT NULL)
- ), "debug_relationships" AS (
- SELECT "individuals_individuals"."sketch_id",
- "count"(*) AS "relationship_count"
- FROM "public"."individuals_individuals"
- GROUP BY "individuals_individuals"."sketch_id"
- ), "relationship_edges" AS (
- SELECT "r"."sketch_id",
- "jsonb_build_object"('id', ("r"."id")::"text", 'source', ("r"."individual_a")::"text", 'target', ("r"."individual_b")::"text", 'type', 'custom', 'label', COALESCE("r"."relation_type", 'related'::"text"), 'data', "jsonb_build_object"('confidence_level', "r"."confidence_level", 'relation_type', "r"."relation_type")) AS "edge"
- FROM "public"."individuals_individuals" "r"
- WHERE (("r"."individual_a" IS NOT NULL) AND ("r"."individual_b" IS NOT NULL))
- ), "orgs_individuals_edges" AS (
- SELECT "r"."sketch_id",
- "jsonb_build_object"('id', ("r"."id")::"text", 'source', ("r"."organization_id")::"text", 'target', ("r"."individual_id")::"text", 'type', 'custom', 'label', COALESCE("r"."relation_type", 'employee'::"text"), 'data', "jsonb_build_object"('relation_type', "r"."relation_type")) AS "edge"
- FROM "public"."organizations_individuals" "r"
- WHERE (("r"."organization_id" IS NOT NULL) AND ("r"."individual_id" IS NOT NULL))
- ), "orgs_organizations_edges" AS (
- SELECT "oo"."sketch_id",
- "jsonb_build_object"('id', ("oo"."id")::"text", 'source', ("oo"."organization_a")::"text", 'target', ("oo"."organization_b")::"text", 'type', 'custom', 'label', COALESCE("oo"."relation_type", 'related'::"text"), 'data', "jsonb_build_object"('relation_type', "oo"."relation_type")) AS "edge"
- FROM "public"."organizations_organizations" "oo"
- WHERE (("oo"."organization_a" IS NOT NULL) AND ("oo"."organization_b" IS NOT NULL))
- ), "nodes_by_investigation" AS (
- SELECT "all_nodes"."sketch_id",
- "json_agg"("all_nodes"."node") AS "nodes"
- FROM ( SELECT "individual_nodes"."sketch_id",
- "individual_nodes"."node"
- FROM "individual_nodes"
- UNION ALL
- SELECT "organization_nodes"."sketch_id",
- "organization_nodes"."node"
- FROM "organization_nodes") "all_nodes"
- GROUP BY "all_nodes"."sketch_id"
- ), "edges_by_investigation" AS (
- SELECT "all_edges"."sketch_id",
- "json_agg"("all_edges"."edge") AS "edges"
- FROM ( SELECT "individual_edges"."sketch_id",
- "individual_edges"."edge"
- FROM "individual_edges"
- UNION ALL
- SELECT "organization_edges"."sketch_id",
- "organization_edges"."edge"
- FROM "organization_edges"
- UNION ALL
- SELECT "relationship_edges"."sketch_id",
- "relationship_edges"."edge"
- FROM "relationship_edges"
- UNION ALL
- SELECT "orgs_individuals_edges"."sketch_id",
- "orgs_individuals_edges"."edge"
- FROM "orgs_individuals_edges"
- UNION ALL
- SELECT "orgs_organizations_edges"."sketch_id",
- "orgs_organizations_edges"."edge"
- FROM "orgs_organizations_edges") "all_edges"
- GROUP BY "all_edges"."sketch_id"
- )
- SELECT "inv"."id" AS "sketch_id",
- COALESCE("n"."nodes", '[]'::"json") AS "nodes",
- COALESCE("e"."edges", '[]'::"json") AS "edges",
- "dr"."relationship_count" AS "debug_relationship_count"
- FROM ((("public"."sketches" "inv"
- LEFT JOIN "nodes_by_investigation" "n" ON (("n"."sketch_id" = "inv"."id")))
- LEFT JOIN "edges_by_investigation" "e" ON (("e"."sketch_id" = "inv"."id")))
- LEFT JOIN "debug_relationships" "dr" ON (("dr"."sketch_id" = "inv"."id")));
-
-
-
-CREATE OR REPLACE TRIGGER "on_investigation_insert" AFTER INSERT ON "public"."investigations" FOR EACH ROW EXECUTE FUNCTION "public"."handle_new_investigation"();
-
-
-
-CREATE OR REPLACE TRIGGER "on_sketch_insert" AFTER INSERT ON "public"."sketches" FOR EACH ROW EXECUTE FUNCTION "public"."handle_new_sketch"();
-
-
-
-CREATE OR REPLACE TRIGGER "trg_sync_investigation_profile" AFTER INSERT ON "public"."sketches_profiles" FOR EACH ROW EXECUTE FUNCTION "public"."sync_investigation_profile_from_sketch"();
-
-
-
-CREATE OR REPLACE TRIGGER "trigger_update_project_last_updated_emails" AFTER INSERT OR DELETE OR UPDATE ON "public"."emails" FOR EACH ROW EXECUTE FUNCTION "public"."update_investigation_last_updated"();
-
-
-
-CREATE OR REPLACE TRIGGER "trigger_update_project_last_updated_individuals" AFTER INSERT OR DELETE OR UPDATE ON "public"."individuals" FOR EACH ROW EXECUTE FUNCTION "public"."update_investigation_last_updated"();
-
-
-
-CREATE OR REPLACE TRIGGER "trigger_update_project_last_updated_ip_addresses" AFTER INSERT OR DELETE OR UPDATE ON "public"."ip_addresses" FOR EACH ROW EXECUTE FUNCTION "public"."update_investigation_last_updated"();
-
-
-
-CREATE OR REPLACE TRIGGER "trigger_update_project_last_updated_phones" AFTER INSERT OR DELETE OR UPDATE ON "public"."phones" FOR EACH ROW EXECUTE FUNCTION "public"."update_investigation_last_updated"();
-
-
-
-CREATE OR REPLACE TRIGGER "trigger_update_project_last_updated_physical_addresses" AFTER INSERT OR DELETE OR UPDATE ON "public"."physical_addresses" FOR EACH ROW EXECUTE FUNCTION "public"."update_investigation_last_updated"();
-
-
-
-CREATE OR REPLACE TRIGGER "trigger_update_project_last_updated_relationships" AFTER INSERT OR DELETE OR UPDATE ON "public"."individuals_individuals" FOR EACH ROW EXECUTE FUNCTION "public"."update_investigation_last_updated"();
-
-
-
-CREATE OR REPLACE TRIGGER "trigger_update_project_last_updated_social_accounts" AFTER INSERT OR DELETE OR UPDATE ON "public"."social_accounts" FOR EACH ROW EXECUTE FUNCTION "public"."update_investigation_last_updated"();
-
-
-
-CREATE OR REPLACE TRIGGER "update_investigation_last_updated" AFTER UPDATE ON "public"."sketches" FOR EACH ROW EXECUTE FUNCTION "public"."update_sketch_last_updated"();
-
-
-
-CREATE OR REPLACE TRIGGER "update_last_updated_at_trigger" AFTER UPDATE ON "public"."sketches" FOR EACH ROW EXECUTE FUNCTION "public"."update_last_updated_at"();
-
-
-
-ALTER TABLE ONLY "public"."accounts_breaches"
- ADD CONSTRAINT "accounts_breaches_breach_id_fkey" FOREIGN KEY ("breach_id") REFERENCES "public"."breaches"("id") ON UPDATE CASCADE ON DELETE CASCADE;
-
-
-
-ALTER TABLE ONLY "public"."emails"
- ADD CONSTRAINT "emails_individual_id_fkey" FOREIGN KEY ("individual_id") REFERENCES "public"."individuals"("id") ON DELETE CASCADE;
-
-
-
-ALTER TABLE ONLY "public"."emails"
- ADD CONSTRAINT "emails_organization_id_fkey" FOREIGN KEY ("organization_id") REFERENCES "public"."organizations"("id") ON DELETE SET NULL;
-
-
-
-ALTER TABLE ONLY "public"."emails"
- ADD CONSTRAINT "emails_sketch_id_fkey" FOREIGN KEY ("sketch_id") REFERENCES "public"."sketches"("id") ON DELETE CASCADE;
-
-
-
-ALTER TABLE ONLY "public"."feedbacks"
- ADD CONSTRAINT "feedbacks_owner_id_fkey" FOREIGN KEY ("owner_id") REFERENCES "public"."profiles"("id");
-
-
-
-ALTER TABLE ONLY "public"."groups"
- ADD CONSTRAINT "groups_sketch_id_fkey" FOREIGN KEY ("sketch_id") REFERENCES "public"."sketches"("id");
-
-
-
-ALTER TABLE ONLY "public"."individuals"
- ADD CONSTRAINT "individuals_group_id_fkey" FOREIGN KEY ("group_id") REFERENCES "public"."groups"("id") ON DELETE SET NULL;
-
-
-
-ALTER TABLE ONLY "public"."individuals"
- ADD CONSTRAINT "individuals_sketch_id_fkey" FOREIGN KEY ("sketch_id") REFERENCES "public"."sketches"("id") ON DELETE CASCADE;
-
-
-
-ALTER TABLE ONLY "public"."investigations"
- ADD CONSTRAINT "investigations_owner_id_fkey" FOREIGN KEY ("owner_id") REFERENCES "public"."profiles"("id") ON UPDATE CASCADE ON DELETE CASCADE;
-
-
-
-ALTER TABLE ONLY "public"."sketches_profiles"
- ADD CONSTRAINT "investigations_profiles_profile_id_fkey" FOREIGN KEY ("profile_id") REFERENCES "public"."profiles"("id") ON UPDATE CASCADE ON DELETE CASCADE;
-
-
-
-ALTER TABLE ONLY "public"."sketches"
- ADD CONSTRAINT "investigations_project_id_fkey" FOREIGN KEY ("investigation_id") REFERENCES "public"."investigations"("id") ON UPDATE CASCADE ON DELETE CASCADE;
-
-
-
-ALTER TABLE ONLY "public"."ip_addresses"
- ADD CONSTRAINT "ip_addresses_individual_id_fkey" FOREIGN KEY ("individual_id") REFERENCES "public"."individuals"("id") ON DELETE CASCADE;
-
-
-
-ALTER TABLE ONLY "public"."ip_addresses"
- ADD CONSTRAINT "ip_addresses_organization_id_fkey" FOREIGN KEY ("organization_id") REFERENCES "public"."organizations"("id") ON DELETE SET NULL;
-
-
-
-ALTER TABLE ONLY "public"."ip_addresses"
- ADD CONSTRAINT "ip_addresses_sketch_id_fkey" FOREIGN KEY ("sketch_id") REFERENCES "public"."sketches"("id") ON DELETE CASCADE;
-
-
-
-ALTER TABLE ONLY "public"."organizations_individuals"
- ADD CONSTRAINT "organizations_individuals_individual_id_fkey" FOREIGN KEY ("individual_id") REFERENCES "public"."individuals"("id") ON UPDATE CASCADE ON DELETE CASCADE;
-
-
-
-ALTER TABLE ONLY "public"."organizations_individuals"
- ADD CONSTRAINT "organizations_individuals_organization_id_fkey" FOREIGN KEY ("organization_id") REFERENCES "public"."organizations"("id") ON UPDATE CASCADE ON DELETE CASCADE;
-
-
-
-ALTER TABLE ONLY "public"."organizations_individuals"
- ADD CONSTRAINT "organizations_individuals_sketch_id_fkey" FOREIGN KEY ("sketch_id") REFERENCES "public"."sketches"("id") ON UPDATE CASCADE ON DELETE CASCADE;
-
-
-
-ALTER TABLE ONLY "public"."organizations_organizations"
- ADD CONSTRAINT "organizations_organizations_organization_a_fkey" FOREIGN KEY ("organization_a") REFERENCES "public"."organizations"("id") ON UPDATE CASCADE ON DELETE CASCADE;
-
-
-
-ALTER TABLE ONLY "public"."organizations_organizations"
- ADD CONSTRAINT "organizations_organizations_organization_b_fkey" FOREIGN KEY ("organization_b") REFERENCES "public"."organizations"("id") ON UPDATE CASCADE ON DELETE CASCADE;
-
-
-
-ALTER TABLE ONLY "public"."organizations_organizations"
- ADD CONSTRAINT "organizations_organizations_sketch_id_fkey" FOREIGN KEY ("sketch_id") REFERENCES "public"."sketches"("id") ON UPDATE CASCADE ON DELETE CASCADE;
-
-
-
-ALTER TABLE ONLY "public"."organizations"
- ADD CONSTRAINT "organizations_sketch_id_fkey" FOREIGN KEY ("sketch_id") REFERENCES "public"."sketches"("id") ON UPDATE CASCADE ON DELETE CASCADE;
-
-
-
-ALTER TABLE ONLY "public"."phones"
- ADD CONSTRAINT "phones_individual_id_fkey" FOREIGN KEY ("individual_id") REFERENCES "public"."individuals"("id") ON DELETE CASCADE;
-
-
-
-ALTER TABLE ONLY "public"."phones"
- ADD CONSTRAINT "phones_organization_id_fkey" FOREIGN KEY ("organization_id") REFERENCES "public"."organizations"("id") ON DELETE SET NULL;
-
-
-
-ALTER TABLE ONLY "public"."phones"
- ADD CONSTRAINT "phones_sketch_id_fkey" FOREIGN KEY ("sketch_id") REFERENCES "public"."sketches"("id") ON DELETE CASCADE;
-
-
-
-ALTER TABLE ONLY "public"."physical_addresses"
- ADD CONSTRAINT "physical_addresses_individual_id_fkey" FOREIGN KEY ("individual_id") REFERENCES "public"."individuals"("id") ON UPDATE CASCADE ON DELETE CASCADE;
-
-
-
-ALTER TABLE ONLY "public"."physical_addresses"
- ADD CONSTRAINT "physical_addresses_organization_id_fkey" FOREIGN KEY ("organization_id") REFERENCES "public"."organizations"("id") ON UPDATE CASCADE ON DELETE CASCADE;
-
-
-
-ALTER TABLE ONLY "public"."physical_addresses"
- ADD CONSTRAINT "physical_addresses_sketch_id_fkey" FOREIGN KEY ("sketch_id") REFERENCES "public"."sketches"("id") ON DELETE CASCADE;
-
-
-
-ALTER TABLE ONLY "public"."profiles"
- ADD CONSTRAINT "profiles_id_fkey" FOREIGN KEY ("id") REFERENCES "auth"."users"("id") ON UPDATE CASCADE ON DELETE CASCADE;
-
-
-
-ALTER TABLE ONLY "public"."investigations_profiles"
- ADD CONSTRAINT "projects_profiles_profile_id_fkey" FOREIGN KEY ("profile_id") REFERENCES "public"."profiles"("id") ON UPDATE CASCADE ON DELETE CASCADE;
-
-
-
-ALTER TABLE ONLY "public"."investigations_profiles"
- ADD CONSTRAINT "projects_profiles_project_id_fkey" FOREIGN KEY ("investigation_id") REFERENCES "public"."investigations"("id") ON UPDATE CASCADE ON DELETE CASCADE;
-
-
-
-ALTER TABLE ONLY "public"."individuals_individuals"
- ADD CONSTRAINT "relationships_individual_a_fkey" FOREIGN KEY ("individual_a") REFERENCES "public"."individuals"("id") ON DELETE CASCADE;
-
-
-
-ALTER TABLE ONLY "public"."individuals_individuals"
- ADD CONSTRAINT "relationships_individual_b_fkey" FOREIGN KEY ("individual_b") REFERENCES "public"."individuals"("id") ON DELETE CASCADE;
-
-
-
-ALTER TABLE ONLY "public"."individuals_individuals"
- ADD CONSTRAINT "relationships_sketch_id_fkey" FOREIGN KEY ("sketch_id") REFERENCES "public"."sketches"("id") ON DELETE CASCADE;
-
-
-
-ALTER TABLE ONLY "public"."scans"
- ADD CONSTRAINT "scans_sketch_id_fkey" FOREIGN KEY ("sketch_id") REFERENCES "public"."sketches"("id") ON UPDATE CASCADE ON DELETE CASCADE;
-
-
-
-ALTER TABLE ONLY "public"."sketches"
- ADD CONSTRAINT "sketches_owner_id_fkey" FOREIGN KEY ("owner_id") REFERENCES "public"."profiles"("id") ON UPDATE CASCADE ON DELETE CASCADE;
-
-
-
-ALTER TABLE ONLY "public"."sketches_profiles"
- ADD CONSTRAINT "sketches_profiles_sketch_id_fkey" FOREIGN KEY ("sketch_id") REFERENCES "public"."sketches"("id") ON UPDATE CASCADE ON DELETE CASCADE;
-
-
-
-ALTER TABLE ONLY "public"."social_accounts"
- ADD CONSTRAINT "social_accounts_individual_id_fkey" FOREIGN KEY ("individual_id") REFERENCES "public"."individuals"("id") ON UPDATE CASCADE ON DELETE CASCADE;
-
-
-
-ALTER TABLE ONLY "public"."social_accounts"
- ADD CONSTRAINT "social_accounts_organization_id_fkey" FOREIGN KEY ("organization_id") REFERENCES "public"."organizations"("id") ON DELETE SET NULL;
-
-
-
-ALTER TABLE ONLY "public"."social_accounts"
- ADD CONSTRAINT "social_accounts_sketch_id_fkey" FOREIGN KEY ("sketch_id") REFERENCES "public"."sketches"("id") ON DELETE CASCADE;
-
-
-
-ALTER TABLE ONLY "public"."vehicles"
- ADD CONSTRAINT "vehicles_individual_id_fkey" FOREIGN KEY ("individual_id") REFERENCES "public"."individuals"("id") ON UPDATE CASCADE ON DELETE SET NULL;
-
-
-
-ALTER TABLE ONLY "public"."vehicles"
- ADD CONSTRAINT "vehicles_organization_id_fkey" FOREIGN KEY ("organization_id") REFERENCES "public"."organizations"("id") ON DELETE SET NULL;
-
-
-
-ALTER TABLE ONLY "public"."vehicles"
- ADD CONSTRAINT "vehicles_sketch_id_fkey" FOREIGN KEY ("sketch_id") REFERENCES "public"."sketches"("id") ON UPDATE CASCADE ON DELETE CASCADE;
-
-
-
-ALTER TABLE ONLY "public"."websites"
- ADD CONSTRAINT "websites_individual_id_fkey" FOREIGN KEY ("individual_id") REFERENCES "public"."individuals"("id") ON UPDATE CASCADE ON DELETE CASCADE;
-
-
-
-ALTER TABLE ONLY "public"."websites"
- ADD CONSTRAINT "websites_organization_id_fkey" FOREIGN KEY ("organization_id") REFERENCES "public"."organizations"("id") ON UPDATE CASCADE ON DELETE CASCADE;
-
-
-
-ALTER TABLE ONLY "public"."websites"
- ADD CONSTRAINT "websites_sketch_id_fkey" FOREIGN KEY ("sketch_id") REFERENCES "public"."sketches"("id") ON UPDATE CASCADE ON DELETE CASCADE;
-
-
-
-CREATE POLICY "Can create sketches in investigations you are part of" ON "public"."sketches" FOR INSERT TO "authenticated" WITH CHECK (((EXISTS ( SELECT 1
- FROM "public"."investigations_profiles" "ip"
- WHERE (("ip"."investigation_id" = "sketches"."investigation_id") AND ("ip"."profile_id" = "auth"."uid"())))) OR ("auth"."uid"() = "owner_id")));
-
-
-
-CREATE POLICY "Can delete emails if you have access to the sketch" ON "public"."emails" FOR DELETE TO "authenticated" USING ((EXISTS ( SELECT 1
- FROM "public"."sketches_profiles" "sp"
- WHERE (("sp"."sketch_id" = "emails"."sketch_id") AND ("sp"."profile_id" = "auth"."uid"())))));
-
-
-
-CREATE POLICY "Can delete individuals if you have access to the sketch" ON "public"."individuals" FOR DELETE TO "authenticated" USING ((EXISTS ( SELECT 1
- FROM "public"."sketches_profiles" "sp"
- WHERE (("sp"."sketch_id" = "individuals"."sketch_id") AND ("sp"."profile_id" = "auth"."uid"())))));
-
-
-
-CREATE POLICY "Can delete individuals_individuals if you have access to the sk" ON "public"."individuals_individuals" FOR DELETE TO "authenticated" USING ((EXISTS ( SELECT 1
- FROM "public"."sketches_profiles" "sp"
- WHERE (("sp"."sketch_id" = "individuals_individuals"."sketch_id") AND ("sp"."profile_id" = "auth"."uid"())))));
-
-
-
-CREATE POLICY "Can delete ip_addresses if you have access to the sketch" ON "public"."ip_addresses" FOR DELETE TO "authenticated" USING ((EXISTS ( SELECT 1
- FROM "public"."sketches_profiles" "sp"
- WHERE (("sp"."sketch_id" = "ip_addresses"."sketch_id") AND ("sp"."profile_id" = "auth"."uid"())))));
-
-
-
-CREATE POLICY "Can delete organizations if you have access to the sketch" ON "public"."organizations" FOR DELETE TO "authenticated" USING ((EXISTS ( SELECT 1
- FROM "public"."sketches_profiles" "sp"
- WHERE (("sp"."sketch_id" = "organizations"."sketch_id") AND ("sp"."profile_id" = "auth"."uid"())))));
-
-
-
-CREATE POLICY "Can delete organizations_individuals if you have access to the " ON "public"."organizations_individuals" FOR DELETE TO "authenticated" USING ((EXISTS ( SELECT 1
- FROM "public"."sketches_profiles" "sp"
- WHERE (("sp"."sketch_id" = "organizations_individuals"."sketch_id") AND ("sp"."profile_id" = "auth"."uid"())))));
-
-
-
-CREATE POLICY "Can delete organizations_organizations if you have access to th" ON "public"."organizations_organizations" FOR DELETE TO "authenticated" USING ((EXISTS ( SELECT 1
- FROM "public"."sketches_profiles" "sp"
- WHERE (("sp"."sketch_id" = "organizations_organizations"."sketch_id") AND ("sp"."profile_id" = "auth"."uid"())))));
-
-
-
-CREATE POLICY "Can delete phones if you have access to the sketch" ON "public"."phones" FOR DELETE TO "authenticated" USING ((EXISTS ( SELECT 1
- FROM "public"."sketches_profiles" "sp"
- WHERE (("sp"."sketch_id" = "phones"."sketch_id") AND ("sp"."profile_id" = "auth"."uid"())))));
-
-
-
-CREATE POLICY "Can delete scans if you have access to the sketch" ON "public"."scans" FOR DELETE TO "authenticated" USING ((EXISTS ( SELECT 1
- FROM "public"."sketches_profiles" "sp"
- WHERE (("sp"."sketch_id" = "scans"."sketch_id") AND ("sp"."profile_id" = "auth"."uid"())))));
-
-
-
-CREATE POLICY "Can delete social_accounts if you have access to the sketch" ON "public"."social_accounts" FOR DELETE TO "authenticated" USING ((EXISTS ( SELECT 1
- FROM "public"."sketches_profiles" "sp"
- WHERE (("sp"."sketch_id" = "social_accounts"."sketch_id") AND ("sp"."profile_id" = "auth"."uid"())))));
-
-
-
-CREATE POLICY "Can delete vehicles if you have access to the sketch" ON "public"."vehicles" FOR DELETE TO "authenticated" USING ((EXISTS ( SELECT 1
- FROM "public"."sketches_profiles" "sp"
- WHERE (("sp"."sketch_id" = "vehicles"."sketch_id") AND ("sp"."profile_id" = "auth"."uid"())))));
-
-
-
-CREATE POLICY "Can delete websites if you have access to the sketch" ON "public"."websites" FOR DELETE TO "authenticated" USING ((EXISTS ( SELECT 1
- FROM "public"."sketches_profiles" "sp"
- WHERE (("sp"."sketch_id" = "websites"."sketch_id") AND ("sp"."profile_id" = "auth"."uid"())))));
-
-
-
-CREATE POLICY "Can insert emails if you have access to the sketch" ON "public"."emails" FOR INSERT TO "authenticated" WITH CHECK ((EXISTS ( SELECT 1
- FROM "public"."sketches_profiles" "sp"
- WHERE (("sp"."sketch_id" = "emails"."sketch_id") AND ("sp"."profile_id" = "auth"."uid"())))));
-
-
-
-CREATE POLICY "Can insert individuals if you have access to the sketch" ON "public"."individuals" FOR INSERT TO "authenticated" WITH CHECK ((EXISTS ( SELECT 1
- FROM "public"."sketches_profiles" "sp"
- WHERE (("sp"."sketch_id" = "individuals"."sketch_id") AND ("sp"."profile_id" = "auth"."uid"())))));
-
-
-
-CREATE POLICY "Can insert individuals_individuals if you have access to the sk" ON "public"."individuals_individuals" FOR INSERT TO "authenticated" WITH CHECK ((EXISTS ( SELECT 1
- FROM "public"."sketches_profiles" "sp"
- WHERE (("sp"."sketch_id" = "individuals_individuals"."sketch_id") AND ("sp"."profile_id" = "auth"."uid"())))));
-
-
-
-CREATE POLICY "Can insert ip_addresses if you have access to the sketch" ON "public"."ip_addresses" FOR INSERT TO "authenticated" WITH CHECK ((EXISTS ( SELECT 1
- FROM "public"."sketches_profiles" "sp"
- WHERE (("sp"."sketch_id" = "ip_addresses"."sketch_id") AND ("sp"."profile_id" = "auth"."uid"())))));
-
-
-
-CREATE POLICY "Can insert organizations if you have access to the sketch" ON "public"."organizations" FOR INSERT TO "authenticated" WITH CHECK ((EXISTS ( SELECT 1
- FROM "public"."sketches_profiles" "sp"
- WHERE (("sp"."sketch_id" = "organizations"."sketch_id") AND ("sp"."profile_id" = "auth"."uid"())))));
-
-
-
-CREATE POLICY "Can insert organizations_individuals if you have access to the " ON "public"."organizations_individuals" FOR INSERT TO "authenticated" WITH CHECK ((EXISTS ( SELECT 1
- FROM "public"."sketches_profiles" "sp"
- WHERE (("sp"."sketch_id" = "organizations_individuals"."sketch_id") AND ("sp"."profile_id" = "auth"."uid"())))));
-
-
-
-CREATE POLICY "Can insert organizations_organizations if you have access to th" ON "public"."organizations_organizations" FOR INSERT TO "authenticated" WITH CHECK ((EXISTS ( SELECT 1
- FROM "public"."sketches_profiles" "sp"
- WHERE (("sp"."sketch_id" = "organizations_organizations"."sketch_id") AND ("sp"."profile_id" = "auth"."uid"())))));
-
-
-
-CREATE POLICY "Can insert phones if you have access to the sketch" ON "public"."phones" FOR INSERT TO "authenticated" WITH CHECK ((EXISTS ( SELECT 1
- FROM "public"."sketches_profiles" "sp"
- WHERE (("sp"."sketch_id" = "phones"."sketch_id") AND ("sp"."profile_id" = "auth"."uid"())))));
-
-
-
-CREATE POLICY "Can insert scans if you have access to the sketch" ON "public"."scans" FOR INSERT TO "authenticated" WITH CHECK ((EXISTS ( SELECT 1
- FROM "public"."sketches_profiles" "sp"
- WHERE (("sp"."sketch_id" = "scans"."sketch_id") AND ("sp"."profile_id" = "auth"."uid"())))));
-
-
-
-CREATE POLICY "Can insert social_accounts if you have access to the sketch" ON "public"."social_accounts" FOR INSERT TO "authenticated" WITH CHECK ((EXISTS ( SELECT 1
- FROM "public"."sketches_profiles" "sp"
- WHERE (("sp"."sketch_id" = "social_accounts"."sketch_id") AND ("sp"."profile_id" = "auth"."uid"())))));
-
-
-
-CREATE POLICY "Can insert vehicles if you have access to the sketch" ON "public"."vehicles" FOR INSERT TO "authenticated" WITH CHECK ((EXISTS ( SELECT 1
- FROM "public"."sketches_profiles" "sp"
- WHERE (("sp"."sketch_id" = "vehicles"."sketch_id") AND ("sp"."profile_id" = "auth"."uid"())))));
-
-
-
-CREATE POLICY "Can insert websites if you have access to the sketch" ON "public"."websites" FOR INSERT TO "authenticated" WITH CHECK ((EXISTS ( SELECT 1
- FROM "public"."sketches_profiles" "sp"
- WHERE (("sp"."sketch_id" = "websites"."sketch_id") AND ("sp"."profile_id" = "auth"."uid"())))));
-
-
-
-CREATE POLICY "Can read all profiles in investigations you are part of" ON "public"."investigations_profiles" FOR SELECT TO "authenticated" USING (true);
-
-
-
-CREATE POLICY "Can read all sketches in investigations you are part of" ON "public"."sketches" FOR SELECT TO "authenticated" USING ((EXISTS ( SELECT 1
- FROM "public"."sketches_profiles" "ip"
- WHERE ((("ip"."sketch_id" = "sketches"."id") AND ("ip"."profile_id" = "auth"."uid"())) OR ("sketches"."owner_id" = "auth"."uid"())))));
-
-
-
-CREATE POLICY "Can read emails if you have access to the sketch" ON "public"."emails" FOR SELECT TO "authenticated" USING ((EXISTS ( SELECT 1
- FROM "public"."sketches_profiles" "sp"
- WHERE (("sp"."sketch_id" = "emails"."sketch_id") AND ("sp"."profile_id" = "auth"."uid"())))));
-
-
-
-CREATE POLICY "Can read individuals if you have access to the sketch" ON "public"."individuals" FOR SELECT TO "authenticated" USING ((EXISTS ( SELECT 1
- FROM "public"."sketches_profiles" "sp"
- WHERE (("sp"."sketch_id" = "individuals"."sketch_id") AND ("sp"."profile_id" = "auth"."uid"())))));
-
-
-
-CREATE POLICY "Can read individuals_individuals if you have access to the sket" ON "public"."individuals_individuals" FOR SELECT TO "authenticated" USING ((EXISTS ( SELECT 1
- FROM "public"."sketches_profiles" "sp"
- WHERE (("sp"."sketch_id" = "individuals_individuals"."sketch_id") AND ("sp"."profile_id" = "auth"."uid"())))));
-
-
-
-CREATE POLICY "Can read ip_addresses if you have access to the sketch" ON "public"."ip_addresses" FOR SELECT TO "authenticated" USING ((EXISTS ( SELECT 1
- FROM "public"."sketches_profiles" "sp"
- WHERE (("sp"."sketch_id" = "ip_addresses"."sketch_id") AND ("sp"."profile_id" = "auth"."uid"())))));
-
-
-
-CREATE POLICY "Can read organizations if you have access to the sketch" ON "public"."organizations" FOR SELECT TO "authenticated" USING ((EXISTS ( SELECT 1
- FROM "public"."sketches_profiles" "sp"
- WHERE (("sp"."sketch_id" = "organizations"."sketch_id") AND ("sp"."profile_id" = "auth"."uid"())))));
-
-
-
-CREATE POLICY "Can read organizations_individuals if you have access to the sk" ON "public"."organizations_individuals" FOR SELECT TO "authenticated" USING ((EXISTS ( SELECT 1
- FROM "public"."sketches_profiles" "sp"
- WHERE (("sp"."sketch_id" = "organizations_individuals"."sketch_id") AND ("sp"."profile_id" = "auth"."uid"())))));
-
-
-
-CREATE POLICY "Can read organizations_organizations if you have access to the " ON "public"."organizations_organizations" FOR SELECT TO "authenticated" USING ((EXISTS ( SELECT 1
- FROM "public"."sketches_profiles" "sp"
- WHERE (("sp"."sketch_id" = "organizations_organizations"."sketch_id") AND ("sp"."profile_id" = "auth"."uid"())))));
-
-
-
-CREATE POLICY "Can read phones if you have access to the sketch" ON "public"."phones" FOR SELECT TO "authenticated" USING ((EXISTS ( SELECT 1
- FROM "public"."sketches_profiles" "sp"
- WHERE (("sp"."sketch_id" = "phones"."sketch_id") AND ("sp"."profile_id" = "auth"."uid"())))));
-
-
-
-CREATE POLICY "Can read profiles in sketches if you have access to the investi" ON "public"."sketches_profiles" FOR SELECT TO "authenticated" USING (true);
-
-
-
-CREATE POLICY "Can read scans if you have access to the sketch" ON "public"."scans" FOR SELECT TO "authenticated" USING ((EXISTS ( SELECT 1
- FROM "public"."sketches_profiles" "sp"
- WHERE (("sp"."sketch_id" = "scans"."sketch_id") AND ("sp"."profile_id" = "auth"."uid"())))));
-
-
-
-CREATE POLICY "Can read social_accounts if you have access to the sketch" ON "public"."social_accounts" FOR SELECT TO "authenticated" USING ((EXISTS ( SELECT 1
- FROM "public"."sketches_profiles" "sp"
- WHERE (("sp"."sketch_id" = "social_accounts"."sketch_id") AND ("sp"."profile_id" = "auth"."uid"())))));
-
-
-
-CREATE POLICY "Can read vehicles if you have access to the sketch" ON "public"."vehicles" FOR SELECT TO "authenticated" USING ((EXISTS ( SELECT 1
- FROM "public"."sketches_profiles" "sp"
- WHERE (("sp"."sketch_id" = "vehicles"."sketch_id") AND ("sp"."profile_id" = "auth"."uid"())))));
-
-
-
-CREATE POLICY "Can read websites if you have access to the sketch" ON "public"."websites" FOR SELECT TO "authenticated" USING ((EXISTS ( SELECT 1
- FROM "public"."sketches_profiles" "sp"
- WHERE (("sp"."sketch_id" = "websites"."sketch_id") AND ("sp"."profile_id" = "auth"."uid"())))));
-
-
-
-CREATE POLICY "Can update emails if you have access to the sketch" ON "public"."emails" FOR UPDATE TO "authenticated" USING ((EXISTS ( SELECT 1
- FROM "public"."sketches_profiles" "sp"
- WHERE (("sp"."sketch_id" = "emails"."sketch_id") AND ("sp"."profile_id" = "auth"."uid"())))));
-
-
-
-CREATE POLICY "Can update individuals if you have access to the sketch" ON "public"."individuals" FOR UPDATE TO "authenticated" USING ((EXISTS ( SELECT 1
- FROM "public"."sketches_profiles" "sp"
- WHERE (("sp"."sketch_id" = "individuals"."sketch_id") AND ("sp"."profile_id" = "auth"."uid"())))));
-
-
-
-CREATE POLICY "Can update individuals_individuals if you have access to the sk" ON "public"."individuals_individuals" FOR UPDATE TO "authenticated" USING ((EXISTS ( SELECT 1
- FROM "public"."sketches_profiles" "sp"
- WHERE (("sp"."sketch_id" = "individuals_individuals"."sketch_id") AND ("sp"."profile_id" = "auth"."uid"())))));
-
-
-
-CREATE POLICY "Can update ip_addresses if you have access to the sketch" ON "public"."ip_addresses" FOR UPDATE TO "authenticated" USING ((EXISTS ( SELECT 1
- FROM "public"."sketches_profiles" "sp"
- WHERE (("sp"."sketch_id" = "ip_addresses"."sketch_id") AND ("sp"."profile_id" = "auth"."uid"())))));
-
-
-
-CREATE POLICY "Can update organizations if you have access to the sketch" ON "public"."organizations" FOR UPDATE TO "authenticated" USING ((EXISTS ( SELECT 1
- FROM "public"."sketches_profiles" "sp"
- WHERE (("sp"."sketch_id" = "organizations"."sketch_id") AND ("sp"."profile_id" = "auth"."uid"())))));
-
-
-
-CREATE POLICY "Can update organizations_individuals if you have access to the " ON "public"."organizations_individuals" FOR UPDATE TO "authenticated" USING ((EXISTS ( SELECT 1
- FROM "public"."sketches_profiles" "sp"
- WHERE (("sp"."sketch_id" = "organizations_individuals"."sketch_id") AND ("sp"."profile_id" = "auth"."uid"())))));
-
-
-
-CREATE POLICY "Can update organizations_organizations if you have access to th" ON "public"."organizations_organizations" FOR UPDATE TO "authenticated" USING ((EXISTS ( SELECT 1
- FROM "public"."sketches_profiles" "sp"
- WHERE (("sp"."sketch_id" = "organizations_organizations"."sketch_id") AND ("sp"."profile_id" = "auth"."uid"())))));
-
-
-
-CREATE POLICY "Can update phones if you have access to the sketch" ON "public"."phones" FOR UPDATE TO "authenticated" USING ((EXISTS ( SELECT 1
- FROM "public"."sketches_profiles" "sp"
- WHERE (("sp"."sketch_id" = "phones"."sketch_id") AND ("sp"."profile_id" = "auth"."uid"())))));
-
-
-
-CREATE POLICY "Can update scans if you have access to the sketch" ON "public"."scans" FOR UPDATE TO "authenticated" USING ((EXISTS ( SELECT 1
- FROM "public"."sketches_profiles" "sp"
- WHERE (("sp"."sketch_id" = "scans"."sketch_id") AND ("sp"."profile_id" = "auth"."uid"())))));
-
-
-
-CREATE POLICY "Can update social_accounts if you have access to the sketch" ON "public"."social_accounts" FOR UPDATE TO "authenticated" USING ((EXISTS ( SELECT 1
- FROM "public"."sketches_profiles" "sp"
- WHERE (("sp"."sketch_id" = "social_accounts"."sketch_id") AND ("sp"."profile_id" = "auth"."uid"())))));
-
-
-
-CREATE POLICY "Can update vehicles if you have access to the sketch" ON "public"."vehicles" FOR UPDATE TO "authenticated" USING ((EXISTS ( SELECT 1
- FROM "public"."sketches_profiles" "sp"
- WHERE (("sp"."sketch_id" = "vehicles"."sketch_id") AND ("sp"."profile_id" = "auth"."uid"())))));
-
-
-
-CREATE POLICY "Can update websites if you have access to the sketch" ON "public"."websites" FOR UPDATE TO "authenticated" USING ((EXISTS ( SELECT 1
- FROM "public"."sketches_profiles" "sp"
- WHERE (("sp"."sketch_id" = "websites"."sketch_id") AND ("sp"."profile_id" = "auth"."uid"())))));
-
-
-
-CREATE POLICY "Members can edit their own sketch profile" ON "public"."sketches_profiles" FOR UPDATE TO "authenticated" USING (("profile_id" = "auth"."uid"()));
-
-
-
-CREATE POLICY "Members can update own investigations" ON "public"."investigations" FOR UPDATE TO "authenticated" USING ((("auth"."uid"() = "owner_id") OR (EXISTS ( SELECT 1
- FROM "public"."investigations_profiles" "ip"
- WHERE (("ip"."investigation_id" = "investigations"."id") AND ("ip"."profile_id" = "auth"."uid"()))))));
-
-
-
-CREATE POLICY "Members of investigations_profiles can read investigation" ON "public"."investigations" FOR SELECT TO "authenticated" USING ((EXISTS ( SELECT 1
- FROM "public"."investigations_profiles" "ip"
- WHERE (("ip"."investigation_id" = "investigations"."id") AND ("ip"."profile_id" = "auth"."uid"())))));
-
-
-
-CREATE POLICY "Only investigation owner can add members" ON "public"."investigations_profiles" FOR INSERT TO "authenticated" WITH CHECK ((EXISTS ( SELECT 1
- FROM "public"."investigations"
- WHERE (("investigations"."id" = "investigations_profiles"."investigation_id") AND ("investigations"."owner_id" = "auth"."uid"())))));
-
-
-
-CREATE POLICY "Only investigation owner can delete profiles" ON "public"."investigations_profiles" FOR DELETE TO "authenticated" USING ((EXISTS ( SELECT 1
- FROM "public"."investigations"
- WHERE (("investigations"."id" = "investigations_profiles"."investigation_id") AND ("investigations"."owner_id" = "auth"."uid"())))));
-
-
-
-CREATE POLICY "Only investigation owner can update profiles" ON "public"."investigations_profiles" FOR UPDATE TO "authenticated" USING ((EXISTS ( SELECT 1
- FROM "public"."investigations"
- WHERE (("investigations"."id" = "investigations_profiles"."investigation_id") AND ("investigations"."owner_id" = "auth"."uid"())))));
-
-
-
-CREATE POLICY "Only owner can add profiles to sketches" ON "public"."sketches_profiles" FOR INSERT TO "authenticated" WITH CHECK ((EXISTS ( SELECT 1
- FROM "public"."sketches" "s"
- WHERE ("s"."owner_id" = "auth"."uid"()))));
-
-
-
-CREATE POLICY "Only owner can delete profiles from sketches" ON "public"."sketches_profiles" FOR DELETE TO "authenticated" USING ((EXISTS ( SELECT 1
- FROM "public"."sketches" "s"
- WHERE (("s"."id" = "sketches_profiles"."sketch_id") AND ("s"."owner_id" = "auth"."uid"())))));
-
-
-
-CREATE POLICY "Only owner or sketch creator can delete their sketch" ON "public"."sketches" FOR DELETE TO "authenticated" USING (((EXISTS ( SELECT 1
- FROM "public"."investigations" "i"
- WHERE (("i"."id" = "sketches"."investigation_id") AND ("i"."owner_id" = "auth"."uid"())))) OR ("owner_id" = "auth"."uid"())));
-
-
-
-CREATE POLICY "Owner can delete own investigations" ON "public"."investigations" FOR DELETE TO "authenticated" USING (("auth"."uid"() = "owner_id"));
-
-
-
-CREATE POLICY "Owner can read own investigations" ON "public"."investigations" FOR SELECT TO "authenticated" USING (("auth"."uid"() = "owner_id"));
-
-
-
-CREATE POLICY "Sketch members can update their sketch" ON "public"."sketches" FOR UPDATE TO "authenticated" USING (((EXISTS ( SELECT 1
- FROM "public"."sketches_profiles" "i"
- WHERE (("i"."sketch_id" = "sketches"."id") AND ("i"."profile_id" = "auth"."uid"())))) OR ("auth"."uid"() = "owner_id")));
-
-
-
-CREATE POLICY "Users can delete their own profiles" ON "public"."profiles" FOR DELETE TO "authenticated" USING (("auth"."uid"() = "id"));
-
-
-
-CREATE POLICY "Users can insert their own investigations" ON "public"."investigations" FOR INSERT TO "authenticated" WITH CHECK (("auth"."uid"() = "owner_id"));
-
-
-
-CREATE POLICY "Users can insert their own profiles" ON "public"."profiles" FOR INSERT TO "authenticated" WITH CHECK (("auth"."uid"() IS NOT NULL));
-
-
-
-CREATE POLICY "Users can update their own profiles" ON "public"."profiles" FOR UPDATE TO "authenticated" USING (("auth"."uid"() = "id")) WITH CHECK (("auth"."uid"() = "id"));
-
-
-
-CREATE POLICY "Users can view their own profiles" ON "public"."profiles" FOR SELECT TO "authenticated" USING (true);
-
-
-
-ALTER TABLE "public"."accounts_breaches" ENABLE ROW LEVEL SECURITY;
-
-
-ALTER TABLE "public"."breaches" ENABLE ROW LEVEL SECURITY;
-
-
-ALTER TABLE "public"."emails" ENABLE ROW LEVEL SECURITY;
-
-
-ALTER TABLE "public"."feedbacks" ENABLE ROW LEVEL SECURITY;
-
-
-ALTER TABLE "public"."groups" ENABLE ROW LEVEL SECURITY;
-
-
-ALTER TABLE "public"."individuals" ENABLE ROW LEVEL SECURITY;
-
-
-ALTER TABLE "public"."individuals_individuals" ENABLE ROW LEVEL SECURITY;
-
-
-ALTER TABLE "public"."investigations" ENABLE ROW LEVEL SECURITY;
-
-
-ALTER TABLE "public"."investigations_profiles" ENABLE ROW LEVEL SECURITY;
-
-
-ALTER TABLE "public"."ip_addresses" ENABLE ROW LEVEL SECURITY;
-
-
-ALTER TABLE "public"."organizations" ENABLE ROW LEVEL SECURITY;
-
-
-ALTER TABLE "public"."organizations_individuals" ENABLE ROW LEVEL SECURITY;
-
-
-ALTER TABLE "public"."organizations_organizations" ENABLE ROW LEVEL SECURITY;
-
-
-ALTER TABLE "public"."phones" ENABLE ROW LEVEL SECURITY;
-
-
-ALTER TABLE "public"."physical_addresses" ENABLE ROW LEVEL SECURITY;
-
-
-ALTER TABLE "public"."profiles" ENABLE ROW LEVEL SECURITY;
-
-
-ALTER TABLE "public"."sketches" ENABLE ROW LEVEL SECURITY;
-
-
-ALTER TABLE "public"."sketches_profiles" ENABLE ROW LEVEL SECURITY;
-
-
-ALTER TABLE "public"."social_accounts" ENABLE ROW LEVEL SECURITY;
-
-
-ALTER TABLE "public"."vehicles" ENABLE ROW LEVEL SECURITY;
-
-
-ALTER TABLE "public"."websites" ENABLE ROW LEVEL SECURITY;
-
-
-
-
-ALTER PUBLICATION "supabase_realtime" OWNER TO "postgres";
-
-
-
-
-
-
-ALTER PUBLICATION "supabase_realtime" ADD TABLE ONLY "public"."scans";
-
-
-
-ALTER PUBLICATION "supabase_realtime" ADD TABLE ONLY "public"."sketches";
-
-
-
-GRANT USAGE ON SCHEMA "public" TO "postgres";
-GRANT USAGE ON SCHEMA "public" TO "anon";
-GRANT USAGE ON SCHEMA "public" TO "authenticated";
-GRANT USAGE ON SCHEMA "public" TO "service_role";
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-GRANT ALL ON FUNCTION "public"."handle_new_investigation"() TO "anon";
-GRANT ALL ON FUNCTION "public"."handle_new_investigation"() TO "authenticated";
-GRANT ALL ON FUNCTION "public"."handle_new_investigation"() TO "service_role";
-
-
-
-GRANT ALL ON FUNCTION "public"."handle_new_project"() TO "anon";
-GRANT ALL ON FUNCTION "public"."handle_new_project"() TO "authenticated";
-GRANT ALL ON FUNCTION "public"."handle_new_project"() TO "service_role";
-
-
-
-GRANT ALL ON FUNCTION "public"."handle_new_sketch"() TO "anon";
-GRANT ALL ON FUNCTION "public"."handle_new_sketch"() TO "authenticated";
-GRANT ALL ON FUNCTION "public"."handle_new_sketch"() TO "service_role";
-
-
-
-GRANT ALL ON FUNCTION "public"."handle_new_user"() TO "anon";
-GRANT ALL ON FUNCTION "public"."handle_new_user"() TO "authenticated";
-GRANT ALL ON FUNCTION "public"."handle_new_user"() TO "service_role";
-
-
-
-GRANT ALL ON FUNCTION "public"."sync_investigation_profile_from_sketch"() TO "anon";
-GRANT ALL ON FUNCTION "public"."sync_investigation_profile_from_sketch"() TO "authenticated";
-GRANT ALL ON FUNCTION "public"."sync_investigation_profile_from_sketch"() TO "service_role";
-
-
-
-GRANT ALL ON FUNCTION "public"."update_investigation_last_updated"() TO "anon";
-GRANT ALL ON FUNCTION "public"."update_investigation_last_updated"() TO "authenticated";
-GRANT ALL ON FUNCTION "public"."update_investigation_last_updated"() TO "service_role";
-
-
-
-GRANT ALL ON FUNCTION "public"."update_last_updated_at"() TO "anon";
-GRANT ALL ON FUNCTION "public"."update_last_updated_at"() TO "authenticated";
-GRANT ALL ON FUNCTION "public"."update_last_updated_at"() TO "service_role";
-
-
-
-GRANT ALL ON FUNCTION "public"."update_sketch_last_updated"() TO "anon";
-GRANT ALL ON FUNCTION "public"."update_sketch_last_updated"() TO "authenticated";
-GRANT ALL ON FUNCTION "public"."update_sketch_last_updated"() TO "service_role";
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-GRANT ALL ON TABLE "public"."accounts_breaches" TO "anon";
-GRANT ALL ON TABLE "public"."accounts_breaches" TO "authenticated";
-GRANT ALL ON TABLE "public"."accounts_breaches" TO "service_role";
-
-
-
-GRANT ALL ON SEQUENCE "public"."accounts_breaches_id_seq" TO "anon";
-GRANT ALL ON SEQUENCE "public"."accounts_breaches_id_seq" TO "authenticated";
-GRANT ALL ON SEQUENCE "public"."accounts_breaches_id_seq" TO "service_role";
-
-
-
-GRANT ALL ON TABLE "public"."breaches" TO "anon";
-GRANT ALL ON TABLE "public"."breaches" TO "authenticated";
-GRANT ALL ON TABLE "public"."breaches" TO "service_role";
-
-
-
-GRANT ALL ON SEQUENCE "public"."breaches_id_seq" TO "anon";
-GRANT ALL ON SEQUENCE "public"."breaches_id_seq" TO "authenticated";
-GRANT ALL ON SEQUENCE "public"."breaches_id_seq" TO "service_role";
-
-
-
-GRANT ALL ON TABLE "public"."emails" TO "anon";
-GRANT ALL ON TABLE "public"."emails" TO "authenticated";
-GRANT ALL ON TABLE "public"."emails" TO "service_role";
-
-
-
-GRANT ALL ON TABLE "public"."feedbacks" TO "anon";
-GRANT ALL ON TABLE "public"."feedbacks" TO "authenticated";
-GRANT ALL ON TABLE "public"."feedbacks" TO "service_role";
-
-
-
-GRANT ALL ON SEQUENCE "public"."feedbacks_id_seq" TO "anon";
-GRANT ALL ON SEQUENCE "public"."feedbacks_id_seq" TO "authenticated";
-GRANT ALL ON SEQUENCE "public"."feedbacks_id_seq" TO "service_role";
-
-
-
-GRANT ALL ON TABLE "public"."groups" TO "anon";
-GRANT ALL ON TABLE "public"."groups" TO "authenticated";
-GRANT ALL ON TABLE "public"."groups" TO "service_role";
-
-
-
-GRANT ALL ON TABLE "public"."individuals" TO "anon";
-GRANT ALL ON TABLE "public"."individuals" TO "authenticated";
-GRANT ALL ON TABLE "public"."individuals" TO "service_role";
-
-
-
-GRANT ALL ON TABLE "public"."individuals_individuals" TO "anon";
-GRANT ALL ON TABLE "public"."individuals_individuals" TO "authenticated";
-GRANT ALL ON TABLE "public"."individuals_individuals" TO "service_role";
-
-
-
-GRANT ALL ON TABLE "public"."investigations" TO "anon";
-GRANT ALL ON TABLE "public"."investigations" TO "authenticated";
-GRANT ALL ON TABLE "public"."investigations" TO "service_role";
-
-
-
-GRANT ALL ON TABLE "public"."investigations_profiles" TO "anon";
-GRANT ALL ON TABLE "public"."investigations_profiles" TO "authenticated";
-GRANT ALL ON TABLE "public"."investigations_profiles" TO "service_role";
-
-
-
-GRANT ALL ON TABLE "public"."sketches_profiles" TO "anon";
-GRANT ALL ON TABLE "public"."sketches_profiles" TO "authenticated";
-GRANT ALL ON TABLE "public"."sketches_profiles" TO "service_role";
-
-
-
-GRANT ALL ON SEQUENCE "public"."investigations_profiles_id_seq" TO "anon";
-GRANT ALL ON SEQUENCE "public"."investigations_profiles_id_seq" TO "authenticated";
-GRANT ALL ON SEQUENCE "public"."investigations_profiles_id_seq" TO "service_role";
-
-
-
-GRANT ALL ON TABLE "public"."ip_addresses" TO "anon";
-GRANT ALL ON TABLE "public"."ip_addresses" TO "authenticated";
-GRANT ALL ON TABLE "public"."ip_addresses" TO "service_role";
-
-
-
-GRANT ALL ON TABLE "public"."organizations" TO "anon";
-GRANT ALL ON TABLE "public"."organizations" TO "authenticated";
-GRANT ALL ON TABLE "public"."organizations" TO "service_role";
-
-
-
-GRANT ALL ON TABLE "public"."organizations_individuals" TO "anon";
-GRANT ALL ON TABLE "public"."organizations_individuals" TO "authenticated";
-GRANT ALL ON TABLE "public"."organizations_individuals" TO "service_role";
-
-
-
-GRANT ALL ON TABLE "public"."organizations_organizations" TO "anon";
-GRANT ALL ON TABLE "public"."organizations_organizations" TO "authenticated";
-GRANT ALL ON TABLE "public"."organizations_organizations" TO "service_role";
-
-
-
-GRANT ALL ON TABLE "public"."organization_graph" TO "anon";
-GRANT ALL ON TABLE "public"."organization_graph" TO "authenticated";
-GRANT ALL ON TABLE "public"."organization_graph" TO "service_role";
-
-
-
-GRANT ALL ON SEQUENCE "public"."organizations_organizations_id_seq" TO "anon";
-GRANT ALL ON SEQUENCE "public"."organizations_organizations_id_seq" TO "authenticated";
-GRANT ALL ON SEQUENCE "public"."organizations_organizations_id_seq" TO "service_role";
-
-
-
-GRANT ALL ON TABLE "public"."phones" TO "anon";
-GRANT ALL ON TABLE "public"."phones" TO "authenticated";
-GRANT ALL ON TABLE "public"."phones" TO "service_role";
-
-
-
-GRANT ALL ON TABLE "public"."physical_addresses" TO "anon";
-GRANT ALL ON TABLE "public"."physical_addresses" TO "authenticated";
-GRANT ALL ON TABLE "public"."physical_addresses" TO "service_role";
-
-
-
-GRANT ALL ON TABLE "public"."profiles" TO "anon";
-GRANT ALL ON TABLE "public"."profiles" TO "authenticated";
-GRANT ALL ON TABLE "public"."profiles" TO "service_role";
-
-
-
-GRANT ALL ON SEQUENCE "public"."projects_profiles_id_seq" TO "anon";
-GRANT ALL ON SEQUENCE "public"."projects_profiles_id_seq" TO "authenticated";
-GRANT ALL ON SEQUENCE "public"."projects_profiles_id_seq" TO "service_role";
-
-
-
-GRANT ALL ON TABLE "public"."scans" TO "anon";
-GRANT ALL ON TABLE "public"."scans" TO "authenticated";
-GRANT ALL ON TABLE "public"."scans" TO "service_role";
-
-
-
-GRANT ALL ON TABLE "public"."sketch_graph" TO "anon";
-GRANT ALL ON TABLE "public"."sketch_graph" TO "authenticated";
-GRANT ALL ON TABLE "public"."sketch_graph" TO "service_role";
-
-
-
-GRANT ALL ON TABLE "public"."social_accounts" TO "anon";
-GRANT ALL ON TABLE "public"."social_accounts" TO "authenticated";
-GRANT ALL ON TABLE "public"."social_accounts" TO "service_role";
-
-
-
-GRANT ALL ON TABLE "public"."vehicles" TO "anon";
-GRANT ALL ON TABLE "public"."vehicles" TO "authenticated";
-GRANT ALL ON TABLE "public"."vehicles" TO "service_role";
-
-
-
-GRANT ALL ON TABLE "public"."websites" TO "anon";
-GRANT ALL ON TABLE "public"."websites" TO "authenticated";
-GRANT ALL ON TABLE "public"."websites" TO "service_role";
-
-
-
-GRANT ALL ON TABLE "public"."sketch_table" TO "anon";
-GRANT ALL ON TABLE "public"."sketch_table" TO "authenticated";
-GRANT ALL ON TABLE "public"."sketch_table" TO "service_role";
-
-
-
-GRANT ALL ON TABLE "public"."sketches" TO "anon";
-GRANT ALL ON TABLE "public"."sketches" TO "authenticated";
-GRANT ALL ON TABLE "public"."sketches" TO "service_role";
-
-
-
-ALTER DEFAULT PRIVILEGES FOR ROLE "postgres" IN SCHEMA "public" GRANT ALL ON SEQUENCES TO "postgres";
-ALTER DEFAULT PRIVILEGES FOR ROLE "postgres" IN SCHEMA "public" GRANT ALL ON SEQUENCES TO "anon";
-ALTER DEFAULT PRIVILEGES FOR ROLE "postgres" IN SCHEMA "public" GRANT ALL ON SEQUENCES TO "authenticated";
-ALTER DEFAULT PRIVILEGES FOR ROLE "postgres" IN SCHEMA "public" GRANT ALL ON SEQUENCES TO "service_role";
-
-
-
-
-
-
-ALTER DEFAULT PRIVILEGES FOR ROLE "postgres" IN SCHEMA "public" GRANT ALL ON FUNCTIONS TO "postgres";
-ALTER DEFAULT PRIVILEGES FOR ROLE "postgres" IN SCHEMA "public" GRANT ALL ON FUNCTIONS TO "anon";
-ALTER DEFAULT PRIVILEGES FOR ROLE "postgres" IN SCHEMA "public" GRANT ALL ON FUNCTIONS TO "authenticated";
-ALTER DEFAULT PRIVILEGES FOR ROLE "postgres" IN SCHEMA "public" GRANT ALL ON FUNCTIONS TO "service_role";
-
-
-
-
-
-
-ALTER DEFAULT PRIVILEGES FOR ROLE "postgres" IN SCHEMA "public" GRANT ALL ON TABLES TO "postgres";
-ALTER DEFAULT PRIVILEGES FOR ROLE "postgres" IN SCHEMA "public" GRANT ALL ON TABLES TO "anon";
-ALTER DEFAULT PRIVILEGES FOR ROLE "postgres" IN SCHEMA "public" GRANT ALL ON TABLES TO "authenticated";
-ALTER DEFAULT PRIVILEGES FOR ROLE "postgres" IN SCHEMA "public" GRANT ALL ON TABLES TO "service_role";
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-RESET ALL;
diff --git a/backend/volumes/api/kong.yml b/backend/volumes/api/kong.yml
deleted file mode 100644
index 7abf4253..00000000
--- a/backend/volumes/api/kong.yml
+++ /dev/null
@@ -1,241 +0,0 @@
-_format_version: '2.1'
-_transform: true
-
-###
-### Consumers / Users
-###
-consumers:
- - username: DASHBOARD
- - username: anon
- keyauth_credentials:
- - key: $SUPABASE_ANON_KEY
- - username: service_role
- keyauth_credentials:
- - key: $SUPABASE_SERVICE_KEY
-
-###
-### Access Control List
-###
-acls:
- - consumer: anon
- group: anon
- - consumer: service_role
- group: admin
-
-###
-### Dashboard credentials
-###
-basicauth_credentials:
- - consumer: DASHBOARD
- username: $DASHBOARD_USERNAME
- password: $DASHBOARD_PASSWORD
-
-###
-### API Routes
-###
-services:
- ## Open Auth routes
- - name: auth-v1-open
- url: http://auth:9999/verify
- routes:
- - name: auth-v1-open
- strip_path: true
- paths:
- - /auth/v1/verify
- plugins:
- - name: cors
- - name: auth-v1-open-callback
- url: http://auth:9999/callback
- routes:
- - name: auth-v1-open-callback
- strip_path: true
- paths:
- - /auth/v1/callback
- plugins:
- - name: cors
- - name: auth-v1-open-authorize
- url: http://auth:9999/authorize
- routes:
- - name: auth-v1-open-authorize
- strip_path: true
- paths:
- - /auth/v1/authorize
- plugins:
- - name: cors
-
- ## Secure Auth routes
- - name: auth-v1
- _comment: 'GoTrue: /auth/v1/* -> http://auth:9999/*'
- url: http://auth:9999/
- routes:
- - name: auth-v1-all
- strip_path: true
- paths:
- - /auth/v1/
- plugins:
- - name: cors
- - name: key-auth
- config:
- hide_credentials: false
- - name: acl
- config:
- hide_groups_header: true
- allow:
- - admin
- - anon
-
- ## Secure REST routes
- - name: rest-v1
- _comment: 'PostgREST: /rest/v1/* -> http://rest:3000/*'
- url: http://rest:3000/
- routes:
- - name: rest-v1-all
- strip_path: true
- paths:
- - /rest/v1/
- plugins:
- - name: cors
- - name: key-auth
- config:
- hide_credentials: true
- - name: acl
- config:
- hide_groups_header: true
- allow:
- - admin
- - anon
-
- ## Secure GraphQL routes
- - name: graphql-v1
- _comment: 'PostgREST: /graphql/v1/* -> http://rest:3000/rpc/graphql'
- url: http://rest:3000/rpc/graphql
- routes:
- - name: graphql-v1-all
- strip_path: true
- paths:
- - /graphql/v1
- plugins:
- - name: cors
- - name: key-auth
- config:
- hide_credentials: true
- - name: request-transformer
- config:
- add:
- headers:
- - Content-Profile:graphql_public
- - name: acl
- config:
- hide_groups_header: true
- allow:
- - admin
- - anon
-
- ## Secure Realtime routes
- - name: realtime-v1-ws
- _comment: 'Realtime: /realtime/v1/* -> ws://realtime:4000/socket/*'
- url: http://realtime-dev.supabase-realtime:4000/socket
- protocol: ws
- routes:
- - name: realtime-v1-ws
- strip_path: true
- paths:
- - /realtime/v1/
- plugins:
- - name: cors
- - name: key-auth
- config:
- hide_credentials: false
- - name: acl
- config:
- hide_groups_header: true
- allow:
- - admin
- - anon
- - name: realtime-v1-rest
- _comment: 'Realtime: /realtime/v1/* -> ws://realtime:4000/socket/*'
- url: http://realtime-dev.supabase-realtime:4000/api
- protocol: http
- routes:
- - name: realtime-v1-rest
- strip_path: true
- paths:
- - /realtime/v1/api
- plugins:
- - name: cors
- - name: key-auth
- config:
- hide_credentials: false
- - name: acl
- config:
- hide_groups_header: true
- allow:
- - admin
- - anon
- ## Storage routes: the storage server manages its own auth
- - name: storage-v1
- _comment: 'Storage: /storage/v1/* -> http://storage:5000/*'
- url: http://storage:5000/
- routes:
- - name: storage-v1-all
- strip_path: true
- paths:
- - /storage/v1/
- plugins:
- - name: cors
-
- ## Edge Functions routes
- - name: functions-v1
- _comment: 'Edge Functions: /functions/v1/* -> http://functions:9000/*'
- url: http://functions:9000/
- routes:
- - name: functions-v1-all
- strip_path: true
- paths:
- - /functions/v1/
- plugins:
- - name: cors
-
- ## Analytics routes
- - name: analytics-v1
- _comment: 'Analytics: /analytics/v1/* -> http://logflare:4000/*'
- url: http://analytics:4000/
- routes:
- - name: analytics-v1-all
- strip_path: true
- paths:
- - /analytics/v1/
-
- ## Secure Database routes
- - name: meta
- _comment: 'pg-meta: /pg/* -> http://pg-meta:8080/*'
- url: http://meta:8080/
- routes:
- - name: meta-all
- strip_path: true
- paths:
- - /pg/
- plugins:
- - name: key-auth
- config:
- hide_credentials: false
- - name: acl
- config:
- hide_groups_header: true
- allow:
- - admin
-
- ## Protected Dashboard - catch all remaining routes
- - name: dashboard
- _comment: 'Studio: /* -> http://studio:3000/*'
- url: http://studio:3000/
- routes:
- - name: dashboard-all
- strip_path: true
- paths:
- - /
- plugins:
- - name: cors
- - name: basic-auth
- config:
- hide_credentials: true
diff --git a/backend/volumes/db/_supabase.sql b/backend/volumes/db/_supabase.sql
deleted file mode 100644
index 6236ae1b..00000000
--- a/backend/volumes/db/_supabase.sql
+++ /dev/null
@@ -1,3 +0,0 @@
-\set pguser `echo "$POSTGRES_USER"`
-
-CREATE DATABASE _supabase WITH OWNER :pguser;
diff --git a/backend/volumes/db/jwt.sql b/backend/volumes/db/jwt.sql
deleted file mode 100644
index cfd3b160..00000000
--- a/backend/volumes/db/jwt.sql
+++ /dev/null
@@ -1,5 +0,0 @@
-\set jwt_secret `echo "$JWT_SECRET"`
-\set jwt_exp `echo "$JWT_EXP"`
-
-ALTER DATABASE postgres SET "app.settings.jwt_secret" TO :'jwt_secret';
-ALTER DATABASE postgres SET "app.settings.jwt_exp" TO :'jwt_exp';
diff --git a/backend/volumes/db/logs.sql b/backend/volumes/db/logs.sql
deleted file mode 100644
index 255c0f40..00000000
--- a/backend/volumes/db/logs.sql
+++ /dev/null
@@ -1,6 +0,0 @@
-\set pguser `echo "$POSTGRES_USER"`
-
-\c _supabase
-create schema if not exists _analytics;
-alter schema _analytics owner to :pguser;
-\c postgres
diff --git a/backend/volumes/db/pooler.sql b/backend/volumes/db/pooler.sql
deleted file mode 100644
index 162c5b96..00000000
--- a/backend/volumes/db/pooler.sql
+++ /dev/null
@@ -1,6 +0,0 @@
-\set pguser `echo "$POSTGRES_USER"`
-
-\c _supabase
-create schema if not exists _supavisor;
-alter schema _supavisor owner to :pguser;
-\c postgres
diff --git a/backend/volumes/db/realtime.sql b/backend/volumes/db/realtime.sql
deleted file mode 100644
index 4d4b9ffb..00000000
--- a/backend/volumes/db/realtime.sql
+++ /dev/null
@@ -1,4 +0,0 @@
-\set pguser `echo "$POSTGRES_USER"`
-
-create schema if not exists _realtime;
-alter schema _realtime owner to :pguser;
diff --git a/backend/volumes/db/roles.sql b/backend/volumes/db/roles.sql
deleted file mode 100644
index 8f7161a6..00000000
--- a/backend/volumes/db/roles.sql
+++ /dev/null
@@ -1,8 +0,0 @@
--- NOTE: change to your own passwords for production environments
-\set pgpass `echo "$POSTGRES_PASSWORD"`
-
-ALTER USER authenticator WITH PASSWORD :'pgpass';
-ALTER USER pgbouncer WITH PASSWORD :'pgpass';
-ALTER USER supabase_auth_admin WITH PASSWORD :'pgpass';
-ALTER USER supabase_functions_admin WITH PASSWORD :'pgpass';
-ALTER USER supabase_storage_admin WITH PASSWORD :'pgpass';
diff --git a/backend/volumes/db/webhooks.sql b/backend/volumes/db/webhooks.sql
deleted file mode 100644
index 5837b861..00000000
--- a/backend/volumes/db/webhooks.sql
+++ /dev/null
@@ -1,208 +0,0 @@
-BEGIN;
- -- Create pg_net extension
- CREATE EXTENSION IF NOT EXISTS pg_net SCHEMA extensions;
- -- Create supabase_functions schema
- CREATE SCHEMA supabase_functions AUTHORIZATION supabase_admin;
- GRANT USAGE ON SCHEMA supabase_functions TO postgres, anon, authenticated, service_role;
- ALTER DEFAULT PRIVILEGES IN SCHEMA supabase_functions GRANT ALL ON TABLES TO postgres, anon, authenticated, service_role;
- ALTER DEFAULT PRIVILEGES IN SCHEMA supabase_functions GRANT ALL ON FUNCTIONS TO postgres, anon, authenticated, service_role;
- ALTER DEFAULT PRIVILEGES IN SCHEMA supabase_functions GRANT ALL ON SEQUENCES TO postgres, anon, authenticated, service_role;
- -- supabase_functions.migrations definition
- CREATE TABLE supabase_functions.migrations (
- version text PRIMARY KEY,
- inserted_at timestamptz NOT NULL DEFAULT NOW()
- );
- -- Initial supabase_functions migration
- INSERT INTO supabase_functions.migrations (version) VALUES ('initial');
- -- supabase_functions.hooks definition
- CREATE TABLE supabase_functions.hooks (
- id bigserial PRIMARY KEY,
- hook_table_id integer NOT NULL,
- hook_name text NOT NULL,
- created_at timestamptz NOT NULL DEFAULT NOW(),
- request_id bigint
- );
- CREATE INDEX supabase_functions_hooks_request_id_idx ON supabase_functions.hooks USING btree (request_id);
- CREATE INDEX supabase_functions_hooks_h_table_id_h_name_idx ON supabase_functions.hooks USING btree (hook_table_id, hook_name);
- COMMENT ON TABLE supabase_functions.hooks IS 'Supabase Functions Hooks: Audit trail for triggered hooks.';
- CREATE FUNCTION supabase_functions.http_request()
- RETURNS trigger
- LANGUAGE plpgsql
- AS $function$
- DECLARE
- request_id bigint;
- payload jsonb;
- url text := TG_ARGV[0]::text;
- method text := TG_ARGV[1]::text;
- headers jsonb DEFAULT '{}'::jsonb;
- params jsonb DEFAULT '{}'::jsonb;
- timeout_ms integer DEFAULT 1000;
- BEGIN
- IF url IS NULL OR url = 'null' THEN
- RAISE EXCEPTION 'url argument is missing';
- END IF;
-
- IF method IS NULL OR method = 'null' THEN
- RAISE EXCEPTION 'method argument is missing';
- END IF;
-
- IF TG_ARGV[2] IS NULL OR TG_ARGV[2] = 'null' THEN
- headers = '{"Content-Type": "application/json"}'::jsonb;
- ELSE
- headers = TG_ARGV[2]::jsonb;
- END IF;
-
- IF TG_ARGV[3] IS NULL OR TG_ARGV[3] = 'null' THEN
- params = '{}'::jsonb;
- ELSE
- params = TG_ARGV[3]::jsonb;
- END IF;
-
- IF TG_ARGV[4] IS NULL OR TG_ARGV[4] = 'null' THEN
- timeout_ms = 1000;
- ELSE
- timeout_ms = TG_ARGV[4]::integer;
- END IF;
-
- CASE
- WHEN method = 'GET' THEN
- SELECT http_get INTO request_id FROM net.http_get(
- url,
- params,
- headers,
- timeout_ms
- );
- WHEN method = 'POST' THEN
- payload = jsonb_build_object(
- 'old_record', OLD,
- 'record', NEW,
- 'type', TG_OP,
- 'table', TG_TABLE_NAME,
- 'schema', TG_TABLE_SCHEMA
- );
-
- SELECT http_post INTO request_id FROM net.http_post(
- url,
- payload,
- params,
- headers,
- timeout_ms
- );
- ELSE
- RAISE EXCEPTION 'method argument % is invalid', method;
- END CASE;
-
- INSERT INTO supabase_functions.hooks
- (hook_table_id, hook_name, request_id)
- VALUES
- (TG_RELID, TG_NAME, request_id);
-
- RETURN NEW;
- END
- $function$;
- -- Supabase super admin
- DO
- $$
- BEGIN
- IF NOT EXISTS (
- SELECT 1
- FROM pg_roles
- WHERE rolname = 'supabase_functions_admin'
- )
- THEN
- CREATE USER supabase_functions_admin NOINHERIT CREATEROLE LOGIN NOREPLICATION;
- END IF;
- END
- $$;
- GRANT ALL PRIVILEGES ON SCHEMA supabase_functions TO supabase_functions_admin;
- GRANT ALL PRIVILEGES ON ALL TABLES IN SCHEMA supabase_functions TO supabase_functions_admin;
- GRANT ALL PRIVILEGES ON ALL SEQUENCES IN SCHEMA supabase_functions TO supabase_functions_admin;
- ALTER USER supabase_functions_admin SET search_path = "supabase_functions";
- ALTER table "supabase_functions".migrations OWNER TO supabase_functions_admin;
- ALTER table "supabase_functions".hooks OWNER TO supabase_functions_admin;
- ALTER function "supabase_functions".http_request() OWNER TO supabase_functions_admin;
- GRANT supabase_functions_admin TO postgres;
- -- Remove unused supabase_pg_net_admin role
- DO
- $$
- BEGIN
- IF EXISTS (
- SELECT 1
- FROM pg_roles
- WHERE rolname = 'supabase_pg_net_admin'
- )
- THEN
- REASSIGN OWNED BY supabase_pg_net_admin TO supabase_admin;
- DROP OWNED BY supabase_pg_net_admin;
- DROP ROLE supabase_pg_net_admin;
- END IF;
- END
- $$;
- -- pg_net grants when extension is already enabled
- DO
- $$
- BEGIN
- IF EXISTS (
- SELECT 1
- FROM pg_extension
- WHERE extname = 'pg_net'
- )
- THEN
- GRANT USAGE ON SCHEMA net TO supabase_functions_admin, postgres, anon, authenticated, service_role;
- ALTER function net.http_get(url text, params jsonb, headers jsonb, timeout_milliseconds integer) SECURITY DEFINER;
- ALTER function net.http_post(url text, body jsonb, params jsonb, headers jsonb, timeout_milliseconds integer) SECURITY DEFINER;
- ALTER function net.http_get(url text, params jsonb, headers jsonb, timeout_milliseconds integer) SET search_path = net;
- ALTER function net.http_post(url text, body jsonb, params jsonb, headers jsonb, timeout_milliseconds integer) SET search_path = net;
- REVOKE ALL ON FUNCTION net.http_get(url text, params jsonb, headers jsonb, timeout_milliseconds integer) FROM PUBLIC;
- REVOKE ALL ON FUNCTION net.http_post(url text, body jsonb, params jsonb, headers jsonb, timeout_milliseconds integer) FROM PUBLIC;
- GRANT EXECUTE ON FUNCTION net.http_get(url text, params jsonb, headers jsonb, timeout_milliseconds integer) TO supabase_functions_admin, postgres, anon, authenticated, service_role;
- GRANT EXECUTE ON FUNCTION net.http_post(url text, body jsonb, params jsonb, headers jsonb, timeout_milliseconds integer) TO supabase_functions_admin, postgres, anon, authenticated, service_role;
- END IF;
- END
- $$;
- -- Event trigger for pg_net
- CREATE OR REPLACE FUNCTION extensions.grant_pg_net_access()
- RETURNS event_trigger
- LANGUAGE plpgsql
- AS $$
- BEGIN
- IF EXISTS (
- SELECT 1
- FROM pg_event_trigger_ddl_commands() AS ev
- JOIN pg_extension AS ext
- ON ev.objid = ext.oid
- WHERE ext.extname = 'pg_net'
- )
- THEN
- GRANT USAGE ON SCHEMA net TO supabase_functions_admin, postgres, anon, authenticated, service_role;
- ALTER function net.http_get(url text, params jsonb, headers jsonb, timeout_milliseconds integer) SECURITY DEFINER;
- ALTER function net.http_post(url text, body jsonb, params jsonb, headers jsonb, timeout_milliseconds integer) SECURITY DEFINER;
- ALTER function net.http_get(url text, params jsonb, headers jsonb, timeout_milliseconds integer) SET search_path = net;
- ALTER function net.http_post(url text, body jsonb, params jsonb, headers jsonb, timeout_milliseconds integer) SET search_path = net;
- REVOKE ALL ON FUNCTION net.http_get(url text, params jsonb, headers jsonb, timeout_milliseconds integer) FROM PUBLIC;
- REVOKE ALL ON FUNCTION net.http_post(url text, body jsonb, params jsonb, headers jsonb, timeout_milliseconds integer) FROM PUBLIC;
- GRANT EXECUTE ON FUNCTION net.http_get(url text, params jsonb, headers jsonb, timeout_milliseconds integer) TO supabase_functions_admin, postgres, anon, authenticated, service_role;
- GRANT EXECUTE ON FUNCTION net.http_post(url text, body jsonb, params jsonb, headers jsonb, timeout_milliseconds integer) TO supabase_functions_admin, postgres, anon, authenticated, service_role;
- END IF;
- END;
- $$;
- COMMENT ON FUNCTION extensions.grant_pg_net_access IS 'Grants access to pg_net';
- DO
- $$
- BEGIN
- IF NOT EXISTS (
- SELECT 1
- FROM pg_event_trigger
- WHERE evtname = 'issue_pg_net_access'
- ) THEN
- CREATE EVENT TRIGGER issue_pg_net_access ON ddl_command_end WHEN TAG IN ('CREATE EXTENSION')
- EXECUTE PROCEDURE extensions.grant_pg_net_access();
- END IF;
- END
- $$;
- INSERT INTO supabase_functions.migrations (version) VALUES ('20210809183423_update_grants');
- ALTER function supabase_functions.http_request() SECURITY DEFINER;
- ALTER function supabase_functions.http_request() SET search_path = supabase_functions;
- REVOKE ALL ON FUNCTION supabase_functions.http_request() FROM PUBLIC;
- GRANT EXECUTE ON FUNCTION supabase_functions.http_request() TO postgres, anon, authenticated, service_role;
-COMMIT;
diff --git a/backend/volumes/functions/hello/index.ts b/backend/volumes/functions/hello/index.ts
deleted file mode 100644
index f1e20b90..00000000
--- a/backend/volumes/functions/hello/index.ts
+++ /dev/null
@@ -1,16 +0,0 @@
-// Follow this setup guide to integrate the Deno language server with your editor:
-// https://deno.land/manual/getting_started/setup_your_environment
-// This enables autocomplete, go to definition, etc.
-
-import { serve } from "https://deno.land/[email protected]/http/server.ts"
-
-serve(async () => {
- return new Response(
- `"Hello from Edge Functions!"`,
- { headers: { "Content-Type": "application/json" } },
- )
-})
-
-// To invoke:
-// curl 'http://localhost:<KONG_HTTP_PORT>/functions/v1/hello' \
-// --header 'Authorization: Bearer <anon/service_role API key>'
diff --git a/backend/volumes/functions/main/index.ts b/backend/volumes/functions/main/index.ts
deleted file mode 100644
index a094010b..00000000
--- a/backend/volumes/functions/main/index.ts
+++ /dev/null
@@ -1,94 +0,0 @@
-import { serve } from 'https://deno.land/[email protected]/http/server.ts'
-import * as jose from 'https://deno.land/x/[email protected]/index.ts'
-
-console.log('main function started')
-
-const JWT_SECRET = Deno.env.get('JWT_SECRET')
-const VERIFY_JWT = Deno.env.get('VERIFY_JWT') === 'true'
-
-function getAuthToken(req: Request) {
- const authHeader = req.headers.get('authorization')
- if (!authHeader) {
- throw new Error('Missing authorization header')
- }
- const [bearer, token] = authHeader.split(' ')
- if (bearer !== 'Bearer') {
- throw new Error(`Auth header is not 'Bearer {token}'`)
- }
- return token
-}
-
-async function verifyJWT(jwt: string): Promise<boolean> {
- const encoder = new TextEncoder()
- const secretKey = encoder.encode(JWT_SECRET)
- try {
- await jose.jwtVerify(jwt, secretKey)
- } catch (err) {
- console.error(err)
- return false
- }
- return true
-}
-
-serve(async (req: Request) => {
- if (req.method !== 'OPTIONS' && VERIFY_JWT) {
- try {
- const token = getAuthToken(req)
- const isValidJWT = await verifyJWT(token)
-
- if (!isValidJWT) {
- return new Response(JSON.stringify({ msg: 'Invalid JWT' }), {
- status: 401,
- headers: { 'Content-Type': 'application/json' },
- })
- }
- } catch (e) {
- console.error(e)
- return new Response(JSON.stringify({ msg: e.toString() }), {
- status: 401,
- headers: { 'Content-Type': 'application/json' },
- })
- }
- }
-
- const url = new URL(req.url)
- const { pathname } = url
- const path_parts = pathname.split('/')
- const service_name = path_parts[1]
-
- if (!service_name || service_name === '') {
- const error = { msg: 'missing function name in request' }
- return new Response(JSON.stringify(error), {
- status: 400,
- headers: { 'Content-Type': 'application/json' },
- })
- }
-
- const servicePath = `/home/deno/functions/${service_name}`
- console.error(`serving the request with ${servicePath}`)
-
- const memoryLimitMb = 150
- const workerTimeoutMs = 1 * 60 * 1000
- const noModuleCache = false
- const importMapPath = null
- const envVarsObj = Deno.env.toObject()
- const envVars = Object.keys(envVarsObj).map((k) => [k, envVarsObj[k]])
-
- try {
- const worker = await EdgeRuntime.userWorkers.create({
- servicePath,
- memoryLimitMb,
- workerTimeoutMs,
- noModuleCache,
- importMapPath,
- envVars,
- })
- return await worker.fetch(req)
- } catch (e) {
- const error = { msg: e.toString() }
- return new Response(JSON.stringify(error), {
- status: 500,
- headers: { 'Content-Type': 'application/json' },
- })
- }
-})
diff --git a/backend/volumes/logs/vector.yml b/backend/volumes/logs/vector.yml
deleted file mode 100644
index cce46df4..00000000
--- a/backend/volumes/logs/vector.yml
+++ /dev/null
@@ -1,232 +0,0 @@
-api:
- enabled: true
- address: 0.0.0.0:9001
-
-sources:
- docker_host:
- type: docker_logs
- exclude_containers:
- - supabase-vector
-
-transforms:
- project_logs:
- type: remap
- inputs:
- - docker_host
- source: |-
- .project = "default"
- .event_message = del(.message)
- .appname = del(.container_name)
- del(.container_created_at)
- del(.container_id)
- del(.source_type)
- del(.stream)
- del(.label)
- del(.image)
- del(.host)
- del(.stream)
- router:
- type: route
- inputs:
- - project_logs
- route:
- kong: '.appname == "supabase-kong"'
- auth: '.appname == "supabase-auth"'
- rest: '.appname == "supabase-rest"'
- realtime: '.appname == "supabase-realtime"'
- storage: '.appname == "supabase-storage"'
- functions: '.appname == "supabase-functions"'
- db: '.appname == "supabase-db"'
- # Ignores non nginx errors since they are related with kong booting up
- kong_logs:
- type: remap
- inputs:
- - router.kong
- source: |-
- req, err = parse_nginx_log(.event_message, "combined")
- if err == null {
- .timestamp = req.timestamp
- .metadata.request.headers.referer = req.referer
- .metadata.request.headers.user_agent = req.agent
- .metadata.request.headers.cf_connecting_ip = req.client
- .metadata.request.method = req.method
- .metadata.request.path = req.path
- .metadata.request.protocol = req.protocol
- .metadata.response.status_code = req.status
- }
- if err != null {
- abort
- }
- # Ignores non nginx errors since they are related with kong booting up
- kong_err:
- type: remap
- inputs:
- - router.kong
- source: |-
- .metadata.request.method = "GET"
- .metadata.response.status_code = 200
- parsed, err = parse_nginx_log(.event_message, "error")
- if err == null {
- .timestamp = parsed.timestamp
- .severity = parsed.severity
- .metadata.request.host = parsed.host
- .metadata.request.headers.cf_connecting_ip = parsed.client
- url, err = split(parsed.request, " ")
- if err == null {
- .metadata.request.method = url[0]
- .metadata.request.path = url[1]
- .metadata.request.protocol = url[2]
- }
- }
- if err != null {
- abort
- }
- # Gotrue logs are structured json strings which frontend parses directly. But we keep metadata for consistency.
- auth_logs:
- type: remap
- inputs:
- - router.auth
- source: |-
- parsed, err = parse_json(.event_message)
- if err == null {
- .metadata.timestamp = parsed.time
- .metadata = merge!(.metadata, parsed)
- }
- # PostgREST logs are structured so we separate timestamp from message using regex
- rest_logs:
- type: remap
- inputs:
- - router.rest
- source: |-
- parsed, err = parse_regex(.event_message, r'^(?P<time>.*): (?P<msg>.*)$')
- if err == null {
- .event_message = parsed.msg
- .timestamp = to_timestamp!(parsed.time)
- .metadata.host = .project
- }
- # Realtime logs are structured so we parse the severity level using regex (ignore time because it has no date)
- realtime_logs:
- type: remap
- inputs:
- - router.realtime
- source: |-
- .metadata.project = del(.project)
- .metadata.external_id = .metadata.project
- parsed, err = parse_regex(.event_message, r'^(?P<time>\d+:\d+:\d+\.\d+) \[(?P<level>\w+)\] (?P<msg>.*)$')
- if err == null {
- .event_message = parsed.msg
- .metadata.level = parsed.level
- }
- # Storage logs may contain json objects so we parse them for completeness
- storage_logs:
- type: remap
- inputs:
- - router.storage
- source: |-
- .metadata.project = del(.project)
- .metadata.tenantId = .metadata.project
- parsed, err = parse_json(.event_message)
- if err == null {
- .event_message = parsed.msg
- .metadata.level = parsed.level
- .metadata.timestamp = parsed.time
- .metadata.context[0].host = parsed.hostname
- .metadata.context[0].pid = parsed.pid
- }
- # Postgres logs some messages to stderr which we map to warning severity level
- db_logs:
- type: remap
- inputs:
- - router.db
- source: |-
- .metadata.host = "db-default"
- .metadata.parsed.timestamp = .timestamp
-
- parsed, err = parse_regex(.event_message, r'.*(?P<level>INFO|NOTICE|WARNING|ERROR|LOG|FATAL|PANIC?):.*', numeric_groups: true)
-
- if err != null || parsed == null {
- .metadata.parsed.error_severity = "info"
- }
- if parsed != null {
- .metadata.parsed.error_severity = parsed.level
- }
- if .metadata.parsed.error_severity == "info" {
- .metadata.parsed.error_severity = "log"
- }
- .metadata.parsed.error_severity = upcase!(.metadata.parsed.error_severity)
-
-sinks:
- logflare_auth:
- type: 'http'
- inputs:
- - auth_logs
- encoding:
- codec: 'json'
- method: 'post'
- request:
- retry_max_duration_secs: 10
- uri: 'http://analytics:4000/api/logs?source_name=gotrue.logs.prod&api_key=${LOGFLARE_API_KEY?LOGFLARE_API_KEY is required}'
- logflare_realtime:
- type: 'http'
- inputs:
- - realtime_logs
- encoding:
- codec: 'json'
- method: 'post'
- request:
- retry_max_duration_secs: 10
- uri: 'http://analytics:4000/api/logs?source_name=realtime.logs.prod&api_key=${LOGFLARE_API_KEY?LOGFLARE_API_KEY is required}'
- logflare_rest:
- type: 'http'
- inputs:
- - rest_logs
- encoding:
- codec: 'json'
- method: 'post'
- request:
- retry_max_duration_secs: 10
- uri: 'http://analytics:4000/api/logs?source_name=postgREST.logs.prod&api_key=${LOGFLARE_API_KEY?LOGFLARE_API_KEY is required}'
- logflare_db:
- type: 'http'
- inputs:
- - db_logs
- encoding:
- codec: 'json'
- method: 'post'
- request:
- retry_max_duration_secs: 10
- # We must route the sink through kong because ingesting logs before logflare is fully initialised will
- # lead to broken queries from studio. This works by the assumption that containers are started in the
- # following order: vector > db > logflare > kong
- uri: 'http://kong:8000/analytics/v1/api/logs?source_name=postgres.logs&api_key=${LOGFLARE_API_KEY?LOGFLARE_API_KEY is required}'
- logflare_functions:
- type: 'http'
- inputs:
- - router.functions
- encoding:
- codec: 'json'
- method: 'post'
- request:
- retry_max_duration_secs: 10
- uri: 'http://analytics:4000/api/logs?source_name=deno-relay-logs&api_key=${LOGFLARE_API_KEY?LOGFLARE_API_KEY is required}'
- logflare_storage:
- type: 'http'
- inputs:
- - storage_logs
- encoding:
- codec: 'json'
- method: 'post'
- request:
- retry_max_duration_secs: 10
- uri: 'http://analytics:4000/api/logs?source_name=storage.logs.prod.2&api_key=${LOGFLARE_API_KEY?LOGFLARE_API_KEY is required}'
- logflare_kong:
- type: 'http'
- inputs:
- - kong_logs
- - kong_err
- encoding:
- codec: 'json'
- method: 'post'
- request:
- retry_max_duration_secs: 10
- uri: 'http://analytics:4000/api/logs?source_name=cloudflare.logs.prod&api_key=${LOGFLARE_API_KEY?LOGFLARE_API_KEY is required}'
diff --git a/backend/volumes/pooler/pooler.exs b/backend/volumes/pooler/pooler.exs
deleted file mode 100644
index 791d61c8..00000000
--- a/backend/volumes/pooler/pooler.exs
+++ /dev/null
@@ -1,30 +0,0 @@
-{:ok, _} = Application.ensure_all_started(:supavisor)
-
-{:ok, version} =
- case Supavisor.Repo.query!("select version()") do
- %{rows: [[ver]]} -> Supavisor.Helpers.parse_pg_version(ver)
- _ -> nil
- end
-
-params = %{
- "external_id" => System.get_env("POOLER_TENANT_ID"),
- "db_host" => "db",
- "db_port" => System.get_env("POSTGRES_PORT"),
- "db_database" => System.get_env("POSTGRES_DB"),
- "require_user" => false,
- "auth_query" => "SELECT * FROM pgbouncer.get_auth($1)",
- "default_max_clients" => System.get_env("POOLER_MAX_CLIENT_CONN"),
- "default_pool_size" => System.get_env("POOLER_DEFAULT_POOL_SIZE"),
- "default_parameter_status" => %{"server_version" => version},
- "users" => [%{
- "db_user" => "pgbouncer",
- "db_password" => System.get_env("POSTGRES_PASSWORD"),
- "mode_type" => System.get_env("POOLER_POOL_MODE"),
- "pool_size" => System.get_env("POOLER_DEFAULT_POOL_SIZE"),
- "is_manager" => true
- }]
-}
-
-if !Supavisor.Tenants.get_tenant_by_external_id(params["external_id"]) do
- {:ok, _} = Supavisor.Tenants.create_tenant(params)
-end
diff --git a/docker-compose.override.yml b/docker-compose.override.yml
deleted file mode 100644
index a81e669f..00000000
--- a/docker-compose.override.yml
+++ /dev/null
@@ -1,130 +0,0 @@
-name: flowsint
-
-services:
- # Traefik reverse proxy
- reverse-proxy:
- image: traefik:v3.1
- container_name: traefik-reverse-proxy
- command:
- - "--api.insecure=true"
- - "--providers.docker"
- - "--entrypoints.ws.address=:80"
- - "--providers.file.watch=true"
- - "--entryPoints.websecure.address=:443"
- - "--entrypoints.websecure.http.tls.certresolver=myresolver"
- - "--providers.file.filename=/etc/traefik/dynamic.yml"
- ports:
- - "80:80"
- - "443:443"
- - "8080:8080"
- restart: unless-stopped
- volumes:
- - ./certs:/etc/traefik/certs
- - ./dynamic.yml:/etc/traefik/dynamic.yml
- - /var/run/docker.sock:/var/run/docker.sock
- networks:
- - traefik
-
- # Next.js application
- web:
- build:
- context: flowsint-web
- dockerfile: Dockerfile
- container_name: flowsint-web
- ports:
- - "3000:3000"
- env_file:
- - .env
- networks:
- - traefik
- labels:
- - "traefik.enable=true"
- - "traefik.http.routers.nextjs.rule=Host(`app.flowsint.localhost`)"
- - "traefik.http.services.nextjs.loadbalancer.server.port=3000"
- - "traefik.http.routers.nextjs.entrypoints=websecure"
-
- # FastAPI application with Celery
- api:
- build:
- context: flowsint-api
- dockerfile: Dockerfile
- container_name: flowsint-api
- ports:
- - "5000:5000"
- depends_on:
- - redis
- - neo4j
- env_file:
- - .env
- command: ["/app/entrypoint.sh", "app"]
- restart: always
- networks:
- - traefik
- labels:
- - "traefik.enable=true"
- - "traefik.http.routers.app.rule=Host(`api.flowsint.localhost`)"
- - "traefik.http.services.app.loadbalancer.server.port=5000"
- - "traefik.http.routers.app.entrypoints=websecure"
-
- celery:
- build:
- context: flowsint-api
- dockerfile: Dockerfile
- container_name: celery-worker
- depends_on:
- - redis
- - api
- - neo4j
- env_file:
- - .env
- command: ["/app/entrypoint.sh", "celery"]
- restart: always
- networks:
- - traefik
-
- redis:
- image: "redis:alpine"
- container_name: redis-cache
- ports:
- - "6379:6379"
- networks:
- - traefik
-
- neo4j:
- image: neo4j:5
- container_name: flowsint-neo4j
- ports:
- - "7474:7474" # Web UI
- - "7687:7687" # Bolt
- environment:
- - NEO4J_AUTH=${NEO4J_USER}/${NEO4J_PASSWORD}
- - NEO4J_PLUGINS=["apoc"]
- - NEO4J_apoc_export_file_enabled=true
- - NEO4J_apoc_import_file_enabled=true
- - NEO4J_apoc_import_file_use__neo4j__config=true
- volumes:
- - neo4j_data:/data
- - neo4j_logs:/logs
- - neo4j_import:/var/lib/neo4j/import
- - neo4j_plugins:/plugins
- restart: unless-stopped
- networks:
- - traefik
- labels:
- - "traefik.enable=true"
- - "traefik.http.routers.neo4j.rule=Host(`neo4j.flowsint.localhost`)"
- - "traefik.http.services.neo4j.loadbalancer.server.port=7474"
- - "traefik.http.routers.neo4j.entrypoints=websecure"
-
-
-networks:
- traefik:
- name: traefik
- driver: bridge
-
-volumes:
- db-config:
- neo4j_data:
- neo4j_logs:
- neo4j_import:
- neo4j_plugins:
diff --git a/docker-compose.yml b/docker-compose.yml
index 52837c8d..95003c8d 100644
--- a/docker-compose.yml
+++ b/docker-compose.yml
@@ -24,6 +24,22 @@ services:
- /var/run/docker.sock:/var/run/docker.sock
networks:
- traefik
+ # PostgreSQL database
+ postgres:
+ image: postgres:15
+ container_name: flowsint-postgres
+ restart: always
+ environment:
+ POSTGRES_USER: flowsint
+ POSTGRES_PASSWORD: flowsint
+ POSTGRES_DB: flowsint
+ ports:
+ - "5433:5432"
+ volumes:
+ - pg_data:/var/lib/postgresql/data
+ networks:
+ - traefik
+
# Next.js application
web:
@@ -43,7 +59,7 @@ services:
- "traefik.http.services.nextjs.loadbalancer.server.port=3000"
- "traefik.http.routers.nextjs.entrypoints=websecure"
- # Flask-like application with Celery
+ # FastAPI application with Celery
api:
build:
context: flowsint-api
@@ -53,9 +69,10 @@ services:
- "5000:5000"
depends_on:
- redis
- environment:
- - REDIS_URL=redis://redis:6379/0
- - ENV=prod
+ - neo4j
+ - postgres
+ env_file:
+ - .env
command: ["/app/entrypoint.sh", "app"]
restart: always
networks:
@@ -74,9 +91,10 @@ services:
depends_on:
- redis
- api
- environment:
- - REDIS_URL=redis://redis:6379/0
- - ENV=prod
+ - neo4j
+ - postgres
+ env_file:
+ - .env
command: ["/app/entrypoint.sh", "celery"]
restart: always
networks:
@@ -90,492 +108,32 @@ services:
networks:
- traefik
- # Supabase services
- studio:
- container_name: supabase-studio
- image: supabase/studio:20250224-d10db0f
- restart: unless-stopped
- healthcheck:
- test:
- [
- "CMD",
- "node",
- "-e",
- "fetch('http://studio:3000/api/platform/profile').then((r) => {if (r.status !== 200) throw new Error(r.status)})"
- ]
- timeout: 10s
- interval: 5s
- retries: 3
- depends_on:
- analytics:
- condition: service_healthy
- environment:
- STUDIO_PG_META_URL: http://meta:8080
- POSTGRES_PASSWORD: ${POSTGRES_PASSWORD}
- DEFAULT_ORGANIZATION_NAME: ${STUDIO_DEFAULT_ORGANIZATION}
- DEFAULT_PROJECT_NAME: ${STUDIO_DEFAULT_PROJECT}
- OPENAI_API_KEY: ${OPENAI_API_KEY:-}
- SUPABASE_URL: http://kong:8000
- SUPABASE_PUBLIC_URL: ${SUPABASE_PUBLIC_URL}
- SUPABASE_ANON_KEY: ${ANON_KEY}
- SUPABASE_SERVICE_KEY: ${SERVICE_ROLE_KEY}
- AUTH_JWT_SECRET: ${JWT_SECRET}
- LOGFLARE_API_KEY: ${LOGFLARE_API_KEY}
- LOGFLARE_URL: http://analytics:4000
- NEXT_PUBLIC_ENABLE_LOGS: true
- NEXT_ANALYTICS_BACKEND_PROVIDER: postgres
- networks:
- - traefik
- labels:
- - "traefik.enable=true"
- - "traefik.http.routers.studio.rule=Host(`studio.flowsint.localhost`)"
- - "traefik.http.services.studio.loadbalancer.server.port=3000"
- - "traefik.http.routers.studio.entrypoints=websecure"
-
- kong:
- container_name: supabase-kong
- image: kong:2.8.1
- restart: unless-stopped
+ neo4j:
+ image: neo4j:5
+ container_name: flowsint-neo4j
ports:
- - ${KONG_HTTP_PORT}:8000/tcp
- - ${KONG_HTTPS_PORT}:8443/tcp
- volumes:
- - ./backend/volumes/api/kong.yml:/home/kong/temp.yml:ro,z
- depends_on:
- analytics:
- condition: service_healthy
- environment:
- KONG_DATABASE: "off"
- KONG_DECLARATIVE_CONFIG: /home/kong/kong.yml
- KONG_DNS_ORDER: LAST,A,CNAME
- KONG_PLUGINS: request-transformer,cors,key-auth,acl,basic-auth
- KONG_NGINX_PROXY_PROXY_BUFFER_SIZE: 160k
- KONG_NGINX_PROXY_PROXY_BUFFERS: 64 160k
- SUPABASE_ANON_KEY: ${ANON_KEY}
- SUPABASE_SERVICE_KEY: ${SERVICE_ROLE_KEY}
- DASHBOARD_USERNAME: ${DASHBOARD_USERNAME}
- DASHBOARD_PASSWORD: ${DASHBOARD_PASSWORD}
- entrypoint: bash -c 'eval "echo \"$$(cat ~/temp.yml)\"" > ~/kong.yml && /docker-entrypoint.sh kong docker-start'
- networks:
- - traefik
- labels:
- - "traefik.enable=true"
- - "traefik.http.routers.kong.rule=Host(`kong.flowsint.localhost`)"
- - "traefik.http.services.kong.loadbalancer.server.port=8000"
- - "traefik.http.routers.kong.entrypoints=websecure"
-
- auth:
- container_name: supabase-auth
- image: supabase/gotrue:v2.170.0
- restart: unless-stopped
- healthcheck:
- test:
- [
- "CMD",
- "wget",
- "--no-verbose",
- "--tries=1",
- "--spider",
- "http://localhost:9999/health"
- ]
- timeout: 5s
- interval: 5s
- retries: 3
- depends_on:
- db:
- condition: service_healthy
- analytics:
- condition: service_healthy
- environment:
- GOTRUE_API_HOST: 0.0.0.0
- GOTRUE_API_PORT: 9999
- API_EXTERNAL_URL: ${API_EXTERNAL_URL}
- GOTRUE_DB_DRIVER: postgres
- GOTRUE_DB_DATABASE_URL: postgres://supabase_auth_admin:${POSTGRES_PASSWORD}@${POSTGRES_HOST}:${POSTGRES_PORT}/${POSTGRES_DB}
- GOTRUE_SITE_URL: ${SITE_URL}
- GOTRUE_URI_ALLOW_LIST: ${ADDITIONAL_REDIRECT_URLS}
- GOTRUE_DISABLE_SIGNUP: ${DISABLE_SIGNUP}
- GOTRUE_JWT_ADMIN_ROLES: service_role
- GOTRUE_JWT_AUD: authenticated
- GOTRUE_JWT_DEFAULT_GROUP_NAME: authenticated
- GOTRUE_JWT_EXP: ${JWT_EXPIRY}
- GOTRUE_JWT_SECRET: ${JWT_SECRET}
- GOTRUE_EXTERNAL_EMAIL_ENABLED: ${ENABLE_EMAIL_SIGNUP}
- GOTRUE_EXTERNAL_ANONYMOUS_USERS_ENABLED: ${ENABLE_ANONYMOUS_USERS}
- GOTRUE_MAILER_AUTOCONFIRM: ${ENABLE_EMAIL_AUTOCONFIRM}
- GOTRUE_SMTP_ADMIN_EMAIL: ${SMTP_ADMIN_EMAIL}
- GOTRUE_SMTP_HOST: ${SMTP_HOST}
- GOTRUE_SMTP_PORT: ${SMTP_PORT}
- GOTRUE_SMTP_USER: ${SMTP_USER}
- GOTRUE_SMTP_PASS: ${SMTP_PASS}
- GOTRUE_SMTP_SENDER_NAME: ${SMTP_SENDER_NAME}
- GOTRUE_MAILER_URLPATHS_INVITE: ${MAILER_URLPATHS_INVITE}
- GOTRUE_MAILER_URLPATHS_CONFIRMATION: ${MAILER_URLPATHS_CONFIRMATION}
- GOTRUE_MAILER_URLPATHS_RECOVERY: ${MAILER_URLPATHS_RECOVERY}
- GOTRUE_MAILER_URLPATHS_EMAIL_CHANGE: ${MAILER_URLPATHS_EMAIL_CHANGE}
- GOTRUE_EXTERNAL_PHONE_ENABLED: ${ENABLE_PHONE_SIGNUP}
- GOTRUE_SMS_AUTOCONFIRM: ${ENABLE_PHONE_AUTOCONFIRM}
- networks:
- - traefik
-
- rest:
- container_name: supabase-rest
- image: postgrest/postgrest:v12.2.8
- restart: unless-stopped
- depends_on:
- db:
- condition: service_healthy
- analytics:
- condition: service_healthy
- environment:
- PGRST_DB_URI: postgres://authenticator:${POSTGRES_PASSWORD}@${POSTGRES_HOST}:${POSTGRES_PORT}/${POSTGRES_DB}
- PGRST_DB_SCHEMAS: ${PGRST_DB_SCHEMAS}
- PGRST_DB_ANON_ROLE: anon
- PGRST_JWT_SECRET: ${JWT_SECRET}
- PGRST_DB_USE_LEGACY_GUCS: "false"
- PGRST_APP_SETTINGS_JWT_SECRET: ${JWT_SECRET}
- PGRST_APP_SETTINGS_JWT_EXP: ${JWT_EXPIRY}
- command:
- [
- "postgrest"
- ]
- networks:
- - traefik
-
- realtime:
- container_name: realtime-dev.supabase-realtime
- image: supabase/realtime:v2.34.40
- restart: unless-stopped
- depends_on:
- db:
- condition: service_healthy
- analytics:
- condition: service_healthy
- healthcheck:
- test:
- [
- "CMD",
- "curl",
- "-sSfL",
- "--head",
- "-o",
- "/dev/null",
- "-H",
- "Authorization: Bearer ${ANON_KEY}",
- "http://localhost:4000/api/tenants/realtime-dev/health"
- ]
- timeout: 5s
- interval: 5s
- retries: 3
- environment:
- PORT: 4000
- DB_HOST: ${POSTGRES_HOST}
- DB_PORT: ${POSTGRES_PORT}
- DB_USER: supabase_admin
- DB_PASSWORD: ${POSTGRES_PASSWORD}
- DB_NAME: ${POSTGRES_DB}
- DB_AFTER_CONNECT_QUERY: 'SET search_path TO _realtime'
- DB_ENC_KEY: supabaserealtime
- API_JWT_SECRET: ${JWT_SECRET}
- SECRET_KEY_BASE: ${SECRET_KEY_BASE}
- ERL_AFLAGS: -proto_dist inet_tcp
- DNS_NODES: "''"
- RLIMIT_NOFILE: "10000"
- APP_NAME: realtime
- SEED_SELF_HOST: true
- RUN_JANITOR: true
- networks:
- - traefik
-
- storage:
- container_name: supabase-storage
- image: supabase/storage-api:v1.19.3
- restart: unless-stopped
- volumes:
- - ./backend/volumes/storage:/var/lib/storage:z
- healthcheck:
- test:
- [
- "CMD",
- "wget",
- "--no-verbose",
- "--tries=1",
- "--spider",
- "http://storage:5000/status"
- ]
- timeout: 5s
- interval: 5s
- retries: 3
- depends_on:
- db:
- condition: service_healthy
- rest:
- condition: service_started
- imgproxy:
- condition: service_started
+ - "7474:7474" # Web UI
+ - "7687:7687" # Bolt
environment:
- ANON_KEY: ${ANON_KEY}
- SERVICE_KEY: ${SERVICE_ROLE_KEY}
- POSTGREST_URL: http://rest:3000
- PGRST_JWT_SECRET: ${JWT_SECRET}
- DATABASE_URL: postgres://supabase_storage_admin:${POSTGRES_PASSWORD}@${POSTGRES_HOST}:${POSTGRES_PORT}/${POSTGRES_DB}
- FILE_SIZE_LIMIT: 52428800
- STORAGE_BACKEND: file
- FILE_STORAGE_BACKEND_PATH: /var/lib/storage
- TENANT_ID: stub
- REGION: stub
- GLOBAL_S3_BUCKET: stub
- ENABLE_IMAGE_TRANSFORMATION: "true"
- IMGPROXY_URL: http://imgproxy:5001
- networks:
- - traefik
-
- imgproxy:
- container_name: supabase-imgproxy
- image: darthsim/imgproxy:v3.8.0
- restart: unless-stopped
+ - NEO4J_AUTH=${NEO4J_USER}/${NEO4J_PASSWORD}
+ - NEO4J_PLUGINS=["apoc"]
+ - NEO4J_apoc_export_file_enabled=true
+ - NEO4J_apoc_import_file_enabled=true
+ - NEO4J_apoc_import_file_use__neo4j__config=true
volumes:
- - ./backend/volumes/storage:/var/lib/storage:z
- healthcheck:
- test:
- [
- "CMD",
- "imgproxy",
- "health"
- ]
- timeout: 5s
- interval: 5s
- retries: 3
- environment:
- IMGPROXY_BIND: ":5001"
- IMGPROXY_LOCAL_FILESYSTEM_ROOT: /
- IMGPROXY_USE_ETAG: "true"
- IMGPROXY_ENABLE_WEBP_DETECTION: ${IMGPROXY_ENABLE_WEBP_DETECTION}
- networks:
- - traefik
-
- meta:
- container_name: supabase-meta
- image: supabase/postgres-meta:v0.86.1
+ - neo4j_data:/data
+ - neo4j_logs:/logs
+ - neo4j_import:/var/lib/neo4j/import
+ - neo4j_plugins:/plugins
restart: unless-stopped
- depends_on:
- db:
- condition: service_healthy
- analytics:
- condition: service_healthy
- environment:
- PG_META_PORT: 8080
- PG_META_DB_HOST: ${POSTGRES_HOST}
- PG_META_DB_PORT: ${POSTGRES_PORT}
- PG_META_DB_NAME: ${POSTGRES_DB}
- PG_META_DB_USER: supabase_admin
- PG_META_DB_PASSWORD: ${POSTGRES_PASSWORD}
- networks:
- - traefik
-
- functions:
- container_name: supabase-edge-functions
- image: supabase/edge-runtime:v1.67.2
- restart: unless-stopped
- volumes:
- - ./backend/volumes/functions:/home/deno/functions:Z
- depends_on:
- analytics:
- condition: service_healthy
- environment:
- JWT_SECRET: ${JWT_SECRET}
- SUPABASE_URL: http://kong:8000
- SUPABASE_ANON_KEY: ${ANON_KEY}
- SUPABASE_SERVICE_ROLE_KEY: ${SERVICE_ROLE_KEY}
- SUPABASE_DB_URL: postgresql://postgres:${POSTGRES_PASSWORD}@${POSTGRES_HOST}:${POSTGRES_PORT}/${POSTGRES_DB}
- VERIFY_JWT: "${FUNCTIONS_VERIFY_JWT}"
- command:
- [
- "start",
- "--main-service",
- "/home/deno/functions/main"
- ]
networks:
- traefik
labels:
- "traefik.enable=true"
- - "traefik.http.routers.functions.rule=Host(`functions.flowsint.localhost`)"
- - "traefik.http.services.functions.loadbalancer.server.port=9000"
- - "traefik.http.routers.functions.entrypoints=websecure"
-
- analytics:
- container_name: supabase-analytics
- image: supabase/logflare:1.12.5
- restart: unless-stopped
- ports:
- - 4000:4000
- healthcheck:
- test:
- [
- "CMD",
- "curl",
- "http://localhost:4000/health"
- ]
- timeout: 5s
- interval: 5s
- retries: 10
- depends_on:
- db:
- condition: service_healthy
- environment:
- LOGFLARE_NODE_HOST: 127.0.0.1
- DB_USERNAME: supabase_admin
- DB_DATABASE: _supabase
- DB_HOSTNAME: ${POSTGRES_HOST}
- DB_PORT: ${POSTGRES_PORT}
- DB_PASSWORD: ${POSTGRES_PASSWORD}
- DB_SCHEMA: _analytics
- LOGFLARE_API_KEY: ${LOGFLARE_API_KEY}
- LOGFLARE_SINGLE_TENANT: true
- LOGFLARE_SUPABASE_MODE: true
- LOGFLARE_MIN_CLUSTER_SIZE: 1
- POSTGRES_BACKEND_URL: postgresql://supabase_admin:${POSTGRES_PASSWORD}@${POSTGRES_HOST}:${POSTGRES_PORT}/_supabase
- POSTGRES_BACKEND_SCHEMA: _analytics
- LOGFLARE_FEATURE_FLAG_OVERRIDE: multibackend=true
- networks:
- - traefik
+ - "traefik.http.routers.neo4j.rule=Host(`neo4j.flowsint.localhost`)"
+ - "traefik.http.services.neo4j.loadbalancer.server.port=7474"
+ - "traefik.http.routers.neo4j.entrypoints=websecure"
- db:
- container_name: supabase-db
- image: supabase/postgres:15.8.1.049
- restart: unless-stopped
- volumes:
- - ./backend/volumes/db/realtime.sql:/docker-entrypoint-initdb.d/migrations/99-realtime.sql:Z
- - ./backend/volumes/db/webhooks.sql:/docker-entrypoint-initdb.d/init-scripts/98-webhooks.sql:Z
- - ./backend/volumes/db/roles.sql:/docker-entrypoint-initdb.d/init-scripts/99-roles.sql:Z
- - ./backend/volumes/db/jwt.sql:/docker-entrypoint-initdb.d/init-scripts/99-jwt.sql:Z
- - ./backend/volumes/db/data:/var/lib/postgresql/data:Z
- - ./backend/volumes/db/_supabase.sql:/docker-entrypoint-initdb.d/migrations/97-_supabase.sql:Z
- - ./backend/volumes/db/logs.sql:/docker-entrypoint-initdb.d/migrations/99-logs.sql:Z
- - ./backend/volumes/db/pooler.sql:/docker-entrypoint-initdb.d/migrations/99-pooler.sql:Z
- - db-config:/etc/postgresql-custom
- healthcheck:
- test:
- [
- "CMD",
- "pg_isready",
- "-U",
- "postgres",
- "-h",
- "localhost"
- ]
- interval: 5s
- timeout: 5s
- retries: 10
- depends_on:
- vector:
- condition: service_healthy
- environment:
- POSTGRES_HOST: /var/run/postgresql
- PGPORT: ${POSTGRES_PORT}
- POSTGRES_PORT: ${POSTGRES_PORT}
- PGPASSWORD: ${POSTGRES_PASSWORD}
- POSTGRES_PASSWORD: ${POSTGRES_PASSWORD}
- PGDATABASE: ${POSTGRES_DB}
- POSTGRES_DB: ${POSTGRES_DB}
- JWT_SECRET: ${JWT_SECRET}
- JWT_EXP: ${JWT_EXPIRY}
- command:
- [
- "postgres",
- "-c",
- "config_file=/etc/postgresql/postgresql.conf",
- "-c",
- "log_min_messages=fatal"
- ]
- networks:
- - traefik
-
- vector:
- container_name: supabase-vector
- image: timberio/vector:0.28.1-alpine
- restart: unless-stopped
- volumes:
- - ./backend/volumes/logs/vector.yml:/etc/vector/vector.yml:ro,z
- - ${DOCKER_SOCKET_LOCATION}:/var/run/docker.sock:ro,z
- healthcheck:
- test:
- [
- "CMD",
- "wget",
- "--no-verbose",
- "--tries=1",
- "--spider",
- "http://vector:9001/health"
- ]
- timeout: 5s
- interval: 5s
- retries: 3
- environment:
- LOGFLARE_API_KEY: ${LOGFLARE_API_KEY}
- command:
- [
- "--config",
- "/etc/vector/vector.yml"
- ]
- security_opt:
- - "label=disable"
- networks:
- - traefik
-
- supavisor:
- container_name: supabase-pooler
- image: supabase/supavisor:2.4.12
- restart: unless-stopped
- ports:
- - ${POSTGRES_PORT}:5432
- - ${POOLER_PROXY_PORT_TRANSACTION}:6543
- volumes:
- - ./backend/volumes/pooler/pooler.exs:/etc/pooler/pooler.exs:ro,z
- healthcheck:
- test:
- [
- "CMD",
- "curl",
- "-sSfL",
- "--head",
- "-o",
- "/dev/null",
- "http://127.0.0.1:4000/api/health"
- ]
- interval: 10s
- timeout: 5s
- retries: 5
- depends_on:
- db:
- condition: service_healthy
- analytics:
- condition: service_healthy
- environment:
- PORT: 4000
- POSTGRES_PORT: ${POSTGRES_PORT}
- POSTGRES_DB: ${POSTGRES_DB}
- POSTGRES_PASSWORD: ${POSTGRES_PASSWORD}
- DATABASE_URL: ecto://supabase_admin:${POSTGRES_PASSWORD}@db:${POSTGRES_PORT}/_supabase
- CLUSTER_POSTGRES: true
- SECRET_KEY_BASE: ${SECRET_KEY_BASE}
- VAULT_ENC_KEY: ${VAULT_ENC_KEY}
- API_JWT_SECRET: ${JWT_SECRET}
- METRICS_JWT_SECRET: ${JWT_SECRET}
- REGION: local
- ERL_AFLAGS: -proto_dist inet_tcp
- POOLER_TENANT_ID: ${POOLER_TENANT_ID}
- POOLER_DEFAULT_POOL_SIZE: ${POOLER_DEFAULT_POOL_SIZE}
- POOLER_MAX_CLIENT_CONN: ${POOLER_MAX_CLIENT_CONN}
- POOLER_POOL_MODE: transaction
- command:
- [
- "/bin/sh",
- "-c",
- "/app/bin/migrate && /app/bin/supavisor eval \"$$(cat /etc/pooler/pooler.exs)\" && /app/bin/server"
- ]
- networks:
- - traefik
networks:
traefik:
@@ -583,4 +141,9 @@ networks:
driver: bridge
volumes:
- db-config:
\ No newline at end of file
+ db-config:
+ neo4j_data:
+ neo4j_logs:
+ neo4j_import:
+ neo4j_plugins:
+ pg_data:
diff --git a/flowsint-api/.env.development b/flowsint-api/.env.development
new file mode 100644
index 00000000..5d4a399e
--- /dev/null
+++ b/flowsint-api/.env.development
@@ -0,0 +1,7 @@
+HIBP_API_KEY=70b78a3256c84d09b79cd4953d77bdf3
+NEO4J_URI_BOLT=bolt://localhost:7687
+REDIS_URI=redis://127.0.0.1:6379/0
+NEO4J_USERNAME=neo4j
+NEO4J_PASSWORD=password
+DATABASE_URL=postgresql://flowsint:flowsint@localhost:5433/flowsint
+AUTH_SECRET="cZcwTtJb6PhdDn253IuJntbGSrhE/bYhY8+Iht8uqrc="
\ No newline at end of file
diff --git a/flowsint-api/app/neo4j/__init__.py b/flowsint-api/__init__.py
similarity index 100%
rename from flowsint-api/app/neo4j/__init__.py
rename to flowsint-api/__init__.py
diff --git a/flowsint-api/alembic.ini b/flowsint-api/alembic.ini
new file mode 100644
index 00000000..c527288e
--- /dev/null
+++ b/flowsint-api/alembic.ini
@@ -0,0 +1,38 @@
+[alembic]
+script_location = alembic
+sqlalchemy.url = postgresql://flowsint:flowsint@localhost:5433/flowsint
+
+[loggers]
+keys = root,sqlalchemy,alembic
+
+[handlers]
+keys = console
+
+[formatters]
+keys = generic
+
+[logger_root]
+level = WARN
+handlers = console
+qualname =
+
+[logger_sqlalchemy]
+level = WARN
+handlers =
+qualname = sqlalchemy.engine
+propagate = 0
+
+[logger_alembic]
+level = INFO
+handlers =
+qualname = alembic
+propagate = 0
+
+[handler_console]
+class = StreamHandler
+args = (sys.stderr,)
+level = NOTSET
+formatter = generic
+
+[formatter_generic]
+format = %(levelname)-5.5s [%(name)s] %(message)s
diff --git a/flowsint-api/alembic/README b/flowsint-api/alembic/README
new file mode 100644
index 00000000..98e4f9c4
--- /dev/null
+++ b/flowsint-api/alembic/README
@@ -0,0 +1 @@
+Generic single-database configuration.
\ No newline at end of file
diff --git a/flowsint-api/alembic/env.py b/flowsint-api/alembic/env.py
new file mode 100644
index 00000000..2280ed23
--- /dev/null
+++ b/flowsint-api/alembic/env.py
@@ -0,0 +1,61 @@
+import os
+import sys
+from logging.config import fileConfig
+
+from sqlalchemy import engine_from_config, pool
+from alembic import context
+from dotenv import load_dotenv
+
+# Charger les variables d'environnement
+load_dotenv()
+
+# Permet les imports comme from app.models.base import Base
+sys.path.append(os.path.join(os.path.dirname(__file__), '..'))
+
+# Importer Base et toutes les tables pour qu'Alembic les détecte
+from app.models.base import Base
+from app.models.models import * # noqa
+
+# Configuration Alembic
+config = context.config
+if config.config_file_name is not None:
+ fileConfig(config.config_file_name)
+
+# Injecter l'URL de la BDD depuis le .env
+database_url = os.getenv("DATABASE_URL")
+if not database_url:
+ raise RuntimeError("DATABASE_URL is not defined in .env")
+config.set_main_option("sqlalchemy.url", database_url)
+
+# Définir la métadonnée cible pour autogenerate
+target_metadata = Base.metadata
+
+def run_migrations_offline() -> None:
+ """Run migrations in 'offline' mode."""
+ url = config.get_main_option("sqlalchemy.url")
+ context.configure(
+ url=url,
+ target_metadata=target_metadata,
+ literal_binds=True,
+ dialect_opts={"paramstyle": "named"},
+ )
+ with context.begin_transaction():
+ context.run_migrations()
+
+def run_migrations_online() -> None:
+ """Run migrations in 'online' mode."""
+ connectable = engine_from_config(
+ config.get_section(config.config_ini_section),
+ prefix="sqlalchemy.",
+ poolclass=pool.NullPool,
+ )
+
+ with connectable.connect() as connection:
+ context.configure(connection=connection, target_metadata=target_metadata)
+ with context.begin_transaction():
+ context.run_migrations()
+
+if context.is_offline_mode():
+ run_migrations_offline()
+else:
+ run_migrations_online()
diff --git a/flowsint-api/alembic/script.py.mako b/flowsint-api/alembic/script.py.mako
new file mode 100644
index 00000000..480b130d
--- /dev/null
+++ b/flowsint-api/alembic/script.py.mako
@@ -0,0 +1,28 @@
+"""${message}
+
+Revision ID: ${up_revision}
+Revises: ${down_revision | comma,n}
+Create Date: ${create_date}
+
+"""
+from typing import Sequence, Union
+
+from alembic import op
+import sqlalchemy as sa
+${imports if imports else ""}
+
+# revision identifiers, used by Alembic.
+revision: str = ${repr(up_revision)}
+down_revision: Union[str, None] = ${repr(down_revision)}
+branch_labels: Union[str, Sequence[str], None] = ${repr(branch_labels)}
+depends_on: Union[str, Sequence[str], None] = ${repr(depends_on)}
+
+
+def upgrade() -> None:
+ """Upgrade schema."""
+ ${upgrades if upgrades else "pass"}
+
+
+def downgrade() -> None:
+ """Downgrade schema."""
+ ${downgrades if downgrades else "pass"}
diff --git a/flowsint-api/alembic/versions/40ece72583b7_add_email_and_hashed_password_to_profile.py b/flowsint-api/alembic/versions/40ece72583b7_add_email_and_hashed_password_to_profile.py
new file mode 100644
index 00000000..16264141
--- /dev/null
+++ b/flowsint-api/alembic/versions/40ece72583b7_add_email_and_hashed_password_to_profile.py
@@ -0,0 +1,38 @@
+"""Add email and hashed_password to profile
+
+Revision ID: 40ece72583b7
+Revises: 965b56353b4c
+Create Date: 2025-05-19 15:37:27.466187
+
+"""
+from typing import Sequence, Union
+
+from alembic import op
+import sqlalchemy as sa
+
+
+# revision identifiers, used by Alembic.
+revision: str = '40ece72583b7'
+down_revision: Union[str, None] = '965b56353b4c'
+branch_labels: Union[str, Sequence[str], None] = None
+depends_on: Union[str, Sequence[str], None] = None
+
+
+def upgrade() -> None:
+ """Upgrade schema."""
+ # ### commands auto generated by Alembic - please adjust! ###
+ op.add_column('profiles', sa.Column('email', sa.String(), nullable=False))
+ op.add_column('profiles', sa.Column('hashed_password', sa.String(), nullable=False))
+ op.add_column('profiles', sa.Column('is_active', sa.Boolean(), nullable=False))
+ op.create_unique_constraint(None, 'profiles', ['email'])
+ # ### end Alembic commands ###
+
+
+def downgrade() -> None:
+ """Downgrade schema."""
+ # ### commands auto generated by Alembic - please adjust! ###
+ op.drop_constraint(None, 'profiles', type_='unique')
+ op.drop_column('profiles', 'is_active')
+ op.drop_column('profiles', 'hashed_password')
+ op.drop_column('profiles', 'email')
+ # ### end Alembic commands ###
diff --git a/flowsint-api/alembic/versions/76f5436251e3_add_relationship_between_investigations_.py b/flowsint-api/alembic/versions/76f5436251e3_add_relationship_between_investigations_.py
new file mode 100644
index 00000000..8b57cc43
--- /dev/null
+++ b/flowsint-api/alembic/versions/76f5436251e3_add_relationship_between_investigations_.py
@@ -0,0 +1,32 @@
+"""Add relationship between investigations and sketches
+
+Revision ID: 76f5436251e3
+Revises: d0a8e5b5a7b9
+Create Date: 2025-05-19 23:59:33.721812
+
+"""
+from typing import Sequence, Union
+
+from alembic import op
+import sqlalchemy as sa
+
+
+# revision identifiers, used by Alembic.
+revision: str = '76f5436251e3'
+down_revision: Union[str, None] = 'd0a8e5b5a7b9'
+branch_labels: Union[str, Sequence[str], None] = None
+depends_on: Union[str, Sequence[str], None] = None
+
+
+def upgrade() -> None:
+ """Upgrade schema."""
+ # ### commands auto generated by Alembic - please adjust! ###
+ pass
+ # ### end Alembic commands ###
+
+
+def downgrade() -> None:
+ """Downgrade schema."""
+ # ### commands auto generated by Alembic - please adjust! ###
+ pass
+ # ### end Alembic commands ###
diff --git a/flowsint-api/alembic/versions/965b56353b4c_initial_migration.py b/flowsint-api/alembic/versions/965b56353b4c_initial_migration.py
new file mode 100644
index 00000000..dc32a13b
--- /dev/null
+++ b/flowsint-api/alembic/versions/965b56353b4c_initial_migration.py
@@ -0,0 +1,151 @@
+"""initial migration
+
+Revision ID: 965b56353b4c
+Revises:
+Create Date: 2025-05-19 14:35:04.755433
+
+"""
+from typing import Sequence, Union
+
+from alembic import op
+import sqlalchemy as sa
+from sqlalchemy.dialects import postgresql
+
+# revision identifiers, used by Alembic.
+revision: str = '965b56353b4c'
+down_revision: Union[str, None] = None
+branch_labels: Union[str, Sequence[str], None] = None
+depends_on: Union[str, Sequence[str], None] = None
+
+
+def upgrade() -> None:
+ """Upgrade schema."""
+ # ### commands auto generated by Alembic - please adjust! ###
+ op.create_table('profiles',
+ sa.Column('id', sa.UUID(), nullable=False),
+ sa.Column('first_name', sa.Text(), nullable=True),
+ sa.Column('last_name', sa.Text(), nullable=True),
+ sa.Column('avatar_url', sa.Text(), nullable=True),
+ sa.PrimaryKeyConstraint('id')
+ )
+ op.create_table('transforms',
+ sa.Column('id', sa.UUID(), nullable=False),
+ sa.Column('name', sa.Text(), nullable=False),
+ sa.Column('description', sa.Text(), nullable=True),
+ sa.Column('category', postgresql.ARRAY(sa.Text()), nullable=True),
+ sa.Column('transform_schema', sa.JSON(), nullable=True),
+ sa.Column('created_at', sa.DateTime(timezone=True), server_default=sa.text('now()'), nullable=True),
+ sa.Column('last_updated_at', sa.DateTime(timezone=True), server_default=sa.text('now()'), nullable=True),
+ sa.PrimaryKeyConstraint('id')
+ )
+ op.create_table('feedbacks',
+ sa.Column('id', sa.Uuid(), nullable=False),
+ sa.Column('created_at', sa.DateTime(timezone=True), server_default=sa.text('now()'), nullable=True),
+ sa.Column('content', sa.Text(), nullable=True),
+ sa.Column('owner_id', sa.UUID(), nullable=True),
+ sa.ForeignKeyConstraint(['owner_id'], ['profiles.id'], ),
+ sa.PrimaryKeyConstraint('id')
+ )
+ op.create_table('investigations',
+ sa.Column('id', sa.UUID(), nullable=False),
+ sa.Column('created_at', sa.DateTime(timezone=True), server_default=sa.text('now()'), nullable=True),
+ sa.Column('name', sa.Text(), nullable=True),
+ sa.Column('description', sa.Text(), nullable=True),
+ sa.Column('owner_id', sa.UUID(), nullable=True),
+ sa.Column('last_updated_at', sa.DateTime(timezone=True), server_default=sa.text('now()'), nullable=True),
+ sa.Column('status', sa.String(), server_default='active', nullable=True),
+ sa.ForeignKeyConstraint(['owner_id'], ['profiles.id'], onupdate='CASCADE', ondelete='CASCADE'),
+ sa.PrimaryKeyConstraint('id')
+ )
+ op.create_index('idx_investigations_id', 'investigations', ['id'], unique=False)
+ op.create_index('idx_investigations_owner_id', 'investigations', ['owner_id'], unique=False)
+ op.create_table('investigations_profiles',
+ sa.Column('id', sa.Uuid(), nullable=False),
+ sa.Column('created_at', sa.DateTime(timezone=True), server_default=sa.text('now()'), nullable=True),
+ sa.Column('investigation_id', sa.UUID(), nullable=True),
+ sa.Column('profile_id', sa.UUID(), nullable=True),
+ sa.Column('role', sa.String(), server_default='member', nullable=True),
+ sa.ForeignKeyConstraint(['investigation_id'], ['investigations.id'], onupdate='CASCADE', ondelete='CASCADE'),
+ sa.ForeignKeyConstraint(['profile_id'], ['profiles.id'], onupdate='CASCADE', ondelete='CASCADE'),
+ sa.PrimaryKeyConstraint('id')
+ )
+ op.create_index('idx_investigations_profiles_investigation_id', 'investigations_profiles', ['investigation_id'], unique=False)
+ op.create_index('idx_investigations_profiles_profile_id', 'investigations_profiles', ['profile_id'], unique=False)
+ op.create_index('projects_profiles_unique_profile_project', 'investigations_profiles', ['profile_id', 'investigation_id'], unique=True)
+ op.create_table('sketches',
+ sa.Column('id', sa.UUID(), nullable=False),
+ sa.Column('title', sa.Text(), nullable=True),
+ sa.Column('description', sa.Text(), nullable=True),
+ sa.Column('created_at', sa.DateTime(timezone=True), server_default=sa.text('now()'), nullable=True),
+ sa.Column('owner_id', sa.UUID(), nullable=True),
+ sa.Column('status', sa.String(), server_default='active', nullable=True),
+ sa.Column('investigation_id', sa.UUID(), nullable=True),
+ sa.Column('last_updated_at', sa.DateTime(timezone=True), server_default=sa.text('now()'), nullable=True),
+ sa.ForeignKeyConstraint(['investigation_id'], ['investigations.id'], onupdate='CASCADE', ondelete='CASCADE'),
+ sa.ForeignKeyConstraint(['owner_id'], ['profiles.id'], onupdate='CASCADE', ondelete='CASCADE'),
+ sa.PrimaryKeyConstraint('id')
+ )
+ op.create_index('idx_sketches_investigation_id', 'sketches', ['investigation_id'], unique=False)
+ op.create_index('idx_sketches_owner_id', 'sketches', ['owner_id'], unique=False)
+ op.create_table('scans',
+ sa.Column('id', sa.UUID(), nullable=False),
+ sa.Column('created_at', sa.DateTime(timezone=True), server_default=sa.text('now()'), nullable=True),
+ sa.Column('status', sa.String(), nullable=True),
+ sa.Column('results', sa.JSON(), nullable=True),
+ sa.Column('values', postgresql.ARRAY(sa.Text()), nullable=True),
+ sa.Column('sketch_id', sa.UUID(), nullable=True),
+ sa.ForeignKeyConstraint(['sketch_id'], ['sketches.id'], onupdate='CASCADE', ondelete='CASCADE'),
+ sa.PrimaryKeyConstraint('id')
+ )
+ op.create_index('idx_scans_sketch_id', 'scans', ['sketch_id'], unique=False)
+ op.create_table('sketches_profiles',
+ sa.Column('id', sa.Uuid(), nullable=False),
+ sa.Column('created_at', sa.DateTime(timezone=True), server_default=sa.text('now()'), nullable=True),
+ sa.Column('profile_id', sa.UUID(), nullable=True),
+ sa.Column('sketch_id', sa.UUID(), nullable=True),
+ sa.Column('role', sa.String(), server_default='editor', nullable=True),
+ sa.ForeignKeyConstraint(['profile_id'], ['profiles.id'], onupdate='CASCADE', ondelete='CASCADE'),
+ sa.ForeignKeyConstraint(['sketch_id'], ['sketches.id'], onupdate='CASCADE', ondelete='CASCADE'),
+ sa.PrimaryKeyConstraint('id')
+ )
+ op.create_index('idx_sketches_profiles_profile_id', 'sketches_profiles', ['profile_id'], unique=False)
+ op.create_index('idx_sketches_profiles_sketch_id', 'sketches_profiles', ['sketch_id'], unique=False)
+ op.create_index('investigations_profiles_unique_profile_investigation', 'sketches_profiles', ['profile_id', 'sketch_id'], unique=True)
+ op.create_table('logs',
+ sa.Column('id', sa.UUID(), nullable=False),
+ sa.Column('scan_id', sa.UUID(), nullable=True),
+ sa.Column('content', sa.Text(), nullable=True),
+ sa.Column('created_at', sa.DateTime(timezone=True), server_default=sa.text('now()'), nullable=True),
+ sa.Column('sketch_id', sa.UUID(), nullable=True),
+ sa.Column('type', sa.String(), server_default='INFO', nullable=True),
+ sa.ForeignKeyConstraint(['scan_id'], ['scans.id'], ondelete='CASCADE'),
+ sa.ForeignKeyConstraint(['sketch_id'], ['sketches.id'], onupdate='CASCADE', ondelete='CASCADE'),
+ sa.PrimaryKeyConstraint('id')
+ )
+ # ### end Alembic commands ###
+
+
+def downgrade() -> None:
+ """Downgrade schema."""
+ # ### commands auto generated by Alembic - please adjust! ###
+ op.drop_table('logs')
+ op.drop_index('investigations_profiles_unique_profile_investigation', table_name='sketches_profiles')
+ op.drop_index('idx_sketches_profiles_sketch_id', table_name='sketches_profiles')
+ op.drop_index('idx_sketches_profiles_profile_id', table_name='sketches_profiles')
+ op.drop_table('sketches_profiles')
+ op.drop_index('idx_scans_sketch_id', table_name='scans')
+ op.drop_table('scans')
+ op.drop_index('idx_sketches_owner_id', table_name='sketches')
+ op.drop_index('idx_sketches_investigation_id', table_name='sketches')
+ op.drop_table('sketches')
+ op.drop_index('projects_profiles_unique_profile_project', table_name='investigations_profiles')
+ op.drop_index('idx_investigations_profiles_profile_id', table_name='investigations_profiles')
+ op.drop_index('idx_investigations_profiles_investigation_id', table_name='investigations_profiles')
+ op.drop_table('investigations_profiles')
+ op.drop_index('idx_investigations_owner_id', table_name='investigations')
+ op.drop_index('idx_investigations_id', table_name='investigations')
+ op.drop_table('investigations')
+ op.drop_table('feedbacks')
+ op.drop_table('transforms')
+ op.drop_table('profiles')
+ # ### end Alembic commands ###
diff --git a/flowsint-api/alembic/versions/d0a8e5b5a7b9_add_relationship_between_investigations_.py b/flowsint-api/alembic/versions/d0a8e5b5a7b9_add_relationship_between_investigations_.py
new file mode 100644
index 00000000..6e15f773
--- /dev/null
+++ b/flowsint-api/alembic/versions/d0a8e5b5a7b9_add_relationship_between_investigations_.py
@@ -0,0 +1,32 @@
+"""Add relationship between investigations and sketches
+
+Revision ID: d0a8e5b5a7b9
+Revises: 40ece72583b7
+Create Date: 2025-05-19 23:57:29.084171
+
+"""
+from typing import Sequence, Union
+
+from alembic import op
+import sqlalchemy as sa
+
+
+# revision identifiers, used by Alembic.
+revision: str = 'd0a8e5b5a7b9'
+down_revision: Union[str, None] = '40ece72583b7'
+branch_labels: Union[str, Sequence[str], None] = None
+depends_on: Union[str, Sequence[str], None] = None
+
+
+def upgrade() -> None:
+ """Upgrade schema."""
+ # ### commands auto generated by Alembic - please adjust! ###
+ pass
+ # ### end Alembic commands ###
+
+
+def downgrade() -> None:
+ """Downgrade schema."""
+ # ### commands auto generated by Alembic - please adjust! ###
+ pass
+ # ### end Alembic commands ###
diff --git a/flowsint-api/app/api/deps.py b/flowsint-api/app/api/deps.py
new file mode 100644
index 00000000..2b132246
--- /dev/null
+++ b/flowsint-api/app/api/deps.py
@@ -0,0 +1,34 @@
+from fastapi import Depends, HTTPException, status
+from fastapi.security import OAuth2PasswordBearer
+from jose import JWTError, jwt
+from sqlalchemy.orm import Session
+from app.core.auth import ALGORITHM
+from app.core.postgre_db import get_db
+from app.models.models import Profile
+
+import os
+from dotenv import load_dotenv
+# Remplace avec ton URL de BDD
+AUTH_SECRET = os.getenv("AUTH_SECRET")
+
+load_dotenv()
+
+oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token")
+
+def get_current_user(token: str = Depends(oauth2_scheme), db: Session = Depends(get_db)) -> Profile:
+ credentials_exception = HTTPException(
+ status_code=status.HTTP_401_UNAUTHORIZED,
+ detail="Could not validate credentials",
+ headers={"WWW-Authenticate": "Bearer"},
+ )
+ try:
+ payload = jwt.decode(token, AUTH_SECRET, algorithms=[ALGORITHM])
+ email: str = payload.get("sub")
+ if email is None:
+ raise credentials_exception
+ except JWTError:
+ raise credentials_exception
+ user = db.query(Profile).filter(Profile.email == email).first()
+ if user is None:
+ raise credentials_exception
+ return user
diff --git a/flowsint-api/app/api/routes/auth.py b/flowsint-api/app/api/routes/auth.py
new file mode 100644
index 00000000..d207841a
--- /dev/null
+++ b/flowsint-api/app/api/routes/auth.py
@@ -0,0 +1,35 @@
+from fastapi import APIRouter, Depends, HTTPException
+from fastapi.security import OAuth2PasswordRequestForm
+from sqlalchemy.orm import Session
+from app.core.auth import verify_password
+from app.core.auth import create_access_token, get_password_hash
+from sqlalchemy.orm import Session
+from app.api.schemas.profile import ProfileCreate
+from app.models.models import Profile
+from app.core.postgre_db import get_db
+
+router = APIRouter()
+
+def login_for_access_token(form_data: OAuth2PasswordRequestForm = Depends(), db: Session = Depends(get_db)):
+ user = db.query(Profile).filter(Profile.email == form_data.username).first()
+ if not user or not verify_password(form_data.password, user.hashed_password):
+ raise HTTPException(status_code=400, detail="Incorrect email or password")
+ access_token = create_access_token(data={"sub": user.email})
+ return {"access_token": access_token, "user_id": user.id, "token_type": "bearer"}
+
[email protected]("/register", status_code=201)
+def register(user: ProfileCreate, db: Session = Depends(get_db)):
+ print(user)
+ existing_user = db.query(Profile).filter(Profile.email == user.email).first()
+ if existing_user:
+ raise HTTPException(status_code=400, detail="Email already registered")
+
+ hashed_password = get_password_hash(user.password)
+ new_user = Profile(email=user.email, hashed_password=hashed_password)
+ db.add(new_user)
+ db.commit()
+ db.refresh(new_user)
+
+
+ return {"message": "User registered successfully", "email": new_user.email}
diff --git a/flowsint-api/app/api/routes/investigations.py b/flowsint-api/app/api/routes/investigations.py
new file mode 100644
index 00000000..8fffb5b8
--- /dev/null
+++ b/flowsint-api/app/api/routes/investigations.py
@@ -0,0 +1,81 @@
+from uuid import UUID, uuid4
+from fastapi import APIRouter, HTTPException, Depends, status
+from typing import List
+from datetime import datetime
+from sqlalchemy.orm import Session, selectinload
+from app.core.postgre_db import get_db
+from app.models.models import Investigation, Profile, Sketch
+from app.api.deps import get_current_user
+from app.api.schemas.investigation import InvestigationRead, InvestigationCreate, InvestigationUpdate
+from app.api.schemas.sketch import SketchRead
+
+router = APIRouter()
+
+# Get the list of all investigations
[email protected]("", response_model=List[InvestigationRead])
+def get_investigations(db: Session = Depends(get_db), current_user: Profile = Depends(get_current_user)):
+ investigations = db.query(Investigation).all()
+ return investigations
+
+# Create a new investigation
[email protected]("/create", response_model=InvestigationRead, status_code=status.HTTP_201_CREATED)
+def create_investigation(payload: InvestigationCreate, db: Session = Depends(get_db), current_user: Profile = Depends(get_current_user)):
+ new_investigation = Investigation(
+ id=uuid4(),
+ name=payload.name,
+ description=payload.description or payload.name,
+ owner_id=current_user.id,
+ status="active",
+ created_at=datetime.utcnow(),
+ last_updated_at=datetime.utcnow(),
+ )
+ db.add(new_investigation)
+ db.commit()
+ db.refresh(new_investigation)
+ return new_investigation
+
+# Get a investigation by ID
[email protected]("/{investigation_id}", response_model=InvestigationRead)
+def get_investigation_by_id(investigation_id: UUID, db: Session = Depends(get_db), current_user: Profile = Depends(get_current_user)):
+ investigation = db.query(Investigation).options(selectinload(Investigation.sketches)).filter(Investigation.id == investigation_id).first()
+ if not investigation:
+ raise HTTPException(status_code=404, detail="Transform not found")
+ return investigation
+
+# Get a investigation by ID
[email protected]("/{investigation_id}/sketches", response_model=List[SketchRead])
+def get_sketches_by_investigation(
+ investigation_id: UUID,
+ db: Session = Depends(get_db),
+ current_user: Profile = Depends(get_current_user)
+):
+ sketches = db.query(Sketch).filter(Sketch.investigation_id == investigation_id).all()
+ if not sketches:
+ raise HTTPException(status_code=404, detail="No sketches found for this investigation")
+ return sketches
+
+# Update a investigation by ID
[email protected]("/{investigation_id}", response_model=InvestigationRead)
+def update_investigation(investigation_id: UUID, payload: InvestigationUpdate, db: Session = Depends(get_db), current_user: Profile = Depends(get_current_user)):
+ investigation = db.query(Investigation).filter(Investigation.id == investigation_id).first()
+ if not investigation:
+ raise HTTPException(status_code=404, detail="Transform not found")
+
+ investigation.name = payload.name
+ investigation.description = payload.description
+ investigation.status = payload.status
+ investigation.last_updated_at = datetime.utcnow()
+
+ db.commit()
+ db.refresh(investigation)
+ return investigation
+
+# Delete a investigation by ID
[email protected]("/{investigation_id}", status_code=status.HTTP_204_NO_CONTENT)
+def delete_investigation(investigation_id: UUID, db: Session = Depends(get_db), current_user: Profile = Depends(get_current_user)):
+ investigation = db.query(Investigation).filter(Investigation.id == investigation_id).first()
+ if not investigation:
+ raise HTTPException(status_code=404, detail="Transform not found")
+ db.delete(investigation)
+ db.commit()
+ return None
diff --git a/flowsint-api/app/api/routes/sketches.py b/flowsint-api/app/api/routes/sketches.py
index 1ed4394f..3f8d4245 100644
--- a/flowsint-api/app/api/routes/sketches.py
+++ b/flowsint-api/app/api/routes/sketches.py
@@ -1,28 +1,63 @@
-from fastapi import APIRouter, HTTPException
+from fastapi import APIRouter, HTTPException, Depends
from pydantic import BaseModel
from typing import Dict, Any, Literal
from fastapi import HTTPException
from pydantic import BaseModel, Field
from app.utils import flatten
-from typing import Dict, Any
-from app.neo4j.connector import Neo4jConnection
-import os
-from dotenv import load_dotenv
-
-
-load_dotenv()
-
-URI = os.getenv("NEO4J_URI_BOLT")
-USERNAME = os.getenv("NEO4J_USERNAME")
-PASSWORD = os.getenv("NEO4J_PASSWORD")
-
-neo4j_connection = Neo4jConnection(URI, USERNAME, PASSWORD)
+from typing import Dict, Any, List
+from sqlalchemy.orm import Session
+from app.api.schemas.sketch import SketchCreate, SketchOut, SketchUpdate
+from app.models.models import Sketch, Profile
+from sqlalchemy.orm import Session
+from uuid import UUID
+from app.core.graph_db import neo4j_connection
+from app.core.postgre_db import get_db
+from app.api.deps import get_current_user
router = APIRouter()
[email protected]("/sketch/{sketch_id}/nodes")
-async def get_sketch_nodes(sketch_id: str):
+
[email protected]("/create", response_model=SketchOut)
+def create_sketch(data: SketchCreate, db: Session = Depends(get_db), current_user: Profile = Depends(get_current_user)):
+ sketch = Sketch(**data.dict())
+ db.add(sketch)
+ db.commit()
+ db.refresh(sketch)
+ return sketch
+
[email protected]("", response_model=List[SketchOut])
+def list_sketches(db: Session = Depends(get_db), current_user: Profile = Depends(get_current_user)):
+ return db.query(Sketch).all()
+
[email protected]("/{id}", response_model=SketchOut)
+def get_sketch(id: UUID, db: Session = Depends(get_db), current_user: Profile = Depends(get_current_user)):
+ sketch = db.query(Sketch).get(id)
+ if not sketch:
+ raise HTTPException(status_code=404, detail="Sketch not found")
+ return sketch
+
[email protected]("/{id}", response_model=SketchOut)
+def update_sketch(id: UUID, data: SketchUpdate, db: Session = Depends(get_db), current_user: Profile = Depends(get_current_user)):
+ sketch = db.query(Sketch).get(id)
+ if not sketch:
+ raise HTTPException(status_code=404, detail="Sketch not found")
+ for key, value in data.dict(exclude_unset=True).items():
+ setattr(sketch, key, value)
+ db.commit()
+ db.refresh(sketch)
+ return sketch
+
[email protected]("/{id}", status_code=204)
+def delete_sketch(id: UUID, db: Session = Depends(get_db), current_user: Profile = Depends(get_current_user)):
+ sketch = db.query(Sketch).get(id)
+ if not sketch:
+ raise HTTPException(status_code=404, detail="Sketch not found")
+ db.delete(sketch)
+ db.commit()
+
[email protected]("/{sketch_id}/graph")
+async def get_sketch_nodes(sketch_id: str, current_user: Profile = Depends(get_current_user)):
import random
nodes_query = """
@@ -79,14 +114,8 @@ class NodeInput(BaseModel):
def dict_to_cypher_props(props: dict, prefix: str = "") -> str:
return ", ".join(f"{key}: ${prefix}{key}" for key in props)
-# Endpoints
[email protected]("/sketches")
-def read_root():
- return {"message": "Sketches API is running"}
-
-
[email protected]("/sketch/{sketch_id}/nodes/add")
-def add_node(sketch_id: str, node: NodeInput):
[email protected]("/{sketch_id}/nodes/add")
+def add_node(sketch_id: str, node: NodeInput, current_user: Profile = Depends(get_current_user)):
node_type = getattr(node, "type", "unknown")
node_data = getattr(node, "data", {})
@@ -138,8 +167,8 @@ class RelationInput(BaseModel):
type: Literal["one-way", "two-way"]
label: str = "RELATED_TO" # Optionnel : nom de la relation
[email protected]("/sketch/{sketch_id}/relations/add")
-def add_edge(sketch_id: str, relation: RelationInput):
[email protected]("/{sketch_id}/relations/add")
+def add_edge(sketch_id: str, relation: RelationInput, current_user: Profile = Depends(get_current_user)):
query = f"""
MATCH (a) WHERE elementId(a) = $from_id
diff --git a/flowsint-api/app/api/routes/transforms.py b/flowsint-api/app/api/routes/transforms.py
index 60b79b85..b5865a9c 100644
--- a/flowsint-api/app/api/routes/transforms.py
+++ b/flowsint-api/app/api/routes/transforms.py
@@ -1,8 +1,10 @@
-from fastapi import APIRouter, HTTPException
+from uuid import UUID, uuid4
+from fastapi import APIRouter, HTTPException, Depends, status, Query
from typing import Dict, List, Any, Optional
from pydantic import BaseModel
import json
-from app.utils import extract_input_schema, extract_transform
+from datetime import datetime
+from app.utils import extract_input_schema
from app.scanners.registry import ScannerRegistry
from app.core.celery import celery_app
from app.types.domain import MinimalDomain
@@ -11,8 +13,11 @@ from app.types.social import MinimalSocial
from app.types.organization import MinimalOrganization
from app.types.email import Email
from app.types.transform import Node, Edge, FlowStep, FlowBranch
-
-from app.core.db import get_db
+from sqlalchemy.orm import Session
+from app.core.postgre_db import get_db
+from app.models.models import Transform, Profile
+from app.api.deps import get_current_user
+from app.api.schemas.transform import TransformRead, TransformCreate, TransformUpdate
class FlowComputationRequest(BaseModel):
nodes: List[Node]
@@ -33,15 +38,22 @@ class LaunchTransformPayload(BaseModel):
router = APIRouter()
-# Endpoints
[email protected]("/transforms")
-def read_root():
- return {"message": "Flow Computation API is running"}
-
[email protected]("/transforms/nodes")
-async def get_scans_list():
+# Get the list of all transforms
[email protected]("", response_model=List[TransformRead])
+def get_transforms(
+ category: Optional[str] = Query(None),
+ db: Session = Depends(get_db),
+ current_user: Profile = Depends(get_current_user)
+):
+ query = db.query(Transform)
+ if category is not None and category != "undefined":
+ query = query.filter(Transform.category.any(category))
+ return query.all()
+
+# Returns the "raw_material" for the transform editor
[email protected]("/raw_materials")
+async def get_scans_list(current_user: Profile = Depends(get_current_user)):
scanners = ScannerRegistry.list_by_category()
-
flattened_scanners = {
category: [
{
@@ -70,19 +82,75 @@ async def get_scans_list():
flattened_scanners["types"] = object_inputs
return {"items": flattened_scanners}
+
+
+# Create a new transform
[email protected]("/create", response_model=TransformRead, status_code=status.HTTP_201_CREATED)
+def create_transform(payload: TransformCreate, db: Session = Depends(get_db), current_user: Profile = Depends(get_current_user)):
+ new_transform = Transform(
+ id=uuid4(),
+ name=payload.name,
+ description=payload.description,
+ category=payload.category,
+ transform_schema=payload.transform_schema,
+ created_at=datetime.utcnow(),
+ last_updated_at=datetime.utcnow(),
+ )
+ db.add(new_transform)
+ db.commit()
+ db.refresh(new_transform)
+ return new_transform
+
+# Get a transform by ID
[email protected]("/{transform_id}", response_model=TransformRead)
+def get_transform_by_id(transform_id: UUID, db: Session = Depends(get_db), current_user: Profile = Depends(get_current_user)):
+ transform = db.query(Transform).filter(Transform.id == transform_id).first()
+ if not transform:
+ raise HTTPException(status_code=404, detail="Transform not found")
+ return transform
+
+# Update a transform by ID
[email protected]("/{transform_id}", response_model=TransformRead)
+def update_transform(transform_id: UUID, payload: TransformUpdate, db: Session = Depends(get_db), current_user: Profile = Depends(get_current_user)):
+ transform = db.query(Transform).filter(Transform.id == transform_id).first()
+ if not transform:
+ raise HTTPException(status_code=404, detail="Transform not found")
[email protected]("/transforms/{transform_id}/launch")
+ transform.name = payload.name
+ transform.description = payload.description
+ transform.category = payload.category
+ transform.transform_schema = payload.transform_schema
+ transform.last_updated_at = datetime.utcnow()
+
+ db.commit()
+ db.refresh(transform)
+ return transform
+
+# Delete a transform by ID
[email protected]("/{transform_id}", status_code=status.HTTP_204_NO_CONTENT)
+def delete_transform(transform_id: UUID, db: Session = Depends(get_db), current_user: Profile = Depends(get_current_user)):
+ transform = db.query(Transform).filter(Transform.id == transform_id).first()
+ if not transform:
+ raise HTTPException(status_code=404, detail="Transform not found")
+ db.delete(transform)
+ db.commit()
+ return None
+
+
[email protected]("/{transform_id}/launch")
async def launch_transform(
transform_id: str,
payload: LaunchTransformPayload,
+ db: Session = Depends(get_db),
+ current_user: Profile = Depends(get_current_user)
):
- db = get_db()
try:
- response = db.table("transforms").select("*").eq("id", str(transform_id)).single().execute()
- if response.data is None:
+ transform = db.query(Transform).filter(Transform.id == transform_id).first()
+ print(transform)
+ if transform is None:
raise HTTPException(status_code=404, detail="Transform not found")
- nodes = [Node(**node) for node in response.data["transform_schema"]["nodes"]]
- edges = [Edge(**edge) for edge in response.data["transform_schema"]["edges"]]
+ nodes = [Node(**node) for node in transform.transform_schema["nodes"]]
+ edges = [Edge(**edge) for edge in transform.transform_schema["edges"]]
transform_branches = compute_transform_branches(
payload.values,
nodes,
@@ -96,28 +164,21 @@ async def launch_transform(
print(e)
raise HTTPException(status_code=404, detail="Transform not found")
[email protected]("/transforms/{transform_id}/compute", response_model=FlowComputationResponse)
-def compute_transforms(request: FlowComputationRequest):
- # Générer les données d'exemple en fonction du type d'entrée
[email protected]("/{transform_id}/compute", response_model=FlowComputationResponse)
+def compute_transforms(request: FlowComputationRequest, current_user: Profile = Depends(get_current_user)):
initial_data = generate_sample_data(request.inputType or "string")
-
- # Calculer les branches de flux
transform_branches = compute_transform_branches(
initial_data,
request.nodes,
request.edges
)
-
return FlowComputationResponse(
transformBranches=transform_branches,
initialData=initial_data
)
-# Fonctions utilitaires
def generate_sample_data(type_str: str) -> Any:
- """Génère des données d'exemple en fonction du type"""
type_str = type_str.lower() if type_str else "string"
-
if type_str == "string":
return "sample_text"
elif type_str == "number":
diff --git a/backend/volumes/db/init/data.sql b/flowsint-api/app/api/schemas/__init__.py
old mode 100755
new mode 100644
similarity index 100%
rename from backend/volumes/db/init/data.sql
rename to flowsint-api/app/api/schemas/__init__.py
diff --git a/flowsint-api/app/api/schemas/base.py b/flowsint-api/app/api/schemas/base.py
new file mode 100644
index 00000000..1823eb11
--- /dev/null
+++ b/flowsint-api/app/api/schemas/base.py
@@ -0,0 +1,6 @@
+from pydantic import BaseModel
+
+
+class ORMBase(BaseModel):
+ class Config:
+ from_attributes = True
diff --git a/flowsint-api/app/api/schemas/feedback.py b/flowsint-api/app/api/schemas/feedback.py
new file mode 100644
index 00000000..32b783ab
--- /dev/null
+++ b/flowsint-api/app/api/schemas/feedback.py
@@ -0,0 +1,14 @@
+from .base import ORMBase
+from pydantic import UUID4, BaseModel
+from typing import Optional
+from datetime import datetime
+
+class FeedbackCreate(BaseModel):
+ content: Optional[str] = None
+ owner_id: Optional[UUID4] = None
+
+class FeedbackRead(ORMBase):
+ id: int
+ created_at: datetime
+ content: Optional[str] = None
+ owner_id: Optional[UUID4]
diff --git a/flowsint-api/app/api/schemas/investigation.py b/flowsint-api/app/api/schemas/investigation.py
new file mode 100644
index 00000000..7680e45e
--- /dev/null
+++ b/flowsint-api/app/api/schemas/investigation.py
@@ -0,0 +1,38 @@
+from .base import ORMBase
+from pydantic import UUID4, BaseModel
+from typing import Optional
+from datetime import datetime
+from .sketch import SketchRead
+class InvestigationCreate(BaseModel):
+ name: str
+ description: str
+ owner_id: Optional[UUID4] = None
+ status: Optional[str] = "active"
+
+class InvestigationRead(ORMBase):
+ id: UUID4
+ created_at: datetime
+ name: str
+ description: str
+ owner_id: Optional[UUID4]
+ last_updated_at: datetime
+ status: str
+ sketches: list[SketchRead] = []
+
+class InvestigationProfileCreate(BaseModel):
+ investigation_id: UUID4
+ profile_id: UUID4
+ role: Optional[str] = "member"
+
+class InvestigationProfileRead(ORMBase):
+ id: int
+ created_at: datetime
+ investigation_id: UUID4
+ profile_id: UUID4
+ role: str
+
+class InvestigationUpdate(BaseModel):
+ name: str
+ description: Optional[str] = None
+ last_updated_at: datetime
+ status: str
diff --git a/flowsint-api/app/api/schemas/investigation_profiles.py b/flowsint-api/app/api/schemas/investigation_profiles.py
new file mode 100644
index 00000000..a9e15346
--- /dev/null
+++ b/flowsint-api/app/api/schemas/investigation_profiles.py
@@ -0,0 +1,16 @@
+from .base import ORMBase
+from pydantic import UUID4, BaseModel
+from typing import Optional
+from datetime import datetime
+
+class InvestigationProfileCreate(BaseModel):
+ investigation_id: UUID4
+ profile_id: UUID4
+ role: Optional[str] = "member"
+
+class InvestigationProfileRead(ORMBase):
+ id: int
+ created_at: datetime
+ investigation_id: UUID4
+ profile_id: UUID4
+ role: str
diff --git a/flowsint-api/app/api/schemas/log.py b/flowsint-api/app/api/schemas/log.py
new file mode 100644
index 00000000..134f4a19
--- /dev/null
+++ b/flowsint-api/app/api/schemas/log.py
@@ -0,0 +1,27 @@
+from uuid import UUID
+from .base import ORMBase
+from pydantic import UUID4, BaseModel
+from typing import Optional
+from datetime import datetime
+
+class LogCreate(BaseModel):
+ scan_id: UUID4
+ content: str
+ sketch_id: Optional[UUID4] = None
+ type: Optional[str] = "INFO"
+
+class LogRead(ORMBase):
+ id: UUID4
+ scan_id: UUID4
+ content: str
+ created_at: datetime
+ sketch_id: Optional[UUID4]
+ type: str
+
+class LogSchema(BaseModel):
+ id: int
+ scan_id: UUID
+ sketch_id: UUID | None = None
+ type: str
+ content: str
+ created_at: datetime
\ No newline at end of file
diff --git a/flowsint-api/app/api/schemas/profile.py b/flowsint-api/app/api/schemas/profile.py
new file mode 100644
index 00000000..fbed722d
--- /dev/null
+++ b/flowsint-api/app/api/schemas/profile.py
@@ -0,0 +1,14 @@
+from .base import ORMBase
+from pydantic import UUID4, BaseModel, EmailStr
+from typing import Optional
+
+class ProfileCreate(BaseModel):
+ email: EmailStr
+ password: str
+
+class ProfileRead(ORMBase):
+ id: UUID4
+ first_name: Optional[str]
+ last_name: Optional[str]
+ avatar_url: Optional[str]
+
diff --git a/flowsint-api/app/api/schemas/scan.py b/flowsint-api/app/api/schemas/scan.py
new file mode 100644
index 00000000..56a87dcc
--- /dev/null
+++ b/flowsint-api/app/api/schemas/scan.py
@@ -0,0 +1,19 @@
+from typing import List, Optional, Any
+from .base import ORMBase
+from pydantic import UUID4, BaseModel
+from typing import Optional
+from datetime import datetime
+
+class ScanCreate(BaseModel):
+ values: Optional[List[str]] = None
+ sketch_id: Optional[UUID4] = None
+ status: Optional[str] = None
+ results: Optional[Any] = None
+
+class ScanRead(ORMBase):
+ id: UUID4
+ created_at: datetime
+ values: Optional[List[str]]
+ sketch_id: Optional[UUID4]
+ status: Optional[str]
+ results: Optional[Any]
diff --git a/flowsint-api/app/api/schemas/sketch.py b/flowsint-api/app/api/schemas/sketch.py
new file mode 100644
index 00000000..6d09c184
--- /dev/null
+++ b/flowsint-api/app/api/schemas/sketch.py
@@ -0,0 +1,62 @@
+from .base import ORMBase
+from pydantic import UUID4, BaseModel
+from typing import Optional
+from datetime import datetime
+from uuid import UUID
+
+class SketchCreate(BaseModel):
+ title: str
+ description: str
+ owner_id: Optional[UUID4] = None
+ investigation_id: UUID4
+ status: Optional[str] = "active"
+
+class SketchRead(ORMBase):
+ id: UUID4
+ title: str
+ description: str
+ created_at: datetime
+ owner_id: Optional[UUID4]
+ investigation_id: UUID4
+ last_updated_at: datetime
+ status: str
+
+class SketchProfileCreate(BaseModel):
+ sketch_id: UUID4
+ profile_id: UUID4
+ role: Optional[str] = "editor"
+
+class SketchProfileRead(ORMBase):
+ id: int
+ created_at: datetime
+ sketch_id: UUID4
+ profile_id: UUID4
+ role: str
+
+class SketchUpdate(BaseModel):
+ title: Optional[str] = None
+ description: Optional[str] = None
+ owner_id: Optional[UUID] = None
+ status: Optional[str] = None
+ investigation_id: Optional[UUID] = None
+
+
+class SketchIn(BaseModel):
+ title: Optional[str] = None
+ description: Optional[str] = None
+ owner_id: Optional[UUID] = None
+ status: Optional[str] = "active"
+ investigation_id: UUID # requis
+
+class SketchOut(BaseModel):
+ id: UUID
+ title: Optional[str]
+ description: Optional[str]
+ created_at: Optional[datetime]
+ owner_id: Optional[UUID]
+ status: Optional[str]
+ investigation_id: UUID
+ last_updated_at: Optional[datetime]
+
+ class Config:
+ from_attributes = True
\ No newline at end of file
diff --git a/flowsint-api/app/api/schemas/transform.py b/flowsint-api/app/api/schemas/transform.py
new file mode 100644
index 00000000..9822dc30
--- /dev/null
+++ b/flowsint-api/app/api/schemas/transform.py
@@ -0,0 +1,26 @@
+from .base import ORMBase
+from pydantic import UUID4, BaseModel
+from typing import Optional
+from datetime import datetime
+from typing import List, Optional, Dict, Any
+
+class TransformCreate(BaseModel):
+ name: str
+ description: Optional[str] = None
+ category: Optional[List[str]] = None
+ transform_schema: Optional[Dict[str, Any]] = None
+
+class TransformRead(ORMBase):
+ id: UUID4
+ name: str
+ description: Optional[str]
+ category: Optional[List[str]]
+ transform_schema: Optional[Dict[str, Any]]
+ created_at: datetime
+ last_updated_at: datetime
+
+class TransformUpdate(BaseModel):
+ name: str
+ description: Optional[str] = None
+ category: Optional[List[str]] = None
+ transform_schema: Optional[Dict[str, Any]] = None
diff --git a/flowsint-api/app/core/auth.py b/flowsint-api/app/core/auth.py
index 40abd9c8..3b1776b4 100644
--- a/flowsint-api/app/core/auth.py
+++ b/flowsint-api/app/core/auth.py
@@ -1,143 +1,26 @@
+from passlib.context import CryptContext
+from datetime import datetime, timedelta
+from jose import jwt
import os
-import requests
-from typing import Dict, Any, Optional
-from fastapi import Depends, HTTPException, status
-from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials
-from jose import jwt, JWTError
from dotenv import load_dotenv
-import json
-from functools import lru_cache
+# Remplace avec ton URL de BDD
+AUTH_SECRET = os.getenv("AUTH_SECRET")
load_dotenv()
+ALGORITHM = "HS256"
+ACCESS_TOKEN_EXPIRE_MINUTES = 60 * 60
-# Chargement des variables d'environnement
-SUPABASE_URL = os.getenv("SUPABASE_URL")
-SUPABASE_JWKS_URL = f"{SUPABASE_URL}/auth/v1/jwks" # URL correcte pour les JWKs
-SUPABASE_ISSUER = f"{SUPABASE_URL}/auth/v1"
-SUPABASE_JWT_SECRET = os.getenv("SUPABASE_JWT_SECRET")
-SUPABASE_KEY = os.getenv("SUPABASE_KEY")
+pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
-http_bearer = HTTPBearer(auto_error=True)
+def verify_password(plain_password: str, hashed_password: str) -> bool:
+ return pwd_context.verify(plain_password, hashed_password)
-@lru_cache(maxsize=1)
-def get_jwks() -> Dict[str, Any]:
- """Récupère les clés JWKS depuis Supabase avec mise en cache."""
- try:
- headers = {"apikey": SUPABASE_KEY} if SUPABASE_KEY else {}
- response = requests.get(SUPABASE_JWKS_URL, headers=headers)
- response.raise_for_status()
- return response.json()
- except requests.RequestException as e:
- # En production, évitez de révéler trop de détails sur l'erreur
- raise HTTPException(
- status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
- detail="Could not fetch JWKS"
- )
+def get_password_hash(password: str) -> str:
+ return pwd_context.hash(password)
-def get_key_from_jwks(token: str) -> Optional[Dict[str, Any]]:
- """Récupère la clé appropriée depuis JWKS en fonction du kid dans le header du JWT."""
- try:
- # Récupérer le header sans vérifier la signature
- header = jwt.get_unverified_header(token)
- kid = header.get("kid")
-
- if not kid:
- return None
-
- # Récupérer les clés JWKS
- jwks = get_jwks()
- for key in jwks.get("keys", []):
- if key.get("kid") == kid:
- return key
-
- return None
- except Exception:
- return None
-
-def verify_token(token: str) -> Dict[str, Any]:
- """
- Vérifie un token JWT de Supabase.
- Essaie d'abord la validation avec JWK (RS256) puis avec secret partagé (HS256).
- """
- # Vérification des entrées
- if not token:
- raise HTTPException(
- status_code=status.HTTP_401_UNAUTHORIZED,
- detail="Missing authentication token"
- )
-
- try:
- # Première tentative: vérification avec JWKS (RS256)
- try:
- jwk = get_key_from_jwks(token)
- if jwk:
- # Si une clé JWK est trouvée, nous utilisons RSA
- public_key = jwt.algorithms.RSAAlgorithm.from_jwk(json.dumps(jwk))
- decoded = jwt.decode(
- token,
- key=public_key,
- algorithms=["RS256"],
- audience="authenticated",
- issuer=SUPABASE_ISSUER,
- )
- return decoded
- except (jwt.JWTError, AttributeError):
- # Échec avec RS256, on essaie avec HS256
- pass
-
- if SUPABASE_JWT_SECRET:
- decoded = jwt.decode(
- token,
- SUPABASE_JWT_SECRET,
- algorithms=["HS256"],
- audience="authenticated",
- issuer=SUPABASE_ISSUER,
- )
- return decoded
-
- # Si on arrive ici, aucune méthode n'a fonctionné
- raise JWTError("Token validation failed")
-
- except jwt.ExpiredSignatureError:
- raise HTTPException(
- status_code=status.HTTP_401_UNAUTHORIZED,
- detail="Token has expired"
- )
- except jwt.JWTClaimsError:
- raise HTTPException(
- status_code=status.HTTP_401_UNAUTHORIZED,
- detail="Invalid claims (audience or issuer)"
- )
- except (jwt.JWTError, JWTError):
- raise HTTPException(
- status_code=status.HTTP_401_UNAUTHORIZED,
- detail="Invalid authentication token"
- )
- except Exception as e:
- # Fallback général
- raise HTTPException(
- status_code=status.HTTP_401_UNAUTHORIZED,
- detail=f"Authentication error: {str(e)}"
- )
-
-def get_current_user(
- credentials: HTTPAuthorizationCredentials = Depends(http_bearer)
-) -> Dict[str, Any]:
- """
- Dependencies to get the current user from the JWT token.
- Usage: user = Depends(get_current_user)
- """
- token = credentials.credentials
- return verify_token(token)
-
-# Fonction utilitaire pour extraire les informations utilisateur du token JWT
-def get_user_info(token_data: Dict[str, Any]) -> Dict[str, Any]:
- """Extracts user infos from the JWT token data."""
- user_info = {
- "user_id": token_data.get("sub"),
- "email": token_data.get("email"),
- "role": token_data.get("role", ""),
- "app_metadata": token_data.get("app_metadata", {}),
- "user_metadata": token_data.get("user_metadata", {})
- }
- return user_info
\ No newline at end of file
+def create_access_token(data: dict, expires_delta: timedelta | None = None):
+ to_encode = data.copy()
+ expire = datetime.utcnow() + (expires_delta or timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES))
+ to_encode.update({"exp": expire})
+ encoded_jwt = jwt.encode(to_encode, AUTH_SECRET, algorithm=ALGORITHM)
+ return encoded_jwt
\ No newline at end of file
diff --git a/flowsint-api/app/core/celery.py b/flowsint-api/app/core/celery.py
index 430000ba..ff9808eb 100644
--- a/flowsint-api/app/core/celery.py
+++ b/flowsint-api/app/core/celery.py
@@ -1,8 +1,18 @@
from celery import Celery
+import os
+from dotenv import load_dotenv
+load_dotenv()
+
+
+REDIS_URI = os.getenv("REDIS_URI")
+
+
+print("REDIS_URI", REDIS_URI)
+
celery_app = Celery(
"flowsint",
- broker="redis://127.0.0.1:6379/0",
- backend="redis://127.0.0.1:6379/0",
+ broker=REDIS_URI,
+ backend=REDIS_URI,
include=["app.tasks.transform"]
)
\ No newline at end of file
diff --git a/flowsint-api/app/core/db.py b/flowsint-api/app/core/db.py
deleted file mode 100644
index 885400e8..00000000
--- a/flowsint-api/app/core/db.py
+++ /dev/null
@@ -1,19 +0,0 @@
-import os
-from dotenv import load_dotenv
-from supabase import create_client, Client
-
-# Charger les variables d'environnement
-load_dotenv()
-
-SUPABASE_URL = os.getenv("SUPABASE_URL")
-SUPABASE_KEY = os.getenv("SUPABASE_KEY")
-
-if not SUPABASE_URL or not SUPABASE_KEY:
- raise ValueError("Missing Supabase credentials")
-
-def get_db(token=None):
-
- supabase_url = os.getenv("SUPABASE_URL")
- supabase_anon_key = os.getenv("SUPABASE_KEY")
- supabase = create_client(supabase_url, supabase_anon_key)
- return supabase
\ No newline at end of file
diff --git a/flowsint-api/app/neo4j/connector.py b/flowsint-api/app/core/graph_db.py
similarity index 63%
rename from flowsint-api/app/neo4j/connector.py
rename to flowsint-api/app/core/graph_db.py
index a678343a..c8e96156 100644
--- a/flowsint-api/app/neo4j/connector.py
+++ b/flowsint-api/app/core/graph_db.py
@@ -1,4 +1,8 @@
+import os
from neo4j import GraphDatabase
+from dotenv import load_dotenv
+
+load_dotenv()
class Neo4jConnection:
def __init__(self, uri: str, user: str, password: str):
@@ -10,4 +14,11 @@ class Neo4jConnection:
def query(self, query: str, parameters: dict = None):
with self.__driver.session() as session:
result = session.run(query, parameters)
- return result.data()
\ No newline at end of file
+ return result.data()
+
+
+URI = os.getenv("NEO4J_URI_BOLT")
+USERNAME = os.getenv("NEO4J_USERNAME")
+PASSWORD = os.getenv("NEO4J_PASSWORD")
+
+neo4j_connection = Neo4jConnection(URI, USERNAME, PASSWORD)
\ No newline at end of file
diff --git a/flowsint-api/app/core/logger.py b/flowsint-api/app/core/logger.py
index ae979284..e85f4d66 100644
--- a/flowsint-api/app/core/logger.py
+++ b/flowsint-api/app/core/logger.py
@@ -1,38 +1,60 @@
-from app.core.db import get_db # Supabase client
-from typing import Literal
from uuid import UUID
+from sqlalchemy.orm import Session
+from typing import Literal
+from datetime import datetime
+from app.models.models import Log
LogLevel = Literal["info", "warn", "error", "success", "debug"]
+LEVEL_MAP = {
+ "info": "INFO",
+ "warn": "WARN",
+ "error": "ERROR",
+ "success": "SUCCESS",
+ "debug": "DEBUG",
+}
+
+
class Logger:
- def __init__(self, db):
+ def __init__(self, db: Session):
self.db = db
- def emit(self, scan_id: UUID, sketch_id: UUID, content: str, level: LogLevel = "info"):
- data = {
- "scan_id": str(scan_id),
- "sketch_id": str(sketch_id),
- "type": level.upper(),
- "content": f"[{level.upper()}] {content}",
- }
+ def emit(
+ self,
+ scan_id: UUID,
+ content: str,
+ sketch_id: UUID | None = None,
+ level: LogLevel = "info",
+ ):
+ level_str = LEVEL_MAP.get(level, "INFO")
+
+ log = Log(
+ scan_id=scan_id,
+ sketch_id=sketch_id,
+ type=level_str,
+ content=f"[{level_str}] {content}",
+ created_at=datetime.utcnow(), # si ton modèle n’a pas de default server-side
+ )
+
try:
- self.db.table("logs").insert(data).execute()
+ self.db.add(log)
+ self.db.commit()
+ print(f"[{level_str}] {content}")
except Exception as e:
+ self.db.rollback()
print(f"[Logger] Failed to emit log: {e}")
- def info(self, scan_id: UUID, sketch_id: UUID, content: str):
- self.emit(scan_id, sketch_id, content, level="info")
+ def info(self, scan_id: UUID, content: str, sketch_id: UUID | None = None):
+ self.emit(scan_id, content, sketch_id, level="info")
- def warn(self, scan_id: UUID, sketch_id: UUID, content: str):
- self.emit(scan_id, sketch_id, content, level="warning")
+ def warn(self, scan_id: UUID, content: str, sketch_id: UUID | None = None):
+ self.emit(scan_id, content, sketch_id, level="warn")
- def error(self, scan_id: UUID, sketch_id: UUID, content: str):
- self.emit(scan_id, sketch_id, content, level="error")
+ def error(self, scan_id: UUID, content: str, sketch_id: UUID | None = None):
+ self.emit(scan_id, content, sketch_id, level="error")
- def success(self, scan_id: UUID, sketch_id: UUID, content: str):
- self.emit(scan_id, sketch_id, content, level="success")
-
- def debug(self, scan_id: UUID, sketch_id: UUID, content: str):
- self.emit(scan_id, sketch_id, content, level="debug")
+ def success(self, scan_id: UUID, content: str, sketch_id: UUID | None = None):
+ self.emit(scan_id, content, sketch_id, level="success")
-logger = Logger(get_db())
+ def debug(self, scan_id: UUID, content: str, sketch_id: UUID | None = None):
+ self.emit(scan_id, content, sketch_id, level="debug")
diff --git a/flowsint-api/app/core/postgre_db.py b/flowsint-api/app/core/postgre_db.py
new file mode 100644
index 00000000..a6f41c53
--- /dev/null
+++ b/flowsint-api/app/core/postgre_db.py
@@ -0,0 +1,21 @@
+from sqlalchemy import create_engine
+from sqlalchemy.orm import sessionmaker, declarative_base, Session
+import os
+from dotenv import load_dotenv
+# Remplace avec ton URL de BDD
+DATABASE_URL = os.getenv("DATABASE_URL")
+
+load_dotenv()
+
+engine = create_engine(DATABASE_URL, pool_pre_ping=True)
+SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
+
+Base = declarative_base()
+
+
+def get_db() -> Session:
+ db = SessionLocal()
+ try:
+ yield db
+ finally:
+ db.close()
\ No newline at end of file
diff --git a/flowsint-api/app/main.py b/flowsint-api/app/main.py
index d20e0287..ddc6820f 100644
--- a/flowsint-api/app/main.py
+++ b/flowsint-api/app/main.py
@@ -1,12 +1,19 @@
-from fastapi import FastAPI
+from fastapi import FastAPI, Depends
from app.scanners.registry import ScannerRegistry
-from app.neo4j.connector import Neo4jConnection
+from app.core.graph_db import Neo4jConnection
import os
+from typing import List
from dotenv import load_dotenv
from fastapi.middleware.cors import CORSMiddleware
-from app.api.routes import transforms
+# Routes to be included
+from app.api.routes import auth
+from app.api.routes import investigations
from app.api.routes import sketches
-
+from app.api.routes import transforms
+from sqlalchemy.orm import Session
+from app.core.postgre_db import get_db
+from app.api.schemas.log import LogSchema
+from app.models.models import Log
load_dotenv()
URI = os.getenv("NEO4J_URI_BOLT")
@@ -30,15 +37,13 @@ neo4j_connection = Neo4jConnection(URI, USERNAME, PASSWORD)
app.add_middleware(
CORSMiddleware,
- allow_origins=origins, # Ou ["*"] pour tout autoriser en dev
+ allow_origins=origins,
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
-app.include_router(transforms.router, prefix="/api", tags=["branches"])
-app.include_router(sketches.router, prefix="/api", tags=["branches"])
-
[email protected]("/scanners")
-async def get_scans_list():
- return {"scanners": ScannerRegistry.list()}
+app.include_router(auth.router, prefix="/api/auth", tags=["auth"])
+app.include_router(sketches.router, prefix="/api/sketches", tags=["sketches"])
+app.include_router(investigations.router, prefix="/api/investigations", tags=["investigations"])
+app.include_router(transforms.router, prefix="/api/transforms", tags=["transforms"])
diff --git a/flowsint-api/app/models/__init__.py b/flowsint-api/app/models/__init__.py
new file mode 100644
index 00000000..e69de29b
diff --git a/flowsint-api/app/models/base.py b/flowsint-api/app/models/base.py
new file mode 100644
index 00000000..f75ec448
--- /dev/null
+++ b/flowsint-api/app/models/base.py
@@ -0,0 +1,4 @@
+from sqlalchemy.orm import DeclarativeBase
+
+class Base(DeclarativeBase):
+ pass
diff --git a/flowsint-api/app/models/models.py b/flowsint-api/app/models/models.py
new file mode 100644
index 00000000..71bb501b
--- /dev/null
+++ b/flowsint-api/app/models/models.py
@@ -0,0 +1,138 @@
+import uuid
+
+from sqlalchemy import (
+ String, Text, DateTime, ForeignKey,
+ Index, func, text, JSON
+)
+from sqlalchemy.dialects.postgresql import UUID as PGUUID, ARRAY
+from sqlalchemy.orm import Mapped, mapped_column, relationship
+
+from .base import Base
+
+
+class Feedback(Base):
+ __tablename__ = "feedbacks"
+
+ id: Mapped[uuid.UUID] = mapped_column(primary_key=True)
+ created_at = mapped_column(DateTime(timezone=True), server_default=func.now())
+ content = mapped_column(Text, nullable=True)
+ owner_id = mapped_column(PGUUID(as_uuid=True), ForeignKey("profiles.id"), nullable=True)
+
+
+class Investigation(Base):
+ __tablename__ = "investigations"
+
+ id: Mapped[uuid.UUID] = mapped_column(PGUUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
+ created_at = mapped_column(DateTime(timezone=True), server_default=func.now())
+ name = mapped_column(Text)
+ description = mapped_column(Text)
+ owner_id = mapped_column(PGUUID(as_uuid=True), ForeignKey("profiles.id", onupdate="CASCADE", ondelete="CASCADE"), nullable=True)
+ last_updated_at = mapped_column(DateTime(timezone=True), server_default=func.now())
+ status = mapped_column(String, server_default='active')
+ sketches = relationship("Sketch", back_populates="investigation")
+ __table_args__ = (
+ Index("idx_investigations_id", "id"),
+ Index("idx_investigations_owner_id", "owner_id"),
+ )
+
+
+class InvestigationsProfiles(Base):
+ __tablename__ = "investigations_profiles"
+
+ id: Mapped[uuid.UUID] = mapped_column(primary_key=True)
+ created_at = mapped_column(DateTime(timezone=True), server_default=func.now())
+ investigation_id = mapped_column(PGUUID(as_uuid=True), ForeignKey("investigations.id", onupdate="CASCADE", ondelete="CASCADE"))
+ profile_id = mapped_column(PGUUID(as_uuid=True), ForeignKey("profiles.id", onupdate="CASCADE", ondelete="CASCADE"))
+ role = mapped_column(String, server_default="member")
+
+ __table_args__ = (
+ Index("idx_investigations_profiles_investigation_id", "investigation_id"),
+ Index("idx_investigations_profiles_profile_id", "profile_id"),
+ # Uniqueness constraint
+ Index("projects_profiles_unique_profile_project", "profile_id", "investigation_id", unique=True),
+ )
+
+
+class Log(Base):
+ __tablename__ = "logs"
+
+ id: Mapped[uuid.UUID] = mapped_column(PGUUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
+ scan_id = mapped_column(PGUUID(as_uuid=True), ForeignKey("scans.id", ondelete="CASCADE"))
+ content = mapped_column(Text)
+ created_at = mapped_column(DateTime(timezone=True), server_default=func.now())
+ sketch_id = mapped_column(PGUUID(as_uuid=True), ForeignKey("sketches.id", onupdate="CASCADE", ondelete="CASCADE"), nullable=True)
+ type = mapped_column(String, server_default="INFO")
+
+
+class Profile(Base):
+ __tablename__ = "profiles"
+
+ id: Mapped[uuid.UUID] = mapped_column(PGUUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
+ first_name = mapped_column(Text, nullable=True)
+ last_name = mapped_column(Text, nullable=True)
+ avatar_url = mapped_column(Text, nullable=True)
+ email: Mapped[str] = mapped_column(String, unique=True, nullable=False)
+ hashed_password: Mapped[str] = mapped_column(String, nullable=False)
+ is_active: Mapped[bool] = mapped_column(default=True)
+
+
+class Scan(Base):
+ __tablename__ = "scans"
+
+ id: Mapped[uuid.UUID] = mapped_column(PGUUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
+ created_at = mapped_column(DateTime(timezone=True), server_default=func.now())
+ status = mapped_column(String, nullable=True)
+ results = mapped_column(JSON, nullable=True)
+ values = mapped_column(ARRAY(Text), nullable=True)
+ sketch_id = mapped_column(PGUUID(as_uuid=True), ForeignKey("sketches.id", onupdate="CASCADE", ondelete="CASCADE"), nullable=True)
+
+ __table_args__ = (
+ Index("idx_scans_sketch_id", "sketch_id"),
+ )
+
+
+class Sketch(Base):
+ __tablename__ = "sketches"
+
+ id: Mapped[uuid.UUID] = mapped_column(PGUUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
+ title = mapped_column(Text)
+ description = mapped_column(Text)
+ created_at = mapped_column(DateTime(timezone=True), server_default=func.now())
+ owner_id = mapped_column(PGUUID(as_uuid=True), ForeignKey("profiles.id", onupdate="CASCADE", ondelete="CASCADE"), nullable=True)
+ status = mapped_column(String, server_default="active")
+ investigation_id = mapped_column(PGUUID(as_uuid=True), ForeignKey("investigations.id", onupdate="CASCADE", ondelete="CASCADE"))
+ investigation = relationship("Investigation", back_populates="sketches")
+ last_updated_at = mapped_column(DateTime(timezone=True), server_default=func.now())
+
+ __table_args__ = (
+ Index("idx_sketches_investigation_id", "investigation_id"),
+ Index("idx_sketches_owner_id", "owner_id"),
+ )
+
+
+class SketchesProfiles(Base):
+ __tablename__ = "sketches_profiles"
+
+ id: Mapped[uuid.UUID] = mapped_column(primary_key=True)
+ created_at = mapped_column(DateTime(timezone=True), server_default=func.now())
+ profile_id = mapped_column(PGUUID(as_uuid=True), ForeignKey("profiles.id", onupdate="CASCADE", ondelete="CASCADE"))
+ sketch_id = mapped_column(PGUUID(as_uuid=True), ForeignKey("sketches.id", onupdate="CASCADE", ondelete="CASCADE"))
+ role = mapped_column(String, server_default="editor")
+
+ __table_args__ = (
+ Index("idx_sketches_profiles_sketch_id", "sketch_id"),
+ Index("idx_sketches_profiles_profile_id", "profile_id"),
+ Index("investigations_profiles_unique_profile_investigation", "profile_id", "sketch_id", unique=True),
+ )
+
+
+class Transform(Base):
+ __tablename__ = "transforms"
+
+ id: Mapped[uuid.UUID] = mapped_column(PGUUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
+ name = mapped_column(Text, nullable=False)
+ description = mapped_column(Text, nullable=True)
+ category = mapped_column(ARRAY(Text), nullable=True)
+ transform_schema = mapped_column(JSON, nullable=True)
+ created_at = mapped_column(DateTime(timezone=True), server_default=func.now())
+ last_updated_at = mapped_column(DateTime(timezone=True), server_default=func.now())
\ No newline at end of file
diff --git a/flowsint-api/app/scanners/base.py b/flowsint-api/app/scanners/base.py
index ceee4292..c7d0ba36 100644
--- a/flowsint-api/app/scanners/base.py
+++ b/flowsint-api/app/scanners/base.py
@@ -1,76 +1,63 @@
from abc import ABC, abstractmethod
-from typing import List, Dict, Any
-from app.neo4j.connector import Neo4jConnection
-from app.core.logger import logger
+from typing import List, Dict, Any, Optional
+from app.core.graph_db import Neo4jConnection
+from app.core.logger import Logger
class Scanner(ABC):
- def __init__(self, sketch_id:str, scan_id: str, neo4j_conn: Neo4jConnection = None):
+ def __init__(
+ self,
+ sketch_id: Optional[str],
+ scan_id: str,
+ logger: Logger,
+ neo4j_conn: Optional[Neo4jConnection] = None,
+ ):
self.scan_id = scan_id
self.sketch_id = sketch_id or "system"
- self.neo4j_conn = neo4j_conn # disponible dans tous les scanners
-
+ self.neo4j_conn = neo4j_conn
+ self.logger = logger
+
@classmethod
@abstractmethod
- def name(self) -> str:
+ def name(cls) -> str:
pass
-
+
@classmethod
@abstractmethod
- def category(self) -> str:
+ def category(cls) -> str:
pass
-
+
@classmethod
@abstractmethod
def input_schema(cls) -> Dict[str, str]:
- """
- Returns the input fields and their types.
- """
pass
@classmethod
@abstractmethod
def output_schema(cls) -> Dict[str, str]:
- """
- Returns the output fields and their types.
- """
pass
-
+
@abstractmethod
def scan(self, values: List[str]) -> List[Dict[str, Any]]:
- """
- The actual scanning logic that operates on the list of values provided.
- """
pass
-
+
def preprocess(self, values: List[str]) -> List[str]:
- """
- Preprocess the values according to their types.
- Validates if the values match the expected format for the given types.
- """
return values
-
+
def postprocess(self, results: List[Dict[str, Any]], input_data: List[str] = None) -> List[Dict[str, Any]]:
- """
- Post-process the scan results if necessary (e.g., format them).
- """
return results
-
+
def execute(self, values: List[str]) -> List[Dict[str, Any]]:
- """
- Execute the scanning process by first preprocessing, then scanning, and finally postprocessing.
- Tries to call postprocess with (results, preprocessed). Falls back to (results) if needed.
- """
if self.name() != "transform_orchestrator":
- logger.info(self.scan_id,self.sketch_id, f"Scanner {self.name()} started.")
- preprocessed = self.preprocess(values)
- results = self.scan(preprocessed)
- processed = self.postprocess(results, preprocessed)
+ self.logger.info(self.scan_id, f"Scanner {self.name()} started.", self.sketch_id)
+
try:
+ preprocessed = self.preprocess(values)
+ results = self.scan(preprocessed)
+ processed = self.postprocess(results, preprocessed)
if self.name() != "transform_orchestrator":
- logger.success(self.scan_id,self.sketch_id, f"Scanner {self.name()} finished.")
+ self.logger.success(self.scan_id, f"Scanner {self.name()} finished.", self.sketch_id)
return processed
except Exception as e:
if self.name() != "transform_orchestrator":
- logger.error(self.scan_id,self.sketch_id, f"Scanner {self.name()} errored: '{str(e)}'.")
- return processed
-
+ self.logger.error(self.scan_id, f"Scanner {self.name()} errored: '{str(e)}'.", self.sketch_id)
+ return []
diff --git a/flowsint-api/app/scanners/domains/resolve.py b/flowsint-api/app/scanners/domains/resolve.py
index 0b1588b3..d20d8eff 100644
--- a/flowsint-api/app/scanners/domains/resolve.py
+++ b/flowsint-api/app/scanners/domains/resolve.py
@@ -5,7 +5,6 @@ from app.scanners.base import Scanner
from app.types.domain import MinimalDomain
from app.types.ip import MinimalIp
from app.utils import is_valid_domain, resolve_type
-from app.core.logger import logger
InputType: TypeAlias = List[MinimalDomain]
OutputType: TypeAlias = List[MinimalIp]
diff --git a/flowsint-api/app/scanners/domains/subdomains.py b/flowsint-api/app/scanners/domains/subdomains.py
index 47e7c052..1f93e979 100644
--- a/flowsint-api/app/scanners/domains/subdomains.py
+++ b/flowsint-api/app/scanners/domains/subdomains.py
@@ -6,7 +6,6 @@ from app.scanners.base import Scanner
from app.types.domain import MinimalDomain, Domain
from app.utils import is_valid_domain, resolve_type
from pydantic import TypeAdapter
-from app.core.logger import logger
InputType: TypeAlias = List[MinimalDomain]
OutputType: TypeAlias = List[MinimalDomain]
@@ -55,7 +54,7 @@ class SubdomainScanner(Scanner):
def preprocess(self, data: Union[List[str], List[dict], InputType]) -> InputType:
cleaned: InputType = []
- logger.debug(self.scan_id, self.sketch_id,f"[SUBDOMAIN_SCANNER]: preprocessed: {str(data)}")
+ self.logger.debug(self.scan_id, self.sketch_id,f"[SUBDOMAIN_SCANNER]: preprocessed: {str(data)}")
for item in data:
domain_obj = None
if isinstance(item, str):
@@ -66,24 +65,24 @@ class SubdomainScanner(Scanner):
domain_obj = item
if domain_obj and is_valid_domain(domain_obj.domain) != "invalid":
cleaned.append(domain_obj)
- logger.debug(self.scan_id, self.sketch_id,f"[SUBDOMAIN_SCANNER]: postprocessed: {str(cleaned)}")
+ self.logger.debug(self.scan_id, self.sketch_id,f"[SUBDOMAIN_SCANNER]: postprocessed: {str(cleaned)}")
return cleaned
def scan(self, data: InputType) -> OutputType:
"""Find subdomains using subfinder (if available) or fallback to crt.sh."""
domains: OutputType = []
use_subfinder = self.__is_subfinder_installed()
- logger.debug(self.scan_id, self.sketch_id,f"[SUBDOMAIN_SCANNER]: input data: {str(data)}")
+ self.logger.debug(self.scan_id, self.sketch_id,f"[SUBDOMAIN_SCANNER]: input data: {str(data)}")
for md in data:
d = Domain(domain=md.domain)
if use_subfinder:
subdomains = self.__get_subdomains_from_subfinder(d.domain)
if not subdomains:
- logger.warn(self.scan_id, self.sketch_id, f"subfinder failed for {d.domain}, falling back to crt.sh")
+ self.logger.warn(self.scan_id, self.sketch_id, f"subfinder failed for {d.domain}, falling back to crt.sh")
subdomains = self.__get_subdomains_from_crtsh(d.domain)
else:
- logger.info(self.scan_id, self.sketch_id, "subfinder not found, using crt.sh only")
+ self.logger.info(self.scan_id, self.sketch_id, "subfinder not found, using crt.sh only")
subdomains = self.__get_subdomains_from_crtsh(d.domain)
d.subdomains = sorted(subdomains)
@@ -110,9 +109,9 @@ class SubdomainScanner(Scanner):
if "*" not in sub and is_valid_domain(sub) and sub.endswith(domain) and sub != domain:
subdomains.add(sub)
elif "*" in sub:
- logger.debug(self.scan_id, self.sketch_id, f"Ignored wildcard subdomain: {sub}")
+ self.logger.debug(self.scan_id, self.sketch_id, f"Ignored wildcard subdomain: {sub}")
except Exception as e:
- logger.error(self.scan_id, self.sketch_id, f"crt.sh failed for {domain}: {e}")
+ self.logger.error(self.scan_id, self.sketch_id, f"crt.sh failed for {domain}: {e}")
return subdomains
def __get_subdomains_from_subfinder(self, domain: str) -> set[str]:
@@ -128,9 +127,9 @@ class SubdomainScanner(Scanner):
if is_valid_domain(sub) and sub.endswith(domain) and sub != domain and not sub.startswith("."):
subdomains.add(sub)
else:
- logger.error(self.scan_id, self.sketch_id, f"subfinder failed for {domain}: {result.stderr.strip()}")
+ self.logger.error(self.scan_id, self.sketch_id, f"subfinder failed for {domain}: {result.stderr.strip()}")
except Exception as e:
- logger.error(self.scan_id, self.sketch_id, f"subfinder exception for {domain}: {e}")
+ self.logger.error(self.scan_id, self.sketch_id, f"subfinder exception for {domain}: {e}")
return subdomains
def postprocess(self, results: OutputType, original_input: InputType) -> OutputType:
@@ -156,6 +155,6 @@ class SubdomainScanner(Scanner):
"caption": subdomain,
"type": "subdomain"
})
- logger.info(self.scan_id, self.sketch_id, f"{domain_obj.domain} -> {len(domain_obj.subdomains)} subdomain(s) found.")
+ self.logger.info(self.scan_id, self.sketch_id, f"{domain_obj.domain} -> {len(domain_obj.subdomains)} subdomain(s) found.")
return output
diff --git a/flowsint-api/app/scanners/emails/holehe.py b/flowsint-api/app/scanners/emails/holehe.py
index 230acc93..408085ae 100644
--- a/flowsint-api/app/scanners/emails/holehe.py
+++ b/flowsint-api/app/scanners/emails/holehe.py
@@ -5,8 +5,6 @@ from app.types.social import Social
from pydantic import TypeAdapter
from app.utils import is_valid_email, resolve_type
import asyncio
-from app.core.logger import logger
-
InputType: TypeAlias = List[Email]
OutputType: TypeAlias = List[Social]
@@ -136,7 +134,7 @@ class HoleheScanner(Scanner):
return results
for profile in results:
- logger.info(self.scan_id, self.sketch_id, f"{profile.username} -> account found on {profile.platform}")
+ self.logger.info(self.scan_id, self.sketch_id, f"{profile.username} -> account found on {profile.platform}")
self.neo4j_conn.query("""
MERGE (p:social_profile {profile_url: $profile_url})
SET p.platform = $platform,
diff --git a/flowsint-api/app/scanners/ips/reverse_resolve.py b/flowsint-api/app/scanners/ips/reverse_resolve.py
index 0f3643d5..d2711082 100644
--- a/flowsint-api/app/scanners/ips/reverse_resolve.py
+++ b/flowsint-api/app/scanners/ips/reverse_resolve.py
@@ -9,7 +9,6 @@ from app.scanners.base import Scanner
from app.types.domain import MinimalDomain
from app.types.ip import MinimalIp
from app.utils import resolve_type, is_valid_ip
-from app.core.logger import logger
InputType: TypeAlias = List[MinimalIp]
OutputType: TypeAlias = List[MinimalDomain]
@@ -142,7 +141,7 @@ class ReverseResolveScanner(Scanner):
def postprocess(self, results: OutputType, original_input: InputType) -> OutputType:
for domain_obj, ip_obj in zip(original_input, results):
- logger.success(self.scan_id, self.sketch_id, f"Resolved {ip_obj.address} to {domain_obj.domain}")
+ self.logger.success(self.scan_id, self.sketch_id, f"Resolved {ip_obj.address} to {domain_obj.domain}")
query = """
MERGE (d:ip {ip: $ip})
SET d.sketch_id = $sketch_id
diff --git a/flowsint-api/app/scanners/orchestrator.py b/flowsint-api/app/scanners/orchestrator.py
index df7174d3..76a69f36 100644
--- a/flowsint-api/app/scanners/orchestrator.py
+++ b/flowsint-api/app/scanners/orchestrator.py
@@ -4,14 +4,13 @@ from datetime import datetime
from pydantic import BaseModel, ValidationError
from app.scanners.base import Scanner
from app.scanners.registry import ScannerRegistry
-from app.core.logger import logger
from app.types.transform import FlowBranch, FlowStep
+from app.core.logger import Logger
class TransformOrchestrator(Scanner):
- def __init__(self, sketch_id: str, scan_id: str, transform_branches: List[FlowBranch], neo4j_conn=None):
- super().__init__(sketch_id, scan_id, neo4j_conn=neo4j_conn)
+ def __init__(self, sketch_id: str, scan_id: str, transform_branches: List[FlowBranch],logger: Logger, neo4j_conn=None ):
+ super().__init__(sketch_id, scan_id, neo4j_conn=neo4j_conn, logger=logger)
self.transform_branches = transform_branches
- self.neo4j_conn = neo4j_conn
self.scanners = {} # Map of nodeId -> scanner instance
self._load_scanners()
@@ -40,21 +39,21 @@ class TransformOrchestrator(Scanner):
if not ScannerRegistry.scanner_exists(scanner_name):
raise ValueError(f"Scanner '{scanner_name}' not found in registry")
- scanner = ScannerRegistry.get_scanner(scanner_name, self.sketch_id, self.scan_id, neo4j_conn=self.neo4j_conn)
+ scanner = ScannerRegistry.get_scanner(scanner_name, self.sketch_id, self.scan_id, neo4j_conn=self.neo4j_conn, logger=self.logger)
self.scanners[node_id] = scanner
# Log the execution plan for debugging
- # self.log_execution_plan()
+ self.log_execution_plan()
def log_execution_plan(self):
"""Log the execution plan for debugging purposes"""
- logger.info(self.scan_id, self.sketch_id, "Workflow execution plan:")
+ self.logger.info(self.scan_id, self.sketch_id, "Workflow execution plan:")
for branch_idx, branch in enumerate(self.transform_branches):
branch_id = branch.id
branch_name = branch.name
- logger.info(self.scan_id, self.sketch_id, f"Branch: {branch_name} (ID: {branch_id})")
+ self.logger.info(self.scan_id, self.sketch_id, f"Branch: {branch_name} (ID: {branch_id})")
steps = branch.steps
for step_idx, step in enumerate(steps):
@@ -66,10 +65,10 @@ class TransformOrchestrator(Scanner):
inputs_str = ', '.join([f"{k}: {v}" for k, v in step.inputs.items()])
outputs_str = ', '.join([f"{k}: {v}" for k, v in step.outputs.items()])
- logger.info(self.scan_id, self.sketch_id,
+ self.logger.info(self.scan_id, self.sketch_id,
f" Step {step_idx+1}: {scanner_name} (Depth: {depth})")
- logger.info(self.scan_id, self.sketch_id, f" Inputs: {inputs_str}")
- logger.info(self.scan_id, self.sketch_id, f" Outputs: {outputs_str}")
+ self.logger.info(self.scan_id, self.sketch_id, f" Inputs: {inputs_str}")
+ self.logger.info(self.scan_id, self.sketch_id, f" Outputs: {outputs_str}")
def resolve_reference(self, ref_value: str, results_mapping: Dict[str, Any]) -> Any:
"""
@@ -178,7 +177,7 @@ class TransformOrchestrator(Scanner):
scanner = self.scanners.get(node_id)
if not scanner:
- logger.error(self.scan_id, self.sketch_id, f"Scanner not found for node {node_id}")
+ self.logger.error(self.scan_id, self.sketch_id, f"Scanner not found for node {node_id}")
continue
scanner_name = scanner.name()
@@ -191,22 +190,22 @@ class TransformOrchestrator(Scanner):
try:
# Prepare inputs for this scanner
# scanner_inputs = self.prepare_scanner_inputs(step, results_mapping, values)
- # logger.debug(self.scan_id, self.sketch_id,f"Current values to be used: {str(scanner_inputs)}")
+ # self.logger.debug(self.scan_id, self.sketch_id,f"Current values to be used: {str(scanner_inputs)}")
if not scanner_inputs:
- logger.warn(self.scan_id, self.sketch_id,
+ self.logger.warn(self.scan_id, self.sketch_id,
f"No inputs available for scanner {scanner_name}, skipping")
step_result["error"] = "No inputs available"
branch_results["steps"].append(step_result)
continue
- # logger.info(self.scan_id, self.sketch_id,
+ # self.logger.info(self.scan_id, self.sketch_id,
# f"Running scanner {scanner_name} with inputs: {str(scanner_inputs)}")
# Execute the scanner
outputs = scanner.execute(scanner_inputs)
if not isinstance(outputs, (dict, list)):
raise ValueError(f"Scanner '{scanner_name}' returned unsupported output format")
- logger.success(self.scan_id, self.sketch_id, f"Found {str(len(outputs))} for scanner {scanner.name()}")
+ self.logger.success(self.scan_id, self.sketch_id, f"Found {str(len(outputs))} for scanner {scanner.name()}")
# Convert outputs to JSON-serializable format
# outputs = self.results_to_json(outputs)
@@ -223,13 +222,13 @@ class TransformOrchestrator(Scanner):
except ValidationError as e:
error_msg = f"Validation error: {str(e)}"
- logger.error(self.scan_id, self.sketch_id, f"Validation error in {scanner_name}: {str(e)}")
+ self.logger.error(self.scan_id, self.sketch_id, f"Validation error in {scanner_name}: {str(e)}")
step_result["error"] = error_msg
results["results"][node_id] = {"error": error_msg}
except Exception as e:
error_msg = f"Error during scan: {str(e)}"
- logger.error(self.scan_id, self.sketch_id, f"Error during scan {scanner_name}: {str(e)}")
+ self.logger.error(self.scan_id, self.sketch_id, f"Error during scan {scanner_name}: {str(e)}")
step_result["error"] = error_msg
results["results"][node_id] = {"error": error_msg}
diff --git a/flowsint-api/app/scanners/socials/maigret.py b/flowsint-api/app/scanners/socials/maigret.py
index 9d55ff15..5aa04d30 100644
--- a/flowsint-api/app/scanners/socials/maigret.py
+++ b/flowsint-api/app/scanners/socials/maigret.py
@@ -7,7 +7,6 @@ from app.utils import is_valid_username, resolve_type
from app.scanners.base import Scanner
from app.types.social import MinimalSocial, Social
from pydantic import TypeAdapter
-from app.core.logger import logger
InputType: TypeAlias = List[MinimalSocial]
OutputType: TypeAlias = List[Social]
@@ -148,7 +147,7 @@ class MaigretScanner(Scanner):
return results
for profile in results:
- logger.info(self.scan_id, self.sketch_id, f"{profile.username} -> account found on {profile.platform}")
+ self.logger.info(self.scan_id, self.sketch_id, f"{profile.username} -> account found on {profile.platform}")
self.neo4j_conn.query("""
MERGE (p:social_profile {profile_url: $profile_url})
SET p.username = $username,
diff --git a/flowsint-api/app/tasks/transform.py b/flowsint-api/app/tasks/transform.py
index 6d85765d..9ad0ee31 100644
--- a/flowsint-api/app/tasks/transform.py
+++ b/flowsint-api/app/tasks/transform.py
@@ -1,14 +1,17 @@
-from app.core.celery import celery_app
-from app.scanners.orchestrator import TransformOrchestrator
-from celery import states
-from app.core.db import get_db
-from typing import List
import os
+import uuid
from dotenv import load_dotenv
from typing import List
-from app.neo4j.connector import Neo4jConnection
-from app.types.transform import FlowBranch
+from celery import states
+from app.core.celery import celery_app
+from app.scanners.orchestrator import TransformOrchestrator
+from app.core.postgre_db import SessionLocal, get_db
+from app.core.graph_db import Neo4jConnection
+from app.types.transform import FlowBranch
+from app.models.models import Scan
+from sqlalchemy.orm import Session
+from app.core.logger import Logger
load_dotenv()
URI = os.getenv("NEO4J_URI_BOLT")
@@ -16,42 +19,58 @@ USERNAME = os.getenv("NEO4J_USERNAME")
PASSWORD = os.getenv("NEO4J_PASSWORD")
neo4j_connection = Neo4jConnection(URI, USERNAME, PASSWORD)
+db: Session = next(get_db())
+logger = Logger(db)
@celery_app.task(name="run_transform", bind=True)
def run_scan(self, transform_branches, values: List[str], sketch_id: str | None):
- db = get_db()
+ session = SessionLocal()
try:
if not transform_branches:
raise ValueError("transform_branches not provided in the input transform")
-
- res = db.table("scans").insert({
- "id": self.request.id,
- "status": "pending",
- "values": values,
- "sketch_id": sketch_id,
- "results": []
- }).execute()
- scan_id = res.data[0]["id"]
-
+
+ scan_id = uuid.UUID(self.request.id)
+
+ scan = Scan(
+ id=scan_id,
+ status="pending",
+ values=values,
+ sketch_id=uuid.UUID(sketch_id) if sketch_id else None,
+ results={}
+ )
+ session.add(scan)
+ session.commit()
+
transform_branches = [FlowBranch(**branch) for branch in transform_branches]
- scanner = TransformOrchestrator(sketch_id, scan_id, transform_branches=transform_branches, neo4j_conn=neo4j_connection)
+ scanner = TransformOrchestrator(
+ sketch_id=sketch_id,
+ scan_id=str(scan_id),
+ transform_branches=transform_branches,
+ neo4j_conn=neo4j_connection,
+ logger=logger
+ )
results = scanner.execute(values=values)
- status = "finished" if "error" not in results else "error"
- db.table("scans").update({
- "status": status,
- "results": scanner.results_to_json(results=results)
- }).eq("id", self.request.id).execute()
- return {"result": scanner.results_to_json(results=results)}
-
+
+ scan.status = "finished" if "error" not in results else "error"
+ scan.results = scanner.results_to_json(results)
+ session.commit()
+
+ return {"result": scan.results}
+
except Exception as ex:
+ session.rollback()
error_logs = f"An error occurred: {str(ex)}"
print(f"Error in task: {error_logs}")
- db.table("scans").update({
- "status": "error",
- "results": {"error": error_logs}
- }).eq("id", self.request.id).execute()
- self.update_state(
- state=states.FAILURE,
- )
- raise ex
\ No newline at end of file
+
+ scan = session.query(Scan).filter(Scan.id == uuid.UUID(self.request.id)).first()
+ if scan:
+ scan.status = "error"
+ scan.results = {"error": error_logs}
+ session.commit()
+
+ self.update_state(state=states.FAILURE)
+ raise ex
+
+ finally:
+ session.close()
diff --git a/flowsint-api/branches.json b/flowsint-api/branches.json
deleted file mode 100644
index f1c5cfaa..00000000
--- a/flowsint-api/branches.json
+++ /dev/null
@@ -1,36 +0,0 @@
-[
- {
- "id": "branch-0",
- "name": "Main Flow",
- "steps": [
- {
- "nodeId": "MinimalDomain-1747312962241",
- "type": "type",
- "inputs": {},
- "outputs": {
- "domain": [
- "adaltas.com"
- ]
- },
- "status": "pending",
- "branchId": "branch-0",
- "depth": 0
- },
- {
- "nodeId": "domain_resolve_scanner-1747312965951",
- "type": "scanner",
- "inputs": {
- "domain": [
- "adaltas.com"
- ]
- },
- "outputs": {
- "address": "transformed_address"
- },
- "status": "pending",
- "branchId": "branch-0",
- "depth": 1
- }
- ]
- }
-]
\ No newline at end of file
diff --git a/flowsint-api/requirements.txt b/flowsint-api/requirements.txt
index 9b080037..4c0d3d7a 100644
--- a/flowsint-api/requirements.txt
+++ b/flowsint-api/requirements.txt
@@ -1,6 +1,5 @@
fastapi
redis==5.0.1
-supabase==2.13.0
celery==5.3.6
redis==5.0.1
holehe
@@ -20,4 +19,8 @@ phonenumbers
pydantic[email]
fastapi[all]
neo4j
-faker
\ No newline at end of file
+faker
+sqlalchemy
+psycopg2-binary
+alembic
+passlib[bcrypt]
diff --git a/flowsint-web/middleware.ts b/flowsint-web/middleware.ts
index 06069133..caedcb4e 100644
--- a/flowsint-web/middleware.ts
+++ b/flowsint-web/middleware.ts
@@ -1,8 +1,6 @@
-import { updateSession } from '@/lib/supabase/middleware'
import { NextRequest } from 'next/server'
export async function middleware(request: NextRequest) {
- return await updateSession(request)
}
export const config = {
matcher: [
diff --git a/flowsint-web/package.json b/flowsint-web/package.json
index c3e9c50d..c2ed5419 100644
--- a/flowsint-web/package.json
+++ b/flowsint-web/package.json
@@ -48,9 +48,6 @@
"@radix-ui/themes": "^3.2.0",
"@react-aria/ssr": "3.9.7",
"@react-aria/visually-hidden": "3.8.18",
- "@supabase-cache-helpers/postgrest-swr": "^1.10.6",
- "@supabase/ssr": "^0.5.2",
- "@supabase/supabase-js": "^2.48.1",
"@tailwindcss/cli": "^4.0.3",
"@tailwindcss/postcss": "^4.0.3",
"@tanstack/react-query": "^5.66.8",
@@ -74,6 +71,7 @@
"lodash.debounce": "^4.0.8",
"lucide-react": "^0.475.0",
"next": "^15.2.5",
+ "next-auth": "^5.0.0-beta.28",
"next-themes": "^0.4.4",
"nextjs-toploader": "^3.7.15",
"nuqs": "^2.4.0",
diff --git a/flowsint-web/src/app/api/auth/[...nextauth]/route.ts b/flowsint-web/src/app/api/auth/[...nextauth]/route.ts
new file mode 100644
index 00000000..0cf14087
--- /dev/null
+++ b/flowsint-web/src/app/api/auth/[...nextauth]/route.ts
@@ -0,0 +1,2 @@
+import { handlers } from "@/auth" // Referring to the auth.ts we just created
+export const { GET, POST } = handlers
\ No newline at end of file
diff --git a/flowsint-web/src/app/api/investigations/[investigation_id]/documents/route.ts b/flowsint-web/src/app/api/investigations/[investigation_id]/documents/route.ts
deleted file mode 100644
index 028171d6..00000000
--- a/flowsint-web/src/app/api/investigations/[investigation_id]/documents/route.ts
+++ /dev/null
@@ -1,77 +0,0 @@
-import { createClient } from "@/lib/supabase/server"
-import { formatFileSize } from "@/lib/utils";
-import { NextResponse } from "next/server"
-
-export async function GET(_: Request, { params }: { params: Promise<{ investigation_id: string }> }) {
- const { investigation_id } = await params
- try {
- const supabase = await createClient()
- const {
- data: { user },
- error: userError,
- } = await supabase.auth.getUser();
- if (!user || userError) {
- return NextResponse.json({ error: "Unauthorized" }, { status: 401 })
- }
- const { data: investigation, error: investigationError } = await supabase.from("investigations")
- .select("id")
- .eq("id", investigation_id)
- .single()
- if (!investigation || investigationError) return NextResponse.json({ error: "investigation doesn't exist." }, { status: 404 })
- const { data, error } = await supabase
- .storage
- .from("documents")
- .list(`${investigation_id}`, {
- sortBy: { column: "created_at", order: "desc" }
- })
- if (error) {
- return NextResponse.json({ error: error.message }, { status: 500 })
- }
- // Filtrer le fichier .emptyFolderPlaceholder
- const filteredData = data?.filter((file) => !["placeholder", ".emptyFolderPlaceholder"].includes(file.name)) || []
-
- // Récupérer les URLs publiques pour chaque fichier
- const filesWithUrls = await Promise.all(
- filteredData.map(async (file) => {
- const { data: urlData } = await supabase.storage.from("documents").createSignedUrl(`${investigation_id}/${file.name}`, 3600)
- return {
- id: file.id,
- name: file.name,
- type: file.metadata.mimetype,
- size: formatFileSize(file.metadata.size),
- created_at: file.created_at,
- last_updated_at: file.updated_at || file.created_at,
- url: urlData?.signedUrl,
- owner: {
- first_name: "System",
- last_name: "User",
- },
- }
- }),
- )
- return NextResponse.json(filesWithUrls)
- } catch (error) {
- return NextResponse.json({ error: "Internal Server Error" }, { status: 500 })
- }
-}
-
-
-export async function DELETE(request: Request, { params }: { params: Promise<{ investigation_id: string }> }) {
- const { investigation_id: investigationId } = await params
- const { searchParams } = new URL(request.url)
- const fileName = searchParams.get("fileName")
- if (!fileName) {
- return NextResponse.json({ error: "File name is required" }, { status: 400 })
- }
- try {
- const supabase = await createClient()
- const { error } = await supabase.storage.from("documents").remove([`${investigationId}/${fileName}`])
- if (error) {
- throw error
- }
- return NextResponse.json({ success: true })
- } catch (error) {
- console.error("Error deleting document:", error)
- return NextResponse.json({ error: "Failed to delete document" }, { status: 500 })
- }
-}
\ No newline at end of file
diff --git a/flowsint-web/src/app/api/investigations/[investigation_id]/individuals/[individual_id]/route.ts b/flowsint-web/src/app/api/investigations/[investigation_id]/individuals/[individual_id]/route.ts
deleted file mode 100644
index 52ef14d9..00000000
--- a/flowsint-web/src/app/api/investigations/[investigation_id]/individuals/[individual_id]/route.ts
+++ /dev/null
@@ -1,37 +0,0 @@
-import { createClient } from "@/lib/supabase/server"
-import { NextResponse } from "next/server"
-
-export async function GET(_: Request, { params }: { params: Promise<{ individual_id: string, investigation_id: string }> }) {
- const { investigation_id, individual_id } = await params
- try {
- const supabase = await createClient()
- const {
- data: { user },
- error: userError,
- } = await supabase.auth.getUser();
- if (!user || userError) {
- return NextResponse.json({ error: "Unauthorized" }, { status: 401 })
- }
- const { data: individual, error } = await supabase
- .from('individuals')
- .select(`
- *,
- ips(*),
- phones(*),
- social_accounts(*),
- emails(*)
- `)
- .eq("id", individual_id)
- .single()
- if (error) {
- return NextResponse.json({ error: error.message }, { status: 500 })
- }
- if (!individual) {
- return NextResponse.json({ error: "Individual not found" }, { status: 404 })
- }
- return NextResponse.json({ individual })
- } catch (error) {
- return NextResponse.json({ error: "Internal Server Error" }, { status: 500 })
- }
-}
-
diff --git a/flowsint-web/src/app/api/investigations/[investigation_id]/route.ts b/flowsint-web/src/app/api/investigations/[investigation_id]/route.ts
deleted file mode 100644
index 0dfd25bb..00000000
--- a/flowsint-web/src/app/api/investigations/[investigation_id]/route.ts
+++ /dev/null
@@ -1,30 +0,0 @@
-import { createClient } from "@/lib/supabase/server"
-import { NextResponse } from "next/server"
-
-export async function GET(_: Request, { params }: { params: Promise<{ investigation_id: string }> }) {
- const { investigation_id } = await params
- try {
- const supabase = await createClient()
- const {
- data: { user },
- error: userError,
- } = await supabase.auth.getUser();
- if (!user || userError) {
- return NextResponse.json({ error: "Unauthorized" }, { status: 401 })
- }
- const { data: investigation, error } = await supabase.from("investigations")
- .select("*, members:investigations_profiles(profile:profiles(id, first_name, last_name, avatar_url), role), sketches(*, members:sketches_profiles(profile:profiles(id, first_name, last_name, avatar_url), role)), owner_id")
- .eq("id", investigation_id)
- .single()
- if (error) {
- return NextResponse.json({ error: error.message }, { status: 500 })
- }
- if (!investigation) {
- return NextResponse.json({ error: "Investigation not found" }, { status: 404 })
- }
- return NextResponse.json(investigation)
- } catch (error) {
- return NextResponse.json({ error: "Internal Server Error" }, { status: 500 })
- }
-}
-
diff --git a/flowsint-web/src/app/api/investigations/[investigation_id]/sketches/[sketch_id]/route.ts b/flowsint-web/src/app/api/investigations/[investigation_id]/sketches/[sketch_id]/route.ts
deleted file mode 100644
index 5cd87bd6..00000000
--- a/flowsint-web/src/app/api/investigations/[investigation_id]/sketches/[sketch_id]/route.ts
+++ /dev/null
@@ -1,32 +0,0 @@
-import { createClient } from "@/lib/supabase/server"
-import { NextResponse } from "next/server"
-
-export async function GET(_: Request, { params }: { params: Promise<{ sketch_id: string, investigation_id: string }> }) {
- const { sketch_id, investigation_id } = await params
- try {
- const supabase = await createClient()
- const {
- data: { user },
- error: userError,
- } = await supabase.auth.getUser();
- if (!user || userError) {
- return NextResponse.json({ error: "Unauthorized" }, { status: 401 })
- }
- const { data: sketch, error } = await supabase
- .from("sketches")
- .select("id, title, description, last_updated_at, investigation_id, investigation:investigations(id, name), members:sketches_profiles(profile:profiles(id, first_name, last_name, avatar_url), role)")
- .eq("id", sketch_id)
- .eq("investigation_id", investigation_id)
- .single()
- if (error) {
- return NextResponse.json({ error: error.message }, { status: 500 })
- }
- if (!sketch) {
- return NextResponse.json({ error: "Sketch not found" }, { status: 404 })
- }
- return NextResponse.json({ sketch })
- } catch (error) {
- return NextResponse.json({ error: "Internal Server Error" }, { status: 500 })
- }
-}
-
diff --git a/flowsint-web/src/app/api/investigations/[investigation_id]/sketches/[sketch_id]/scans/[scan_id]/route.ts b/flowsint-web/src/app/api/investigations/[investigation_id]/sketches/[sketch_id]/scans/[scan_id]/route.ts
deleted file mode 100644
index b1745eb6..00000000
--- a/flowsint-web/src/app/api/investigations/[investigation_id]/sketches/[sketch_id]/scans/[scan_id]/route.ts
+++ /dev/null
@@ -1,28 +0,0 @@
-import { createClient } from "@/lib/supabase/server"
-import { NextResponse } from "next/server"
-
-export async function GET(_: Request, { params }: { params: Promise<{ sketch_id: string, scan_id: string }> }) {
- const { sketch_id, scan_id } = await params
- try {
- const supabase = await createClient()
- const {
- data: { user },
- error: userError,
- } = await supabase.auth.getUser();
- if (!user || userError) {
- return NextResponse.json({ error: "Unauthorized" }, { status: 401 })
- }
- const { data: scan, error } = await supabase
- .from('scans')
- .select(`*`)
- .eq("sketch_id", sketch_id)
- .eq('id', scan_id)
- .single()
- if (error) {
- return NextResponse.json({ error: error.message }, { status: 500 })
- }
- return NextResponse.json(scan)
- } catch (error) {
- return NextResponse.json({ error: "Internal Server Error" }, { status: 500 })
- }
-}
\ No newline at end of file
diff --git a/flowsint-web/src/app/api/investigations/[investigation_id]/sketches/[sketch_id]/scans/route.ts b/flowsint-web/src/app/api/investigations/[investigation_id]/sketches/[sketch_id]/scans/route.ts
deleted file mode 100644
index 3751b2b7..00000000
--- a/flowsint-web/src/app/api/investigations/[investigation_id]/sketches/[sketch_id]/scans/route.ts
+++ /dev/null
@@ -1,27 +0,0 @@
-import { createClient } from "@/lib/supabase/server"
-import { NextResponse } from "next/server"
-
-export async function GET(_: Request, { params }: { params: Promise<{ sketch_id: string }> }) {
- const { sketch_id } = await params
- try {
- const supabase = await createClient()
- const {
- data: { user },
- error: userError,
- } = await supabase.auth.getUser();
- if (!user || userError) {
- return NextResponse.json({ error: "Unauthorized" }, { status: 401 })
- }
- const { data: scans, error } = await supabase
- .from('scans')
- .select(`*`)
- .eq("sketch_id", sketch_id)
- .order("created_at", { ascending: false })
- if (error) {
- return NextResponse.json({ error: error.message }, { status: 500 })
- }
- return NextResponse.json(scans)
- } catch (error) {
- return NextResponse.json({ error: "Internal Server Error" }, { status: 500 })
- }
-}
\ No newline at end of file
diff --git a/flowsint-web/src/app/api/investigations/[investigation_id]/sketches/[sketch_id]/sketch/route.ts b/flowsint-web/src/app/api/investigations/[investigation_id]/sketches/[sketch_id]/sketch/route.ts
deleted file mode 100644
index 60ce4e42..00000000
--- a/flowsint-web/src/app/api/investigations/[investigation_id]/sketches/[sketch_id]/sketch/route.ts
+++ /dev/null
@@ -1,26 +0,0 @@
-import { createClient } from "@/lib/supabase/server"
-import { NextResponse } from "next/server"
-
-export async function GET(_: Request, { params }: { params: Promise<{ sketch_id: string }> }) {
- const { sketch_id } = await params
- const supabase = await createClient()
- try {
- await supabase.auth.refreshSession()
- const { data: { session } } = await supabase.auth.getSession();
- const jwt = session?.access_token;
- const response = await fetch(`${process.env.NEXT_PUBLIC_DOCKER_FLOWSINT_API}/sketch/${sketch_id}/nodes`, {
- headers: {
- 'Authorization': `Bearer ${jwt}`,
- "Content-Type": "application/json",
- },
- })
- const re = await response.json()
- if (!response.ok) {
- return NextResponse.json({ error: "An error occured." }, { status: 500 })
- }
- return NextResponse.json(re, { status: 200 })
- } catch (error) {
- console.log(error)
- return NextResponse.json({ error: "Internal Server Error" }, { status: 500 })
- }
-}
diff --git a/flowsint-web/src/app/api/investigations/[investigation_id]/sketches/route.ts b/flowsint-web/src/app/api/investigations/[investigation_id]/sketches/route.ts
deleted file mode 100644
index 07e1394e..00000000
--- a/flowsint-web/src/app/api/investigations/[investigation_id]/sketches/route.ts
+++ /dev/null
@@ -1,27 +0,0 @@
-import { createClient } from "@/lib/supabase/server"
-import { NextResponse } from "next/server"
-
-export async function GET(_: Request, { params }: { params: Promise<{ investigation_id: string }> }) {
- try {
- const { investigation_id } = await params
- const supabase = await createClient()
- const {
- data: { user },
- error: userError,
- } = await supabase.auth.getUser();
- if (!user || userError) {
- return NextResponse.json({ error: "Unauthorized" }, { status: 401 })
- }
- const { data: sketches, error } = await supabase.from("sketches")
- .select("id, title, description, status, owner_id, investigation_id, last_updated_at, investigation:investigations(id, name), members:sketches_profiles(profile:profiles(id, first_name, last_name, avatar_url), role)")
- .order("last_updated_at", { ascending: false })
- .eq("investigation_id", investigation_id)
- if (error) {
- return NextResponse.json({ error: error.message }, { status: 500 })
- }
- return NextResponse.json(sketches)
- } catch (error) {
- return NextResponse.json({ error: "Internal Server Error" }, { status: 500 })
- }
-}
-
diff --git a/flowsint-web/src/app/api/investigations/route.ts b/flowsint-web/src/app/api/investigations/route.ts
deleted file mode 100644
index ab2cad53..00000000
--- a/flowsint-web/src/app/api/investigations/route.ts
+++ /dev/null
@@ -1,24 +0,0 @@
-import { createClient } from "@/lib/supabase/server"
-import { NextResponse } from "next/server"
-
-export async function GET() {
- try {
- const supabase = await createClient()
- const {
- data: { user },
- error: userError,
- } = await supabase.auth.getUser();
- if (!user || userError) {
- return NextResponse.json({ error: "Unauthorized" }, { status: 401 })
- }
- const { data: investigations, error } = await supabase.from("investigations")
- .select("*, sketches(*), status, owner_id, members:investigations_profiles(profile:profiles(id, first_name, last_name, avatar_url), role)")
- if (error) {
- return NextResponse.json({ error: error.message }, { status: 500 })
- }
- return NextResponse.json({ investigations })
- } catch (error) {
- return NextResponse.json({ error: "Internal Server Error" }, { status: 500 })
- }
-}
-
diff --git a/flowsint-web/src/app/api/latest-sketches/route.ts b/flowsint-web/src/app/api/latest-sketches/route.ts
deleted file mode 100644
index 3cbb85bb..00000000
--- a/flowsint-web/src/app/api/latest-sketches/route.ts
+++ /dev/null
@@ -1,27 +0,0 @@
-import { createClient } from "@/lib/supabase/server"
-import { NextRequest, NextResponse } from "next/server"
-
-export async function GET(request: NextRequest) {
- try {
- const supabase = await createClient()
- let limit = request.nextUrl.searchParams.get("limit") || "4"
- const {
- data: { user },
- error: userError,
- } = await supabase.auth.getUser();
- if (!user || userError) {
- return NextResponse.json({ error: "Unauthorized" }, { status: 401 })
- }
- const { data: sketches, error } = await supabase.from("sketches")
- .select("id, title, owner_id, description, last_updated_at, investigation_id, investigation:investigations(id, name), members:sketches_profiles(profile:profiles(id, first_name, last_name, avatar_url), role)")
- .order("last_updated_at", { ascending: false })
- .limit(parseInt(limit))
- if (error) {
- return NextResponse.json({ error: error.message }, { status: 500 })
- }
- return NextResponse.json(sketches)
- } catch (error) {
- return NextResponse.json({ error: "Internal Server Error" }, { status: 500 })
- }
-}
-
diff --git a/flowsint-web/src/app/api/metrics/global/route.ts b/flowsint-web/src/app/api/metrics/global/route.ts
deleted file mode 100644
index b293f87f..00000000
--- a/flowsint-web/src/app/api/metrics/global/route.ts
+++ /dev/null
@@ -1,34 +0,0 @@
-import { createClient } from "@/lib/supabase/server"
-import { NextRequest, NextResponse } from "next/server"
-
-export async function GET(request: NextRequest) {
- try {
- const supabase = await createClient()
- const now = new Date();
- const oneMonthAgo = new Date();
- oneMonthAgo.setMonth(now.getMonth() - 1);
- now.setDate(now.getDate() + 1); // Ajoute un jour à "today"
- let start = request.nextUrl.searchParams.get("start") || oneMonthAgo.toISOString().split("T")[0];
- let end = request.nextUrl.searchParams.get("end") || now.toISOString().split("T")[0];
-
- const {
- data: { user },
- error: userError,
- } = await supabase.auth.getUser();
- if (!user || userError) {
- return NextResponse.json({ error: "Unauthorized" }, { status: 401 })
- }
- const { data, error } = await supabase.rpc('get_global_metrics', {
- start_date: start,
- end_date: end
- }).single();
-
- if (error) {
- return NextResponse.json({ error: error.message }, { status: 500 })
- }
- return NextResponse.json(data)
- } catch (error) {
- return NextResponse.json({ error: "Internal Server Error" }, { status: 500 })
- }
-}
-
diff --git a/flowsint-web/src/app/api/profiles/[profile_id]/route.ts b/flowsint-web/src/app/api/profiles/[profile_id]/route.ts
deleted file mode 100644
index ae3e2504..00000000
--- a/flowsint-web/src/app/api/profiles/[profile_id]/route.ts
+++ /dev/null
@@ -1,27 +0,0 @@
-import { createClient } from "@/lib/supabase/server"
-import { NextResponse } from "next/server"
-
-export async function GET(_: Request, { params }: { params: Promise<{ profile_id: string }> }) {
- const { profile_id } = await (params)
- try {
- const supabase = await createClient()
- const {
- data: { user },
- error: userError,
- } = await supabase.auth.getUser();
- if (!user || userError) {
- return NextResponse.json({ error: "Unauthorized" }, { status: 401 })
- }
- const { data: profile, error } = await supabase.from("profiles")
- .select("id, first_name, last_name, avatar_url")
- .eq("id", profile_id)
- .single()
- if (error) {
- return NextResponse.json({ error: error.message }, { status: 500 })
- }
- return NextResponse.json(profile)
- } catch (error) {
- return NextResponse.json({ error: "Internal Server Error" }, { status: 500 })
- }
-}
-
diff --git a/flowsint-web/src/app/api/profiles/route.ts b/flowsint-web/src/app/api/profiles/route.ts
deleted file mode 100644
index 0d4a6a07..00000000
--- a/flowsint-web/src/app/api/profiles/route.ts
+++ /dev/null
@@ -1,25 +0,0 @@
-import { createClient } from "@/lib/supabase/server"
-import { NextResponse } from "next/server"
-
-export async function GET() {
- try {
- const supabase = await createClient()
- const {
- data: { user },
- error: userError,
- } = await supabase.auth.getUser();
- if (!user || userError) {
- return NextResponse.json({ error: "Unauthorized" }, { status: 401 })
- }
- const { data: profiles, error } = await supabase.from("profiles")
- .select("*")
- .neq("id", user.id)
- if (error) {
- return NextResponse.json({ error: error.message }, { status: 500 })
- }
- return NextResponse.json(profiles)
- } catch (error) {
- return NextResponse.json({ error: "Internal Server Error" }, { status: 500 })
- }
-}
-
diff --git a/flowsint-web/src/app/api/transforms/route.ts b/flowsint-web/src/app/api/transforms/route.ts
deleted file mode 100644
index 65f3ffc6..00000000
--- a/flowsint-web/src/app/api/transforms/route.ts
+++ /dev/null
@@ -1,32 +0,0 @@
-import { createClient } from "@/lib/supabase/server"
-import { NextRequest, NextResponse } from "next/server"
-
-export async function GET(request: NextRequest) {
- try {
- const supabase = await createClient()
- let type = request.nextUrl.searchParams.get("type")
- const {
- data: { user },
- error: userError,
- } = await supabase.auth.getUser();
- if (!user || userError) {
- return NextResponse.json({ error: "Unauthorized" }, { status: 401 })
- }
- if (!type) {
- return NextResponse.json({ error: "Missing param 'type'" }, { status: 400 })
- }
- const { data: transforms, error } = await supabase.from("transforms")
- .select("id, name, description, category, created_at, last_updated_at")
- .order("last_updated_at", { ascending: false })
- .contains('category', [type])
- if (error) {
- console.log(error)
- return NextResponse.json({ error: error.message }, { status: 500 })
- }
- return NextResponse.json(transforms)
- } catch (error) {
- console.log(error)
- return NextResponse.json({ error: "Internal Server Error" }, { status: 500 })
- }
-}
-
diff --git a/flowsint-web/src/app/auth/callback/route.ts b/flowsint-web/src/app/auth/callback/route.ts
deleted file mode 100644
index af11e00e..00000000
--- a/flowsint-web/src/app/auth/callback/route.ts
+++ /dev/null
@@ -1,30 +0,0 @@
-import { NextResponse } from 'next/server'
-// The client you created from the Server-Side Auth instructions
-import { createClient } from '@/lib/supabase/server'
-
-export async function GET(request: Request) {
- const { searchParams, origin } = new URL(request.url)
- const code = searchParams.get('code')
- // if "next" is in param, use it as the redirect URL
- const next = searchParams.get('next') ?? '/'
-
- if (code) {
- const supabase = await createClient()
- const { error } = await supabase.auth.exchangeCodeForSession(code)
- if (!error) {
- const forwardedHost = request.headers.get('x-forwarded-host') // original origin before load balancer
- const isLocalEnv = process.env.NODE_ENV === 'development'
- if (isLocalEnv) {
- // we can be sure that there is no load balancer in between, so no need to watch for X-Forwarded-Host
- return NextResponse.redirect(`${origin}${next}`)
- } else if (forwardedHost) {
- return NextResponse.redirect(`https://${forwardedHost}${next}`)
- } else {
- return NextResponse.redirect(`${origin}${next}`)
- }
- }
- }
-
- // return the user to an error page with instructions
- return NextResponse.redirect(`${origin}/auth/auth-code-error`)
-}
\ No newline at end of file
diff --git a/flowsint-web/src/app/auth/confirm/route.ts b/flowsint-web/src/app/auth/confirm/route.ts
deleted file mode 100644
index beee77c6..00000000
--- a/flowsint-web/src/app/auth/confirm/route.ts
+++ /dev/null
@@ -1,27 +0,0 @@
-import { type EmailOtpType } from '@supabase/supabase-js'
-import { type NextRequest } from 'next/server'
-
-import { createClient } from '@/lib/supabase/server'
-import { redirect } from 'next/navigation'
-
-export async function GET(request: NextRequest) {
- const { searchParams } = new URL(request.url)
- const token_hash = searchParams.get('token_hash')
- const type = searchParams.get('type') as EmailOtpType | null
- const next = searchParams.get('next') ?? '/'
-
- if (token_hash && type) {
- const supabase = await createClient()
-
- const { error } = await supabase.auth.verifyOtp({
- type,
- token_hash,
- })
- if (!error) {
- // redirect user to specified redirect URL or root of app
- redirect(next)
- }
- }
- // redirect the user to an error page with some instructions
- redirect('/error')
-}
\ No newline at end of file
diff --git a/flowsint-web/src/app/dashboard/investigations/[investigation_id]/layout.tsx b/flowsint-web/src/app/dashboard/investigations/[investigation_id]/layout.tsx
index 03e2ff15..9a8384f4 100644
--- a/flowsint-web/src/app/dashboard/investigations/[investigation_id]/layout.tsx
+++ b/flowsint-web/src/app/dashboard/investigations/[investigation_id]/layout.tsx
@@ -1,5 +1,4 @@
-import FileUploadDialog from "@/components/investigations/file-upload";
-import { createClient } from "@/lib/supabase/server";
+import { serverFetch } from "@/lib/server-fetch";
import { notFound } from "next/navigation";
const DashboardLayout = async ({
@@ -9,16 +8,15 @@ const DashboardLayout = async ({
children: React.ReactNode;
params: Promise<{ investigation_id: string }>
}) => {
- const supabase = await createClient()
- const { investigation_id } = await (params)
- const { data: investigation, error } = await supabase.from("investigations").select("id").eq("id", investigation_id).single()
- if (!investigation || error) {
+ const { investigation_id } = await params
+ const investigation = await serverFetch(`${process.env.NEXT_PUBLIC_DOCKER_FLOWSINT_API}/investigations/${investigation_id}`)
+
+ if (!investigation) {
return notFound()
}
return (
<>
{children}
- <FileUploadDialog />
</>
)
}
diff --git a/flowsint-web/src/app/dashboard/investigations/[investigation_id]/page.tsx b/flowsint-web/src/app/dashboard/investigations/[investigation_id]/page.tsx
index 6e645e94..25a0cf8f 100644
--- a/flowsint-web/src/app/dashboard/investigations/[investigation_id]/page.tsx
+++ b/flowsint-web/src/app/dashboard/investigations/[investigation_id]/page.tsx
@@ -21,44 +21,19 @@ import { AvatarList } from "@/components/avatar-list"
// import { SectionCards } from "@/components/investigations/section-cards"
import { Profile } from "@/types"
import { Skeleton } from "@/components/ui/skeleton"
+import { clientFetch } from "@/lib/client-fetch"
const DashboardPage = () => {
const { investigation_id } = useParams()
const [searchQuery, setSearchQuery] = useState("")
-
- const { data: investigation, isLoading: isLoadingInvestigations, isRefetching: isRefetchingInvestigations, refetch: refetchSketches } = useQuery({
- queryKey: ["dashboard", "investigation", investigation_id],
+ const { data: investigation, isLoading, refetch, isRefetching } = useQuery({
+ queryKey: [process.env.NEXT_PUBLIC_FLOWSINT_API, "dashboard", "investigations", investigation_id],
queryFn: async () => {
- const res = await fetch(`/api/investigations/${investigation_id}`)
- if (!res.ok) {
- notFound()
- }
- return res.json()
+ const data = await clientFetch(`${process.env.NEXT_PUBLIC_FLOWSINT_API}/investigations/${investigation_id}`)
+ return data
},
refetchOnWindowFocus: true,
})
- const {
- data: documents, isLoading: isLoadingDocs, isRefetching: isRefetchingDocs, refetch: refetchDocs
- } = useQuery({
- queryKey: ["investigations", investigation_id, "documents"],
- queryFn: async () => {
- const res = await fetch(`/api/investigations/${investigation_id}/documents`)
- if (!res.ok) {
- throw new Error("Failed to fetch documents")
- }
- return res.json() as Promise<Document[]>
- },
- refetchOnWindowFocus: true,
- enabled: !!investigation_id,
- })
-
- const handleRefetch = () => {
- refetchSketches()
- refetchDocs()
- }
-
- const isLoading = isLoadingDocs || isLoadingInvestigations
- const isRefetching = isRefetchingDocs || isRefetchingInvestigations
return (
<>
@@ -103,7 +78,7 @@ const DashboardPage = () => {
/>
</div>
<div className="flex items-center gap-2">
- <Button onClick={handleRefetch} disabled={isLoading || isRefetching} variant={"outline"} className="gap-2">
+ <Button onClick={() => refetch()} disabled={isLoading || isRefetching} variant={"outline"} className="gap-2">
<RotateCwIcon className={cn("h-4 w-4", isLoading || isRefetching && "animate-spin")} /> Refresh
</Button>
<NewSketch>
@@ -113,7 +88,7 @@ const DashboardPage = () => {
</NewSketch>
</div>
</div>
- {isLoadingInvestigations ? (
+ {isLoading ? (
<Loader label="Loading..." />
) : (
<Card className="border rounded-md bg-card shadow-xs">
@@ -130,7 +105,7 @@ const DashboardPage = () => {
</TableRow>
</TableHeader>
<TableBody>
- {investigation.sketches.length === 0 && documents?.length === 0 ? (
+ {investigation.sketches.length === 0 ? (
<TableRow>
<TableCell colSpan={7} className="text-center w-full py-2 text-muted-foreground">
<div className="flex flex-col justify-center items-center p-3 gap-2">
@@ -193,7 +168,6 @@ const DashboardPage = () => {
</TableRow>
))
)}
- <DocumentList refetch={refetchDocs} isLoading={isLoadingDocs} documents={documents} />
</TableBody>
</Table>
</Card>
diff --git a/flowsint-web/src/app/dashboard/investigations/[investigation_id]/sketches/[sketch_id]/client.tsx b/flowsint-web/src/app/dashboard/investigations/[investigation_id]/sketches/[sketch_id]/client.tsx
index d576c05c..c6b6ed87 100644
--- a/flowsint-web/src/app/dashboard/investigations/[investigation_id]/sketches/[sketch_id]/client.tsx
+++ b/flowsint-web/src/app/dashboard/investigations/[investigation_id]/sketches/[sketch_id]/client.tsx
@@ -13,6 +13,7 @@ import { GraphPanel } from "./graph-panel"
import { Sketch } from "@/types/sketch"
import SettingsModal from "./settings-modal"
import { CreateRelationDialog } from "@/components/sketches/sketch/create-relation"
+import { clientFetch } from "@/lib/client-fetch"
interface DashboardClientProps {
investigationId: string
@@ -34,16 +35,14 @@ export default function DashboardClient({ investigationId, sketchId, sketch, use
} = useSketchStore(stateSelector, shallow)
const graphQuery = useQuery({
- queryKey: ["investigations", investigationId, 'sketches', sketchId, "data"],
+ queryKey: [process.env.NEXT_PUBLIC_DOCKER_FLOWSINT_API, "sketches", sketchId, "graph"],
queryFn: async () => {
- const res = await fetch(`/api/investigations/${investigationId}/sketches/${sketchId}/sketch`)
- if (!res.ok) {
- notFound()
- }
- return res.json()
+ const data = await clientFetch(`${process.env.NEXT_PUBLIC_FLOWSINT_API}/sketches/${sketchId}/graph`)
+ return data
},
refetchOnWindowFocus: true,
})
+
return (
<>
<Toolbar investigation_id={investigationId} sketch_id={sketchId} sketch={sketch} user_id={user_id} />
diff --git a/flowsint-web/src/app/dashboard/investigations/[investigation_id]/sketches/[sketch_id]/console-panel.tsx b/flowsint-web/src/app/dashboard/investigations/[investigation_id]/sketches/[sketch_id]/console-panel.tsx
index cc34f7c9..d7baa179 100644
--- a/flowsint-web/src/app/dashboard/investigations/[investigation_id]/sketches/[sketch_id]/console-panel.tsx
+++ b/flowsint-web/src/app/dashboard/investigations/[investigation_id]/sketches/[sketch_id]/console-panel.tsx
@@ -3,7 +3,6 @@
import { CopyButton } from "@/components/copy"
import { Button } from "@/components/ui/button"
import { useConfirm } from "@/components/use-confirm-dialog"
-import { supabase } from "@/lib/supabase/client"
import { Loader2, TrashIcon, XCircle, AlertTriangle, Info, CheckCircle } from "lucide-react"
import { useParams } from "next/navigation"
import { memo, useCallback, useEffect, useRef, useState } from "react"
@@ -34,101 +33,18 @@ const typeToClass: Record<string, string> = {
export const ConsolePanel = memo(function ConsolePanel() {
const [logEntries, setLogEntries] = useState<LogEntry[]>([])
- const [isLoading, setIsLoading] = useState(true)
+ const [isLoading, setIsLoading] = useState(false)
const { sketch_id } = useParams()
const bottomRef = useRef<HTMLDivElement | null>(null)
const { confirm } = useConfirm()
const refetch = useCallback(async () => {
- try {
- setIsLoading(true)
- const { data, error } = await supabase
- .from("logs")
- .select("*")
- .eq("sketch_id", sketch_id)
- .order("created_at", { ascending: true })
- .limit(50)
-
- if (error) {
- toast.error("Failed to load logs")
- return
- }
-
- if (data) {
- const formattedLogs = data.map((log: any) => ({
- id: log.id,
- type: log.type || "INFO",
- timestamp: new Date(log.created_at).toLocaleTimeString(),
- content: log.content,
- created_at: log.created_at,
- }))
- setLogEntries(formattedLogs)
- }
- } catch (error) {
- console.error("Error in refetch:", error)
- toast.error("An unexpected error occurred while loading logs")
- } finally {
- setIsLoading(false)
- }
+ // TODO
}, [sketch_id])
const handleDeleteLogs = useCallback(async () => {
- try {
- const confirmed = await confirm({
- title: "Deleting logs",
- message: "Are you sure you want to delete these logs ?",
- })
-
- if (!confirmed) return
-
- setIsLoading(true)
- const { error } = await supabase.from("logs").delete().eq("sketch_id", sketch_id)
-
- if (error) {
- toast.error("An error occurred deleting the logs.")
- return
- }
-
- toast.success("Logs cleared.")
- await refetch()
- } catch (e) {
- toast.error("An error occurred deleting the logs.")
- } finally {
- setIsLoading(false)
- }
- }, [confirm, sketch_id, refetch])
-
- useEffect(() => {
- refetch()
-
- const subscription = supabase
- .channel("logs-channel")
- .on(
- "postgres_changes",
- {
- event: "INSERT",
- schema: "public",
- table: "logs",
- filter: `sketch_id=eq.${sketch_id}`,
- },
- (payload) => {
- const newLog = payload.new as any
- const formattedLog: LogEntry = {
- id: newLog.id,
- type: newLog.type || "INFO",
- timestamp: new Date(newLog.created_at).toLocaleTimeString(),
- content: newLog.content,
- created_at: newLog.created_at,
- }
- setLogEntries((prevLogs) => [...prevLogs, formattedLog])
- },
- )
- .subscribe()
-
- return () => {
- subscription.unsubscribe()
- }
- }, [refetch])
+ // TODO
+ }, [])
useEffect(() => {
bottomRef.current?.scrollIntoView({ behavior: "smooth" })
diff --git a/flowsint-web/src/app/dashboard/investigations/[investigation_id]/sketches/[sketch_id]/page.tsx b/flowsint-web/src/app/dashboard/investigations/[investigation_id]/sketches/[sketch_id]/page.tsx
index 88b6a373..4d2bfb2b 100644
--- a/flowsint-web/src/app/dashboard/investigations/[investigation_id]/sketches/[sketch_id]/page.tsx
+++ b/flowsint-web/src/app/dashboard/investigations/[investigation_id]/sketches/[sketch_id]/page.tsx
@@ -1,28 +1,23 @@
import { notFound, redirect, unauthorized } from "next/navigation"
import DashboardClient from "./client"
-import { createClient } from "@/lib/supabase/server"
+import { serverFetch } from "@/lib/server-fetch"
+import { auth } from "@/auth"
const InvestigationPage = async ({
params,
}: {
params: Promise<{ investigation_id: string, sketch_id: string }>
}) => {
- const supabase = await createClient()
+ const session = await auth();
+ if (!session) return redirect("/login")
const { investigation_id, sketch_id } = await (params)
- const {
- data: { user },
- error: userError,
- } = await supabase.auth.getUser();
- if (!user || userError) {
- return redirect("/login")
- }
- const { data: sketch, error } = await supabase.from("sketches").select("*, members:sketches_profiles(profile:profiles(id, first_name, last_name, avatar_url), role)").eq("id", sketch_id).single()
- if (!sketch || error) {
+ const sketch = await serverFetch(`${process.env.NEXT_PUBLIC_DOCKER_FLOWSINT_API}/sketches/${sketch_id}`)
+ if (!sketch) {
return notFound()
}
return (
<>
- <DashboardClient investigationId={investigation_id} sketchId={sketch_id} sketch={sketch} user_id={user?.id} />
+ <DashboardClient investigationId={investigation_id} sketchId={sketch_id} sketch={sketch} user_id={session?.user?.id as string} />
</>)
}
diff --git a/flowsint-web/src/app/dashboard/investigations/[investigation_id]/sketches/[sketch_id]/toolbar.tsx b/flowsint-web/src/app/dashboard/investigations/[investigation_id]/sketches/[sketch_id]/toolbar.tsx
index 5a29f343..7829cc11 100644
--- a/flowsint-web/src/app/dashboard/investigations/[investigation_id]/sketches/[sketch_id]/toolbar.tsx
+++ b/flowsint-web/src/app/dashboard/investigations/[investigation_id]/sketches/[sketch_id]/toolbar.tsx
@@ -2,9 +2,7 @@
import { AvatarList } from "@/components/avatar-list"
import MoreMenu from "@/components/sketches/more-menu"
-import { ScanButton } from "@/components/sketches/scans-drawer/scan-button"
import { Button } from "@/components/ui/button"
-import { Toggle } from "@/components/ui/toggle"
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from "@/components/ui/tooltip"
import { useConfirm } from "@/components/use-confirm-dialog"
import { cn } from "@/lib/utils"
@@ -173,10 +171,6 @@ export const Toolbar = memo(function Toolbar({
<ToolbarButton disabled icon={<Layers className="h-4 w-4 opacity-70" />} tooltip="Layers" />
<ToolbarButton onClick={toggleSettings} icon={<GearIcon className="h-4 w-4 opacity-70" />} tooltip="Settings" />
<Separator />
- {/* <Toggle className="h-8 w-8" onClick={() => setGraphView((prev) => prev === "2d" ? "3d" : "2d")} aria-label="Toggle italic">
- <Rotate3DIcon className={cn("h-4 w-4 opacity-70")} />
- </Toggle> */}
- {/* <Separator /> */}
<ToolbarButton onClick={refetch} disabled={isRefetching} icon={<RotateCwIcon className={cn("h-4 w-4 opacity-70", isRefetching && "animate-spin")} />} tooltip="Reload" />
</TooltipProvider>
</div>
@@ -187,12 +181,7 @@ export const Toolbar = memo(function Toolbar({
users={sketchMembers}
/>
</div>
- {/* <DownloadButton
- endpoint={`/api/investigations/${investigation_id}/sketches/${sketch_id}/table`}
- name={investigation_id}
- /> */}
<MoreMenu sketch={sketch} user_id={user_id} />
- <ScanButton />
</div>
</div>
)
diff --git a/flowsint-web/src/app/dashboard/investigations/page.tsx b/flowsint-web/src/app/dashboard/investigations/page.tsx
index 60340bd3..2b6504e0 100644
--- a/flowsint-web/src/app/dashboard/investigations/page.tsx
+++ b/flowsint-web/src/app/dashboard/investigations/page.tsx
@@ -19,24 +19,19 @@ import { cn } from "@/lib/utils"
import { SubNav } from "@/components/dashboard/sub-nav"
import { Card } from "@/components/ui/card"
import StatusBadge from "@/components/investigations/status-badge"
+import { clientFetch } from "@/lib/client-fetch"
const DashboardPage = () => {
const [searchQuery, setSearchQuery] = useState("")
- const [viewMode, setViewMode] = useState<"grid" | "list">("grid")
-
- const { data, isLoading, refetch, isRefetching } = useQuery({
- queryKey: ["dashboard", "investigations"],
+ const { data: investigations, isLoading, refetch, isRefetching } = useQuery({
+ queryKey: [process.env.NEXT_PUBLIC_FLOWSINT_API, "dashboard", "investigations"],
queryFn: async () => {
- const res = await fetch(`/api/investigations`)
- if (!res.ok || res.status === 404) {
- notFound()
- }
- return res.json()
+ const data = await clientFetch(`${process.env.NEXT_PUBLIC_FLOWSINT_API}/investigations`)
+ return data
},
refetchOnWindowFocus: true,
})
- const investigations = data?.investigations || []
- const filteredInvestigations = investigations.filter(
+ const filteredInvestigations = investigations?.filter(
(investigation: Investigation) => searchQuery === "" || investigation.name?.toLowerCase().includes(searchQuery.toLowerCase()),
)
diff --git a/flowsint-web/src/app/dashboard/layout.tsx b/flowsint-web/src/app/dashboard/layout.tsx
index a4956876..b2cc8496 100644
--- a/flowsint-web/src/app/dashboard/layout.tsx
+++ b/flowsint-web/src/app/dashboard/layout.tsx
@@ -1,15 +1,12 @@
-import { createClient } from "@/lib/supabase/server";
import {
SidebarInset,
SidebarProvider,
} from "@/components/ui/sidebar"
import { redirect } from "next/navigation";
-import { Button } from "@/components/ui/button";
import { MainNav } from "@/components/dashboard/main-nav";
-import { NavUser } from "@/components/nav-user";
-import Feedback from "@/components/dashboard/feedback";
import Link from "next/link";
import SecondaryNav from "@/components/dashboard/secondary-nav";
+import { auth } from "@/auth";
const DashboardLayout = async ({
children,
@@ -17,12 +14,8 @@ const DashboardLayout = async ({
children: React.ReactNode;
}) => {
- const supabase = await createClient()
- const { data, error: userError } = await supabase.auth.getUser()
-
- if (userError || !data?.user) {
- redirect('/login')
- }
+ const session = await auth();
+ if (!session) return redirect("/login")
return (
<SidebarProvider>
@@ -44,7 +37,8 @@ const DashboardLayout = async ({
</Link>
{/* <Separator orientation="vertical" className="h-6" /> */}
<MainNav className="mx-6" />
- <SecondaryNav profile_id={data?.user.id} />
+ {/* @ts-ignore */}
+ <SecondaryNav profile_id={session?.user?.id as string} />
</div>
</header>
{children}
diff --git a/flowsint-web/src/app/dashboard/page.tsx b/flowsint-web/src/app/dashboard/page.tsx
index df7e4ed3..5c431934 100644
--- a/flowsint-web/src/app/dashboard/page.tsx
+++ b/flowsint-web/src/app/dashboard/page.tsx
@@ -1,183 +1,11 @@
-// "use client"
-
-// import { useState } from "react"
-// import { Button } from "@/components/ui/button"
-// import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table"
-// import { FolderLockIcon, MoreHorizontal, PlusIcon, RotateCwIcon } from "lucide-react"
-// import { useQuery } from "@tanstack/react-query"
-// import { notFound } from "next/navigation"
-// import Loader from "@/components/loader"
-// import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from "@/components/ui/dropdown-menu"
-// import { format, formatDistanceToNow } from "date-fns"
-// import Link from "next/link"
-// import { Investigation } from "@/types/investigation"
-// import RecentSketches from "@/components/dashboard/recent-sketches"
-// import NewInvestigation from "@/components/dashboard/new-investigation"
-// import { AvatarList } from "@/components/avatar-list"
-// import { cn } from "@/lib/utils"
-// import { SubNav } from "@/components/dashboard/sub-nav"
-// import { Card } from "@/components/ui/card"
-// import StatusBadge from "@/components/investigations/status-badge"
-// import { InvestigationGraph } from "@/components/dashboard/charts/investigation-chart"
-// import { MetricsChart } from "@/components/dashboard/charts/metrics-chart"
-// import { DateRangePicker } from "@/components/date-range-picker"
-// const DashboardPage = () => {
-
-// const { data, isLoading, refetch, isRefetching } = useQuery({
-// queryKey: ["dashboard", "investigations"],
-// queryFn: async () => {
-// const res = await fetch(`/api/investigations`)
-// if (!res.ok || res.status === 404) {
-// notFound()
-// }
-// return res.json()
-// },
-// refetchOnWindowFocus: true,
-// })
-// const investigations = data?.investigations || []
-
-// return (
-// <>
-// <div className="sticky z-40 bg-card w-full hidden md:flex top-[48px] border-b">
-// <SubNav />
-// </div>
-// <div className="w-full space-y-4 container mx-auto py-12 px-8">
-// <div className="flex grow items-center justify-between w-full gap-4">
-// <h1 className="font-bold text-2xl">Overview</h1>
-// <div className="flex items-center gap-2">
-// <DateRangePicker />
-// <NewInvestigation>
-// <Button className="gap-2">
-// <PlusIcon className="h-4 w-4" /> New
-// </Button>
-// </NewInvestigation>
-// </div>
-// </div>
-// {/* <SectionCards /> */}
-// <div className="grid lg:grid-cols-5 gap-4 w-full">
-// <div className="lg:col-span-2 col-span-1 h-full">
-// <MetricsChart />
-// </div>
-// {/* <div className="col-span-1 h-full">
-// <MetricsChart />
-// </div> */}
-// <div className="lg:col-span-3 col-span-1 h-full">
-// <InvestigationGraph />
-// </div>
-// </div>
-// <h2 className="font-bold text-2xl mt-8">Recent sketches</h2>
-// <RecentSketches limit={4} />
-// <div className="flex items-center gap-2 justify-between mb-6">
-// <div className="flex items-center gap-2">
-// <Button onClick={() => refetch()} disabled={isLoading || isRefetching} variant={"outline"} size="sm" className="gap-2">
-// <RotateCwIcon className={cn("h-4 w-4", isLoading || isRefetching && "animate-spin")} /> Refresh
-// </Button>
-// </div>
-// </div>
-// {isLoading ? (
-// <Loader label="Loading..." />
-// ) : (
-// <Card className="border rounded-md bg-card shadow-xs">
-// <Table>
-// <TableHeader>
-// <TableRow>
-// <TableHead>Name</TableHead>
-// <TableHead className="hidden md:table-cell">Status</TableHead>
-// <TableHead className="hidden md:table-cell">Size</TableHead>
-// <TableHead className="hidden sm:table-cell">Last modified</TableHead>
-// <TableHead className="hidden sm:table-cell">Members</TableHead>
-// <TableHead className="hidden sm:table-cell">Creation</TableHead>
-// <TableHead className="w-[50px]"></TableHead>
-// </TableRow>
-// </TableHeader>
-// <TableBody>
-// {investigations.length === 0 ? (
-// <TableRow>
-// <TableCell colSpan={7} className="text-center py-8 text-muted-foreground">
-// <div className="flex items-center flex-col gap-3">No investigations yet
-// <div className="mt-4">
-// <NewInvestigation noDropDown>
-// <Button size="sm" className="gap-2">
-// <PlusIcon className="h-4 w-4" /> Create a new investigation
-// </Button>
-// </NewInvestigation>
-// </div>
-// </div>
-// </TableCell>
-// </TableRow>
-// ) : (
-// investigations.map((investigation: Investigation) => (
-// <TableRow key={investigation.id}>
-// <TableCell>
-// <Link href={`/dashboard/investigations/${investigation.id}`} className="flex items-center gap-2 hover:underline font-medium">
-// <FolderLockIcon className="h-5 w-5 text-muted-foreground opacity-60" />
-// <span>{investigation.name}</span>
-// </Link>
-// </TableCell>
-// <TableCell className="hidden md:table-cell text-muted-foreground">
-// <StatusBadge status={investigation.status as string} />
-// </TableCell>
-// <TableCell className="hidden md:table-cell text-muted-foreground">
-// {(investigation.sketches?.length || 0) > 0 ? `${investigation.sketches.length} items` : "Empty"}
-// </TableCell>
-// <TableCell className="hidden sm:table-cell text-muted-foreground">
-// {formatDistanceToNow(new Date(investigation.last_updated_at), { addSuffix: true })}
-// </TableCell>
-// <TableCell className="hidden sm:table-cell text-muted-foreground">
-// <AvatarList
-// size="md"
-// users={
-// investigation?.members?.map(member => ({
-// ...member.profile,
-// owner: member.profile.id === investigation.owner_id,
-// })) || []
-// }
-// />
-// </TableCell>
-// <TableCell className="hidden sm:table-cell text-muted-foreground">
-// {format(new Date(investigation.created_at), "dd.MM.yyyy")}
-// </TableCell>
-// <TableCell>
-// <DropdownMenu>
-// <DropdownMenuTrigger asChild>
-// <Button variant="ghost" size="icon" className="h-10 w-8">
-// <MoreHorizontal className="h-4 w-4" />
-// <span className="sr-only">Actions</span>
-// </Button>
-// </DropdownMenuTrigger>
-// <DropdownMenuContent align="end">
-// <DropdownMenuItem>Open</DropdownMenuItem>
-// <DropdownMenuItem>Rename</DropdownMenuItem>
-// <DropdownMenuItem>Share</DropdownMenuItem>
-// <DropdownMenuItem className="text-destructive">Delete</DropdownMenuItem>
-// </DropdownMenuContent>
-// </DropdownMenu>
-// </TableCell>
-// </TableRow>
-// ))
-// )}
-// </TableBody>
-// </Table>
-// </Card>
-// )}
-// </div>
-// </>
-// )
-// }
-
-// export default DashboardPage
-
-
-
"use client"
import { useState } from "react"
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table"
-import { ChevronDown, FolderLockIcon, Grid, List, MoreHorizontal, PlusIcon, RotateCwIcon, Search, SlidersHorizontal } from "lucide-react"
+import { FolderLockIcon, MoreHorizontal, PlusIcon, RotateCwIcon, Search } from "lucide-react"
import { useQuery } from "@tanstack/react-query"
-import { notFound } from "next/navigation"
import Loader from "@/components/loader"
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from "@/components/ui/dropdown-menu"
import { format, formatDistanceToNow } from "date-fns"
@@ -190,24 +18,21 @@ import { cn } from "@/lib/utils"
import { SubNav } from "@/components/dashboard/sub-nav"
import { Card } from "@/components/ui/card"
import StatusBadge from "@/components/investigations/status-badge"
+import { clientFetch } from "@/lib/client-fetch"
const DashboardPage = () => {
const [searchQuery, setSearchQuery] = useState("")
- const [viewMode, setViewMode] = useState<"grid" | "list">("grid")
- const { data, isLoading, refetch, isRefetching } = useQuery({
- queryKey: ["dashboard", "investigations"],
+ const { data: investigations, isLoading, refetch, isRefetching } = useQuery({
+ queryKey: [process.env.NEXT_PUBLIC_DOCKER_FLOWSINT_API, "dashboard", "investigations"],
queryFn: async () => {
- const res = await fetch(`/api/investigations`)
- if (!res.ok || res.status === 404) {
- notFound()
- }
- return res.json()
+ const data = await clientFetch(`${process.env.NEXT_PUBLIC_FLOWSINT_API}/investigations`)
+ return data
},
refetchOnWindowFocus: true,
})
- const investigations = data?.investigations || []
- const filteredInvestigations = investigations.filter(
+
+ const filteredInvestigations = investigations?.filter(
(investigation: Investigation) => searchQuery === "" || investigation.name?.toLowerCase().includes(searchQuery.toLowerCase()),
)
diff --git a/flowsint-web/src/app/dashboard/transforms/[transform_id]/page.tsx b/flowsint-web/src/app/dashboard/transforms/[transform_id]/page.tsx
index 12134c8c..f7b08b70 100644
--- a/flowsint-web/src/app/dashboard/transforms/[transform_id]/page.tsx
+++ b/flowsint-web/src/app/dashboard/transforms/[transform_id]/page.tsx
@@ -1,24 +1,18 @@
import TransformEditor from "@/components/transforms/editor"
-import { createClient } from "@/lib/supabase/server"
+import { serverFetch } from "@/lib/server-fetch"
import { notFound } from "next/navigation"
-async function fetchNodes() {
- const res = await fetch(`${process.env.NEXT_PUBLIC_DOCKER_FLOWSINT_API}/transforms/nodes`)
- if (!res.ok) {
- notFound()
- }
- return res.json()
-}
export default async function EditorCustom({
params
}: {
params: Promise<{ transform_id: string }>
}) {
const { transform_id } = await (params)
- const supabase = await createClient()
- const nodesData = await fetchNodes()
- const { data: transform, error } = await supabase.from("transforms").select("*").eq("id", transform_id as string).single()
- if (error || !transform)
+ const nodesData = await serverFetch(`${process.env.NEXT_PUBLIC_DOCKER_FLOWSINT_API}/transforms/raw_materials`)
+ const transform = await serverFetch(`${process.env.NEXT_PUBLIC_DOCKER_FLOWSINT_API}/transforms/${transform_id}`)
+
+ if (!transform)
return notFound()
+
return <TransformEditor transform={transform} nodesData={nodesData} initialNodes={transform?.transform_schema?.nodes} initialEdges={transform?.transform_schema?.edges} />
}
\ No newline at end of file
diff --git a/flowsint-web/src/app/dashboard/transforms/editor/page.tsx b/flowsint-web/src/app/dashboard/transforms/editor/page.tsx
index 7b1ab33f..909bb281 100644
--- a/flowsint-web/src/app/dashboard/transforms/editor/page.tsx
+++ b/flowsint-web/src/app/dashboard/transforms/editor/page.tsx
@@ -1,16 +1,7 @@
import TransformEditor from "@/components/transforms/editor"
-import { notFound } from "next/navigation"
+import { serverFetch } from "@/lib/server-fetch"
-async function fetchNodes() {
- const res = await fetch(`${process.env.NEXT_PUBLIC_DOCKER_FLOWSINT_API}/transforms/nodes`, {
- next: { revalidate: 3600 }
- })
- if (!res.ok) {
- notFound()
- }
- return res.json()
-}
export default async function Editor() {
- const nodesData = await fetchNodes()
+ const nodesData = await serverFetch(`${process.env.NEXT_PUBLIC_DOCKER_FLOWSINT_API}/transforms/raw_materials`)
return <TransformEditor nodesData={nodesData} />
}
\ No newline at end of file
diff --git a/flowsint-web/src/app/dashboard/transforms/page.tsx b/flowsint-web/src/app/dashboard/transforms/page.tsx
index a4368f8c..f9138a48 100644
--- a/flowsint-web/src/app/dashboard/transforms/page.tsx
+++ b/flowsint-web/src/app/dashboard/transforms/page.tsx
@@ -1,14 +1,14 @@
import { Button } from "@/components/ui/button"
import { Card, CardContent } from "@/components/ui/card"
-import { createClient } from "@/lib/supabase/server"
import { PlusCircle, FileCode2 } from "lucide-react"
import Link from "next/link"
import { TransformItem } from "@/components/transforms/transform-item"
+import { serverFetch } from "@/lib/server-fetch"
-const TransformsPage = async () => {
- const supabase = await createClient()
- const { data: transforms } = await supabase.from("transforms").select("*")
+const API_URL = `${process.env.NEXT_PUBLIC_DOCKER_FLOWSINT_API}/transforms`
+const TransformsPage = async () => {
+ const transforms = await serverFetch(API_URL)
return (
<div className="w-full space-y-8 container bg-background grow mx-auto py-12 px-8">
<div className="flex flex-col sm:flex-row justify-between items-start sm:items-center gap-4">
@@ -29,13 +29,13 @@ const TransformsPage = async () => {
<EmptyState />
) : (
<div className="w-full grid lg:grid-cols-3 md:grid-cols-2 grid-cols-1 xl:grid-cols-3 gap-5">
- {transforms.map((transform) => (
+ {transforms.map((transform: any) => (
<TransformItem key={transform.id} transform={transform} />
))}
</div>
)
}
- </div >
+ </div>
)
}
@@ -61,6 +61,4 @@ const EmptyState = () => {
)
}
-
-
export default TransformsPage
diff --git a/flowsint-web/src/app/login/page.tsx b/flowsint-web/src/app/login/page.tsx
index 2634fe8f..6c6cdefc 100644
--- a/flowsint-web/src/app/login/page.tsx
+++ b/flowsint-web/src/app/login/page.tsx
@@ -1,15 +1,13 @@
+import { auth } from "@/auth";
import { Message } from "@/components/form-message"
import LoginForm from "@/components/login-form"
-import { createClient } from "@/lib/supabase/server"
import { redirect } from "next/navigation"
export default async function Page(props: { searchParams: Promise<Message> }) {
- const supabase = await createClient()
- const { data, error } = await supabase.auth.getUser()
- if (!error || data.user) {
- redirect('/dashboard')
+ const session = await auth();
+ if (session) {
+ redirect("/");
}
-
return (
<div className="flex h-screen w-full items-center justify-center px-4">
<LoginForm searchParams={props.searchParams} />
diff --git a/flowsint-web/src/app/page.tsx b/flowsint-web/src/app/page.tsx
index fd022d46..994d279b 100644
--- a/flowsint-web/src/app/page.tsx
+++ b/flowsint-web/src/app/page.tsx
@@ -1,13 +1,9 @@
-import { createClient } from '@/lib/supabase/server';
+import { auth } from '@/auth';
import { redirect } from 'next/navigation';
export default async function Home() {
- const supabase = await createClient()
- const {
- data: { user },
- error: userError,
- } = await supabase.auth.getUser();
- if (!user || userError) {
+ const session = await auth();
+ if (!session) {
return redirect("/login")
}
return redirect("/dashboard")
diff --git a/flowsint-web/src/app/providers.tsx b/flowsint-web/src/app/providers.tsx
index 1f59a635..d824ce93 100644
--- a/flowsint-web/src/app/providers.tsx
+++ b/flowsint-web/src/app/providers.tsx
@@ -5,6 +5,7 @@ import * as React from "react";
import { ThemeProvider as NextThemesProvider } from "next-themes";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query"
import { useState } from "react"
+import { SessionProvider } from "next-auth/react";
export interface ProvidersProps {
children: React.ReactNode;
@@ -25,9 +26,11 @@ export function Providers({ children, themeProps }: ProvidersProps) {
)
return (
<NextThemesProvider {...themeProps}>
- <QueryClientProvider client={queryClient}>
- {children}
- </QueryClientProvider>
+ <SessionProvider>
+ <QueryClientProvider client={queryClient}>
+ {children}
+ </QueryClientProvider>
+ </SessionProvider>
</NextThemesProvider>
);
}
diff --git a/flowsint-web/src/app/register/page.tsx b/flowsint-web/src/app/register/page.tsx
new file mode 100644
index 00000000..68ed4324
--- /dev/null
+++ b/flowsint-web/src/app/register/page.tsx
@@ -0,0 +1,16 @@
+import { auth } from "@/auth";
+import { Message } from "@/components/form-message"
+import RegisterForm from "@/components/register-form"
+import { redirect } from "next/navigation"
+
+export default async function Page(props: { searchParams: Promise<Message> }) {
+ const session = await auth();
+ if (session) {
+ redirect("/");
+ }
+ return (
+ <div className="flex h-screen w-full items-center justify-center px-4">
+ <RegisterForm searchParams={props.searchParams} />
+ </div>
+ )
+}
\ No newline at end of file
diff --git a/flowsint-web/src/auth.ts b/flowsint-web/src/auth.ts
new file mode 100644
index 00000000..ab7c09bd
--- /dev/null
+++ b/flowsint-web/src/auth.ts
@@ -0,0 +1,60 @@
+import NextAuth, { User } from "next-auth"
+import Credentials from "next-auth/providers/credentials"
+
+declare module "next-auth" {
+ interface User {
+ accessToken?: string;
+ }
+}
+
+export const { handlers, signIn, signOut, auth } = NextAuth({
+ session: {
+ strategy: "jwt",
+ maxAge: 60 * 60,
+ },
+ providers: [
+ Credentials({
+ credentials: {
+ email: {},
+ password: {},
+ },
+
+ authorize: async (credentials) => {
+ const formData = new URLSearchParams();
+ formData.append("username", credentials?.email as string);
+ formData.append("password", credentials?.password as string);
+ const res = await fetch(`${process.env.NEXT_PUBLIC_DOCKER_FLOWSINT_API}/auth/token`, {
+ method: "POST",
+ headers: { "Content-Type": "application/x-www-form-urlencoded" },
+ body: formData.toString(),
+ });
+
+ const data = await res.json()
+
+ if (res.ok && data.access_token) {
+ return {
+ email: credentials?.email as string,
+ id: data.user_id,
+ accessToken: data.access_token,
+ }
+ }
+ return null
+ },
+ }),
+
+ ],
+ callbacks: {
+ jwt({ token, user }) {
+ if (user) {
+ token.id = user.id
+ token.accessToken = user.accessToken
+ }
+ return token
+ },
+ session({ session, token }) {
+ session.user.id = token.id as string
+ session.user.accessToken = token.accessToken as string
+ return session
+ },
+ },
+})
diff --git a/flowsint-web/src/components/dashboard/feedback.tsx b/flowsint-web/src/components/dashboard/feedback.tsx
index cfe6f0cc..ca699512 100644
--- a/flowsint-web/src/components/dashboard/feedback.tsx
+++ b/flowsint-web/src/components/dashboard/feedback.tsx
@@ -1,7 +1,6 @@
"use client"
import { useState } from "react"
-import { supabase } from "@/lib/supabase/client"
import { Button } from "@/components/ui/button"
import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover"
import type React from "react" // Added import for React
@@ -16,10 +15,7 @@ export default function Feedback() {
const formData = new FormData(e.currentTarget)
const data = Object.fromEntries(formData)
try {
- const { error } = await supabase
- .from("feedbacks")
- .insert({ ...data })
- if (error) return toast.error("Could not create new feedback:" + JSON.stringify(error))
+ // TODO
toast.success("Feedback submitted.")
setOpen(false)
} catch (error) {
diff --git a/flowsint-web/src/components/dashboard/new-investigation.tsx b/flowsint-web/src/components/dashboard/new-investigation.tsx
index c450a157..5005ca14 100644
--- a/flowsint-web/src/components/dashboard/new-investigation.tsx
+++ b/flowsint-web/src/components/dashboard/new-investigation.tsx
@@ -38,8 +38,6 @@ export default function NewInvestigation({ children, noDropDown }: { children: R
const result = await createNewInvestigation(formData)
if (result.success) {
toast.success("New investigation created.")
- if (result.path)
- toast.success("New storage bucket created.")
router.push(`/dashboard/investigations/${result.id}`)
setOpen(false)
} else {
diff --git a/flowsint-web/src/components/dashboard/recent-sketches.tsx b/flowsint-web/src/components/dashboard/recent-sketches.tsx
index 07a8fb35..2fbf8d5f 100644
--- a/flowsint-web/src/components/dashboard/recent-sketches.tsx
+++ b/flowsint-web/src/components/dashboard/recent-sketches.tsx
@@ -9,18 +9,15 @@ import { Card, CardContent } from "@/components/ui/card"
import { Skeleton } from "@/components/ui/skeleton"
import { formatDistanceToNow } from "date-fns"
import { AvatarList } from "../avatar-list"
+import { clientFetch } from "@/lib/client-fetch"
const RecentSketches = ({ limit = 4 }: { limit: string | number }) => {
- const {
- data: sketches,
- isLoading,
- error,
- } = useQuery({
- queryKey: ["dashboard", "sketches"],
+ const { data: sketches, error, isLoading } = useQuery({
+ queryKey: ["dashboard", "recent", "sketches"],
queryFn: async () => {
- const res = await fetch(`/api/latest-sketches?limit=${limit}`)
- return res.json()
+ const data = await clientFetch(`${process.env.NEXT_PUBLIC_FLOWSINT_API}/sketches?limit=${limit}`)
+ return data
},
refetchOnWindowFocus: true,
})
diff --git a/flowsint-web/src/components/dashboard/secondary-nav.tsx b/flowsint-web/src/components/dashboard/secondary-nav.tsx
index 05ec0703..1f7a11a8 100644
--- a/flowsint-web/src/components/dashboard/secondary-nav.tsx
+++ b/flowsint-web/src/components/dashboard/secondary-nav.tsx
@@ -21,7 +21,7 @@ const SecondaryNav = ({ profile_id }: { profile_id: string }) => {
<Button size={"sm"} variant={"ghost"}>Changelog</Button>
<Button size={"sm"} variant={"ghost"}>Docs</Button>
</div>
- <NavUser profile_id={profile_id} />
+ <NavUser />
</div>
)
}
diff --git a/flowsint-web/src/components/investigations/file-upload.tsx b/flowsint-web/src/components/investigations/file-upload.tsx
deleted file mode 100644
index b0166f30..00000000
--- a/flowsint-web/src/components/investigations/file-upload.tsx
+++ /dev/null
@@ -1,215 +0,0 @@
-"use client"
-
-import type React from "react"
-
-import { useState, useRef } from "react"
-import { supabase } from "@/lib/supabase/client"
-import { Upload, X, FileText, CheckCircle, AlertCircle } from "lucide-react"
-import { sanitize } from '@/lib/utils'
-
-import { cn } from "@/lib/utils"
-import { Button } from "@/components/ui/button"
-import {
- Dialog,
- DialogContent,
- DialogDescription,
- DialogFooter,
- DialogHeader,
- DialogTitle,
-} from "@/components/ui/dialog"
-import { Progress } from "@/components/ui/progress"
-import { useInvestigationStore } from "@/store/investigation-store"
-import { toast } from "sonner"
-import { useParams, useRouter } from "next/navigation"
-
-type FileStatus = "idle" | "uploading" | "success" | "error"
-
-interface FileWithStatus {
- file: File
- status: FileStatus
- progress: number
- error?: string
-}
-
-export default function FileUploadDialog() {
- const { investigation_id } = useParams()
- const { openUploadModal: open, setOpenUploadModal: setOpen } = useInvestigationStore()
- const router = useRouter()
- const [files, setFiles] = useState<FileWithStatus[]>([])
- const [isDragging, setIsDragging] = useState(false)
- const fileInputRef = useRef<HTMLInputElement>(null)
-
- const handleDragOver = (e: React.DragEvent<HTMLDivElement>) => {
- e.preventDefault()
- e.stopPropagation()
- setIsDragging(true)
- }
-
- const handleDragLeave = (e: React.DragEvent<HTMLDivElement>) => {
- e.preventDefault()
- e.stopPropagation()
- setIsDragging(false)
- }
-
- const handleDrop = (e: React.DragEvent<HTMLDivElement>) => {
- e.preventDefault()
- e.stopPropagation()
- setIsDragging(false)
-
- if (e.dataTransfer.files && e.dataTransfer.files.length > 0) {
- const newFiles = Array.from(e.dataTransfer.files).map((file) => ({
- file,
- status: "idle" as FileStatus,
- progress: 0,
- }))
- setFiles((prev) => [...prev, ...newFiles])
- }
- }
-
- const handleFileChange = (e: React.ChangeEvent<HTMLInputElement>) => {
- if (e.target.files && e.target.files.length > 0) {
- const newFiles = Array.from(e.target.files).map((file) => ({
- file,
- status: "idle" as FileStatus,
- progress: 0,
- }))
- setFiles((prev) => [...prev, ...newFiles])
- }
- }
-
- const removeFile = (index: number) => {
- setFiles((prev) => prev.filter((_, i) => i !== index))
- }
-
- const uploadFiles = async () => {
- for (let i = 0; i < files.length; i++) {
- if (files[i].status !== "idle") continue
-
- // Update status to uploading
- setFiles((prev) => prev.map((file, idx) => (idx === i ? { ...file, status: "uploading" } : file)))
- try {
- const file = files[i].file
- const safeName = sanitize(file.name)
- const filePath = `${investigation_id}/${safeName}`
- // Upload file to Supabase
- const { error } = await supabase.storage.from("documents").upload(filePath, file)
- // Simulate progress tracking (if needed)
- setFiles((prev) => prev.map((file, idx) => (idx === i ? { ...file, progress: 100 } : file)))
- if (error) throw toast.error("Error uploading file: " + error.message)
- // Update status to success
- setFiles((prev) => prev.map((file, idx) => (idx === i ? { ...file, status: "success", progress: 100 } : file)))
- toast.success("File uploaded successfully")
- router.refresh()
- } catch (error) {
- toast.error("Error uploading file: " + JSON.stringify(error))
- setFiles((prev) =>
- prev.map((file, idx) =>
- idx === i
- ? {
- ...file,
- status: "error",
- error: error instanceof Error ? error.message : "Unknown error",
- }
- : file,
- ),
- )
- }
- }
- }
-
- const handleButtonClick = () => {
- fileInputRef.current?.click()
- }
-
- const allFilesProcessed =
- files.length > 0 && files.every((file) => file.status === "success" || file.status === "error")
- const resetDialog = () => {
- setFiles([])
- }
- const closeDialog = () => {
- setOpen(false)
- setTimeout(resetDialog, 300) // Reset after dialog close animation
- }
- return (
- <Dialog open={open} onOpenChange={setOpen}>
- <DialogContent className="sm:max-w-[700px] overflow-y-auto max-h-[80vh]">
- <DialogHeader>
- <DialogTitle>Upload Files</DialogTitle>
- <DialogDescription>Drag and drop files to upload to the documents bucket.</DialogDescription>
- </DialogHeader>
- <div
- className={cn(
- "mt-4 border-2 border-dashed rounded-lg p-6 transition-colors",
- isDragging ? "border-primary bg-primary/5" : "border-muted-foreground/25",
- files.length > 0 ? "h-auto" : "h-40",
- )}
- onDragOver={handleDragOver}
- onDragLeave={handleDragLeave}
- onDrop={handleDrop}
- >
- {files.length === 0 ? (
- <div className="h-full flex flex-col items-center justify-center gap-2 text-center">
- <Upload className="h-10 w-10 text-muted-foreground" />
- <p className="text-sm text-muted-foreground">Drag and drop files here or click to browse</p>
- <Button variant="secondary" size="sm" className="mt-2" onClick={handleButtonClick}>
- Select Files
- </Button>
- <input type="file" ref={fileInputRef} className="hidden" onChange={handleFileChange} multiple />
- </div>
- ) : (
- <div className="space-y-4 w-full">
- {files.map((fileItem, index) => (
- <div key={index} className="flex items-start gap-3 bg-muted/50 p-3 rounded-md w-full">
- <FileText className="h-5 w-5 flex-shrink-0 text-muted-foreground" />
- <div className="flex-1 min-w-0 w-full truncate">
- <p className="text-sm font-medium w-full truncate">{fileItem.file.name}</p>
- <p className="text-xs text-muted-foreground">{(fileItem.file.size / 1024).toFixed(1)} KB</p>
-
- {fileItem.status === "uploading" && <Progress value={fileItem.progress} className="h-1 mt-2" />}
-
- {fileItem.status === "error" && <p className="text-xs text-destructive mt-1">{fileItem.error}</p>}
- </div>
-
- <div className="flex-shrink-0">
- {fileItem.status === "idle" && (
- <Button variant="ghost" size="icon" className="h-6 w-6" onClick={() => removeFile(index)}>
- <X className="h-4 w-4" />
- <span className="sr-only">Remove file</span>
- </Button>
- )}
-
- {fileItem.status === "success" && <CheckCircle className="h-5 w-5 text-green-500" />}
-
- {fileItem.status === "error" && <AlertCircle className="h-5 w-5 text-destructive" />}
- </div>
- </div>
- ))}
-
- {!allFilesProcessed && (
- <Button variant="secondary" size="sm" className="mt-2" onClick={handleButtonClick}>
- Add More Files
- </Button>
- )}
- </div>
- )}
- </div>
-
- <DialogFooter className="mt-4">
- {allFilesProcessed ? (
- <Button onClick={closeDialog}>Done</Button>
- ) : (
- <>
- <Button variant="outline" onClick={closeDialog}>
- Cancel
- </Button>
- <Button onClick={uploadFiles} disabled={files.length === 0 || files.every((f) => f.status !== "idle")}>
- Upload
- </Button>
- </>
- )}
- </DialogFooter>
- </DialogContent>
- </Dialog>
- )
-}
-
diff --git a/flowsint-web/src/components/investigations/investigation-selector.tsx b/flowsint-web/src/components/investigations/investigation-selector.tsx
index d78b00cd..e3526e2b 100644
--- a/flowsint-web/src/components/investigations/investigation-selector.tsx
+++ b/flowsint-web/src/components/investigations/investigation-selector.tsx
@@ -11,19 +11,20 @@ import { Skeleton } from "@/components/ui/skeleton";
import { useQuery } from "@tanstack/react-query";
import { Investigation } from "@/types/investigation";
import { Badge } from '../ui/badge';
+import { clientFetch } from "@/lib/client-fetch";
export default function InvestigationSelector() {
const router = useRouter()
const { investigation_id } = useParams()
- const { data, isLoading } = useQuery({
- queryKey: ["dashboard", "investigations"],
+
+ const { data: investigations, isLoading } = useQuery({
+ queryKey: [process.env.NEXT_PUBLIC_DOCKER_FLOWSINT_API, "dashboard", "selector", investigation_id],
queryFn: async () => {
- const res = await fetch(`/api/investigations`)
- return res.json()
+ const data = await clientFetch(`${process.env.NEXT_PUBLIC_FLOWSINT_API}/investigations`)
+ return data
},
refetchOnWindowFocus: true,
})
- const investigations = data?.investigations || []
const handleSelectionChange = (value: string) => {
router.push(`/dashboard/investigations/${value}`);
diff --git a/flowsint-web/src/components/login-form.tsx b/flowsint-web/src/components/login-form.tsx
index 99c74943..a15d1b9a 100644
--- a/flowsint-web/src/components/login-form.tsx
+++ b/flowsint-web/src/components/login-form.tsx
@@ -1,8 +1,6 @@
import Link from "next/link"
-import { Github } from "lucide-react"
-import { Button } from "@/components/ui/button"
-import { login, signInWithGithub } from "@/lib/actions/auth"
-import { Card, CardHeader, CardContent, CardFooter } from "@/components/ui/card"
+import { login } from "@/lib/actions/auth"
+import { Card, CardHeader, CardContent } from "@/components/ui/card"
import { Input } from "@/components/ui/input"
import { Label } from "@/components/ui/label"
import { SubmitButton } from "./submit-button"
@@ -35,31 +33,8 @@ export default async function LoginForm(props: { searchParams: Promise<Message>
Log in
</SubmitButton>
<FormMessage message={searchParams} />
- <div className="relative">
- <div className="absolute inset-0 flex items-center">
- <span className="w-full border-t" />
- </div>
- <div className="relative flex justify-center text-xs uppercase">
- <span className="bg-background px-2 text-muted-foreground">Or continue with</span>
- </div>
- </div>
</form>
- <form>
- <SubmitButton pendingText="Logging in..." formAction={signInWithGithub} variant="outline" className="w-full">
- <Github className="mr-2 h-4 w-4" />
- Login with Github
- </SubmitButton>
- </form>
-
</CardContent>
- {/* <CardFooter className="flex justify-center">
- <div className="text-sm text-muted-foreground">
- Don&apos;t have an account?{" "}
- <Button variant="link" formAction={signup} className="p-0">
- Sign up
- </Button>
- </div>
- </CardFooter> */}
</Card>
)
}
diff --git a/flowsint-web/src/components/nav-user.tsx b/flowsint-web/src/components/nav-user.tsx
index 66e68302..54ef797b 100644
--- a/flowsint-web/src/components/nav-user.tsx
+++ b/flowsint-web/src/components/nav-user.tsx
@@ -35,50 +35,39 @@ import EnvIndicator from "./env-indicator"
import { cn, getAvatarColor } from "@/lib/utils"
import { getInitials } from "@/lib/utils"
import { useQuery } from "@tanstack/react-query"
-export function NavUser({
- profile_id,
-}: {
- profile_id: any
-}) {
- const { isMobile } = useSidebar()
+import { useSession } from "next-auth/react"
+import { Button } from "@/components/ui/button"
- const {
- data: profile,
- isLoading,
- error,
- } = useQuery({
- queryKey: ["profiles", profile_id],
- queryFn: async () => {
- const res = await fetch(`/api/profiles/${profile_id}`)
- return res.json()
- },
- refetchOnWindowFocus: true,
- })
+export function NavUser() {
- if (isLoading) return
+ const session = useSession()
+ console.log("session", session)
- const renderAvatar = () => {
- const name = `${profile?.first_name || "fd"} ${profile?.last_name || "fd"}`
- const avatarColor = getAvatarColor(name)
- const avatar = (
- <div className="relative">
- {isLoading ? "" :
- <Avatar
- key={profile.id}
- className={cn(
- 'h-8 w-8',
- "border-2 border-background bg-background relative",
- "transition-transform",
- "ring-0 ring-offset-0",
- )}
- >
- <AvatarImage src={profile.avatar_url} alt={``} />
- <AvatarFallback className={cn("text-xs text-white", avatarColor)}>{getInitials(name)}</AvatarFallback>
- </Avatar>}
- </div>
- )
- return avatar
+ if (session.status === "loading") {
+ return <div className="h-8 w-8 animate-pulse rounded-full bg-gray-200" />
}
+ // const renderAvatar = () => {
+ // const name = `${session?.user?.first_name || "fd"} ${session?.user?.last_name || "fd"}`
+ // const avatarColor = getAvatarColor(name)
+ // const avatar = (
+ // <div className="relative">
+ // {isLoading ? "" :
+ // <Avatar
+ // key={profile.id}
+ // className={cn(
+ // 'h-8 w-8',
+ // "border-2 border-background bg-background relative",
+ // "transition-transform",
+ // "ring-0 ring-offset-0",
+ // )}
+ // >
+ // <AvatarImage src={profile.avatar_url} alt={``} />
+ // <AvatarFallback className={cn("text-xs text-white", avatarColor)}>{getInitials(name)}</AvatarFallback>
+ // </Avatar>}
+ // </div>
+ // )
+ // return avatar
+ // }
return (
<SidebarMenu>
@@ -89,21 +78,22 @@ export function NavUser({
size="lg"
className="p-0 h-auto rounded-full cursor-pointer p-1"
>
- {renderAvatar()}
+ <div className="h-8 w-8 rounded-full bg-muted" />
</SidebarMenuButton>
</DropdownMenuTrigger>
<DropdownMenuContent
className="w-(--radix-dropdown-menu-trigger-width) min-w-56 rounded-lg"
- side={isMobile ? "bottom" : "right"}
align="end"
sideOffset={4}
>
<DropdownMenuLabel className="p-0 font-normal">
<div className="flex items-center gap-2 px-1 py-1.5 text-left text-sm">
- {renderAvatar()}
+ <div className="h-8 w-8 rounded-full bg-muted" />
<div className="grid flex-1 text-left text-sm leading-tight">
- <span className="truncate font-semibold">{profile.name}</span>
- <span className="truncate text-xs">{profile.email}</span>
+ {/* @ts-ignore */}
+ <span className="truncate font-semibold">{session?.user?.email}</span>
+ {/* @ts-ignore */}
+ <span className="truncate text-xs">{session?.user?.email}</span>
</div>
</div>
</DropdownMenuLabel>
diff --git a/flowsint-web/src/components/register-form.tsx b/flowsint-web/src/components/register-form.tsx
new file mode 100644
index 00000000..3b31705c
--- /dev/null
+++ b/flowsint-web/src/components/register-form.tsx
@@ -0,0 +1,41 @@
+import Link from "next/link"
+import { register } from "@/lib/actions/auth"
+import { Card, CardHeader, CardContent } from "@/components/ui/card"
+import { Input } from "@/components/ui/input"
+import { Label } from "@/components/ui/label"
+import { SubmitButton } from "./submit-button"
+import { FormMessage, Message } from "./form-message"
+
+export default async function RegisterForm(props: { searchParams: Promise<Message> }) {
+ const searchParams = await props.searchParams;
+ return (
+ <Card className="mx-auto bg-background w-full max-w-md">
+ <CardHeader className="space-y-1">
+ <h2 className="text-2xl font-semibold tracking-tight">Register</h2>
+ <p className="text-sm text-muted-foreground">Create an account.</p>
+ </CardHeader>
+ <CardContent className="space-y-4">
+ <form className="space-y-4">
+ <div className="space-y-2">
+ <Label htmlFor="email">Email</Label>
+ <Input id="email" type="email" name="email" placeholder="[email protected]" required />
+ </div>
+ <div className="space-y-2">
+ <div className="flex items-center justify-between">
+ <Label htmlFor="password">Password</Label>
+ <Link href="#" className="text-xs text-muted-foreground underline-offset-4 hover:underline">
+ Forgot password?
+ </Link>
+ </div>
+ <Input id="password" name="password" type="password" placeholder="Your password" required />
+ </div>
+ <SubmitButton pendingText="Signing in..." formAction={register} className="w-full">
+ Sign up
+ </SubmitButton>
+ <FormMessage message={searchParams} />
+ </form>
+ </CardContent>
+ </Card>
+ )
+}
+
diff --git a/flowsint-web/src/components/sketches/add-contributor.tsx b/flowsint-web/src/components/sketches/add-contributor.tsx
index f9f6fa6a..f84f2f03 100644
--- a/flowsint-web/src/components/sketches/add-contributor.tsx
+++ b/flowsint-web/src/components/sketches/add-contributor.tsx
@@ -20,9 +20,9 @@ import {
import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover"
import { toast } from "sonner"
import { cn, getAvatarColor } from "@/lib/utils"
-import { supabase } from "@/lib/supabase/client"
import { Avatar, AvatarFallback, AvatarImage } from "../ui/avatar"
import { Profile } from "@/types"
+import { clientFetch } from "@/lib/client-fetch"
interface AddInvestigationModalProps {
sketchId: string
@@ -38,31 +38,24 @@ export function AddInvestigationModal({ sketchId, open, setOpen }: AddInvestigat
isLoading,
refetch,
} = useQuery({
- queryKey: ["profiles"],
+ queryKey: [process.env.NEXT_PUBLIC_DOCKER_FLOWSINT_API, "profiles",],
queryFn: async () => {
- const response = await fetch("/api/profiles")
- if (!response.ok) {
- throw new Error("Erreur lors de la récupération des profils")
- }
- return response.json()
+ const data = await clientFetch(`${process.env.NEXT_PUBLIC_FLOWSINT_API}/profiles`)
+ return data
},
- enabled: false, // Don't fetch on component mount, only when needed
+ enabled: false,
})
// Mutation for adding a profile to investigation
const mutation = useMutation({
mutationFn: async ({ profile_id, sketch_id }: { profile_id: string; sketch_id: string }) => {
- const { error } = await supabase.from("sketches_profiles").upsert({ profile_id, sketch_id })
- if (error)
- throw (error)
+ // TODO
},
onSuccess: () => {
toast.success(`${selectedProfile?.first_name} ${selectedProfile?.last_name} a été ajouté à l'investigation`)
setOpen(false)
},
onError: (e: { code: string }) => {
- if (e.code === "42501")
- return toast.error("You don't have permission to add a new collaborator.")
return toast.error("An error occured. Try again later.")
},
})
@@ -70,7 +63,7 @@ export function AddInvestigationModal({ sketchId, open, setOpen }: AddInvestigat
const handleOpenChange = (newOpen: boolean) => {
setOpen(newOpen)
if (newOpen) {
- refetch() // Fetch profiles when modal opens
+ refetch()
} else {
setSelectedProfile(null)
}
diff --git a/flowsint-web/src/components/sketches/more-menu.tsx b/flowsint-web/src/components/sketches/more-menu.tsx
index adaaecc3..313cc325 100644
--- a/flowsint-web/src/components/sketches/more-menu.tsx
+++ b/flowsint-web/src/components/sketches/more-menu.tsx
@@ -1,5 +1,4 @@
import { Ellipsis } from "lucide-react";
-import { supabase } from "@/lib/supabase/client";
import {
DropdownMenu,
DropdownMenuTrigger,
@@ -27,13 +26,7 @@ export default function MoreMenu({ sketch, user_id }: { sketch: Sketch, user_id:
if (!sketch_id) {
throw new Error("No sketch ID provided");
}
- const { error } = await supabase
- .from('sketches')
- .delete()
- .eq('id', sketch_id);
- if (error) {
- throw error;
- }
+ // TODO
router.push(`/dashboard/investigations/${sketch.investigation_id}`)
return "Sketch successfully deleted";
},
diff --git a/flowsint-web/src/components/sketches/scans-drawer/scan-button.tsx b/flowsint-web/src/components/sketches/scans-drawer/scan-button.tsx
deleted file mode 100644
index fed32101..00000000
--- a/flowsint-web/src/components/sketches/scans-drawer/scan-button.tsx
+++ /dev/null
@@ -1,152 +0,0 @@
-"use client"
-
-import { useEffect, useState } from "react"
-import { Zap, ZapIcon } from "lucide-react"
-import { createClient } from "@supabase/supabase-js"
-import { useQueryState } from "nuqs"
-
-import { Button } from "@/components/ui/button"
-import { Badge } from "@/components/ui/badge"
-import {
- Sheet,
- SheetClose,
- SheetContent,
- SheetDescription,
- SheetFooter,
- SheetHeader,
- SheetTitle,
- SheetTrigger,
-} from "@/components/ui/sheet"
-import { ScanTable } from "./scan-table"
-import { toast } from "sonner"
-import { supabase } from "@/lib/supabase/client"
-import { notFound, useParams } from "next/navigation"
-import { useQuery } from "@tanstack/react-query"
-export type Scan = {
- id: string
- value: string
- status: "pending" | "finished" | "failed"
- scan_name: string
- results: { results: any[] }
-}
-
-export function ScanButton() {
- const [scans, setScans] = useState<Scan[]>([])
- const [pendingCount, setPendingCount] = useState(0)
- const [scanId, setScanId] = useQueryState("scan_id")
- const [open, setOpen] = useState(false)
- const { investigation_id, sketch_id } = useParams()
-
- const { refetch } = useQuery({
- queryKey: ["investigations", investigation_id, 'sketches', sketch_id, "data"],
- queryFn: async () => {
- const res = await fetch(`/api/investigations/${investigation_id}/sketches/${sketch_id}/sketch`)
- if (!res.ok) {
- notFound()
- }
- return res.json()
- },
- refetchOnWindowFocus: true,
- })
-
- useEffect(() => {
- // Initial fetch of scans
- const fetchScans = async () => {
- const { data, error } = await supabase.from("scans").select("*").eq("sketch_id", sketch_id).order("created_at", { ascending: false })
- if (error) {
- console.error("Error fetching scans:", error)
- return
- }
- setScans(data || [])
- updatePendingCount(data || [])
- }
- fetchScans()
- // Set up real-time subscription
- const subscription = supabase
- .channel("scans-channel")
- .on(
- "postgres_changes",
- {
- event: "*",
- schema: "public",
- table: "scans",
- filter: `sketch_id=eq.${sketch_id}`,
- },
- (payload) => {
- // Handle different types of changes
- if (payload.eventType === "INSERT") {
- setScans((current) => {
- const newScans = [...current, payload.new as Scan]
- updatePendingCount(newScans)
- return newScans
- })
- } else if (payload.eventType === "UPDATE") {
- setScans((current) => {
- const newScans = current.map((scan) => (scan.id === payload.new.id ? (payload.new as Scan) : scan))
- updatePendingCount(newScans)
- toast.success('Scan complete on this item ! Refreshing now.')
- refetch()
- return newScans
- })
- } else if (payload.eventType === "DELETE") {
- setScans((current) => {
- const newScans = current.filter((scan) => scan.id !== payload.old.id)
- updatePendingCount(newScans)
- return newScans
- })
- }
- },
- )
- .subscribe()
-
- return () => {
- // Clean up subscription
- supabase.removeChannel(subscription)
- }
- }, [])
-
- const updatePendingCount = (scans: Scan[]) => {
- const count = scans.filter((scan) => scan.status === "pending").length
- setPendingCount(count)
- }
-
- const handleScanClick = (id: string) => {
- setScanId(id)
- }
-
- return (
- <Sheet open={open} onOpenChange={setOpen}>
- <SheetTrigger asChild>
- <Button variant="ghost" className="rounded-none">
- {pendingCount > 0 ? (
- <div className="pr-1">
- <ZapIcon fill="var(--primary)" stroke="var(--primary)" className="!h-5 !w-5 animate-pulse" />
- <Badge className='absolute -top-0 right-2 text-xs rounded-full h-4 w-4' variant={"default"}>{pendingCount}</Badge>
- </div>
- ) : (
- <>
- <ZapIcon className="!h-4.5 !w-4.5 opacity-60" />
- </>
- )}
- </Button>
- </SheetTrigger>
- <SheetContent className="w-full !max-w-[500px]">
- <div className="mx-auto w-full !max-w-[500px] h-screen overflow-auto">
- <SheetHeader>
- <SheetTitle>Scans</SheetTitle>
- <SheetDescription>View all your scans. Click on a scan to select it.</SheetDescription>
- </SheetHeader>
- <div className="p-4">
- <ScanTable scans={scans} onScanClick={handleScanClick} selectedScanId={scanId || ""} />
- </div>
- <SheetFooter>
- <SheetClose asChild>
- <Button variant="outline">Close</Button>
- </SheetClose>
- </SheetFooter>
- </div>
- </SheetContent>
- </Sheet>
- )
-}
-
diff --git a/flowsint-web/src/components/sketches/scans-drawer/scan-table.tsx b/flowsint-web/src/components/sketches/scans-drawer/scan-table.tsx
deleted file mode 100644
index 46d884af..00000000
--- a/flowsint-web/src/components/sketches/scans-drawer/scan-table.tsx
+++ /dev/null
@@ -1,61 +0,0 @@
-"use client"
-
-import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table"
-import { Badge } from "@/components/ui/badge"
-import type { Scan } from "./scan-button"
-
-interface ScanTableProps {
- scans: Scan[]
- onScanClick: (id: string) => void
- selectedScanId: string
-}
-
-export function ScanTable({ scans, onScanClick, selectedScanId }: ScanTableProps) {
- return (
- <Table>
- <TableHeader>
- <TableRow>
- <TableHead>Item</TableHead>
- <TableHead>Type</TableHead>
- <TableHead>Status</TableHead>
- <TableHead>Results</TableHead>
- </TableRow>
- </TableHeader>
- <TableBody>
- {scans.length === 0 ? (
- <TableRow>
- <TableCell colSpan={4} className="text-center">
- No scans yet.
- </TableCell>
- </TableRow>
- ) : (
- scans.map((scan) => (
- <TableRow
- key={scan.id}
- className={`cursor-pointer hover:bg-muted/50 ${selectedScanId === scan.id ? "bg-muted" : ""}`}
- onClick={() => onScanClick(scan.id)}
- >
- <TableCell className="font-medium"><span className=" max-w-[200px] block truncate text-ellipsis">{scan.value}</span></TableCell>
- <TableCell className="font-medium"><span className=" max-w-[200px] block truncate text-ellipsis">{scan.scan_name}</span></TableCell>
- <TableCell>
- {scan.status === "pending" ? (
- <Badge variant="default" className="bg-yellow-500 hover:bg-yellow-600">
- Pending
- </Badge>
- ) : scan.status === "finished" ? (
- <Badge variant="default" className="bg-green-500 hover:bg-green-600">
- Completed
- </Badge>
- ) : (
- <Badge variant="destructive">Failed</Badge>
- )}
- </TableCell>
- <TableCell>{!scan?.results ? "pending..." : `${scan?.results?.results?.length} results`}</TableCell>
- </TableRow>
- ))
- )}
- </TableBody>
- </Table>
- )
-}
-
diff --git a/flowsint-web/src/components/sketches/sketch-navigation.tsx b/flowsint-web/src/components/sketches/sketch-navigation.tsx
deleted file mode 100644
index e015d64f..00000000
--- a/flowsint-web/src/components/sketches/sketch-navigation.tsx
+++ /dev/null
@@ -1,90 +0,0 @@
-"use client"
-
-import { cn } from "@/lib/utils"
-import { Users, TimerIcon, MapIcon, WaypointsIcon, TablePropertiesIcon } from 'lucide-react'
-import Link from "next/link"
-import { usePathname } from "next/navigation"
-import { Fragment, memo, useMemo } from "react"
-import MoreMenu from "./more-menu"
-import { ScanButton } from "./scans-drawer/scan-button"
-import { Badge } from "../ui/badge"
-import { DownloadButton } from "../download-button"
-import { AvatarList } from "../avatar-list"
-import { Sketch } from "@/types/sketch"
-import { Profile } from "@/types"
-
-function SketchNavigation({ investigation_id, sketch_id, sketch, user_id }: { investigation_id: string, sketch_id: string, sketch: Sketch, user_id: string }) {
- const pathname = usePathname()
-
- // Memoize the sections array so it doesn't get recreated on every render
- const sections = useMemo(() => [
- {
- id: "sketch",
- name: "Sketch",
- href: `/dashboard/investigations/${investigation_id}/sketches/${sketch_id}`,
- icon: WaypointsIcon
- },
- {
- id: "table",
- name: "Table",
- href: `/dashboard/investigations/${investigation_id}/sketches/${sketch_id}/table`,
- icon: TablePropertiesIcon,
- },
- {
- id: "map",
- name: "Map",
- href: `/dashboard/investigations/${investigation_id}/sketches/${sketch_id}/map`,
- icon: MapIcon,
- disabled: true,
- },
- {
- id: "timeline",
- name: "Timeline",
- href: `/dashboard/investigations/${investigation_id}/sketches/${sketch_id}/timeline`,
- icon: TimerIcon,
- disabled: true,
- }
- ], [investigation_id, sketch_id]);
-
- return (
- <div className="flex items-center justify-between w-full">
- <div className="flex overflow-auto">
- {sections.map((section) => (
- <Fragment key={section.id}>
- {section.disabled ?
- <span
- className="text-muted-foreground border-b-2 border-transparent opacity-40 text-sm px-4 py-2.5 flex items-center gap-2">
- <section.icon className="h-4 w-4" />
- <span>{section.name}</span>
- <Badge variant={"outline"}>Soon</Badge>
- </span> :
- <Link
- href={section?.href || ""}
- className={cn(
- "flex items-center text-sm gap-2 border-b-2 border-transparent px-4 py-2 transition-colors",
- section?.href == pathname
- ? "bg-background text-accent-foreground border-b-primary"
- : "text-muted-foreground hover:text-foreground hover:bg-background/50",
- )}
- >
- <section.icon className="h-4 w-4" />
- <span>{section.name}</span>
- </Link>}
- </Fragment>
- ))}
- </div>
- <div className="flex items-center">
- <div className="px-2">
- <AvatarList size="md" users={sketch?.members?.map(({ profile }: { profile: Profile }) => ({ ...profile, owner: profile.id === sketch.owner_id })) || []} />
- </div>
- <DownloadButton endpoint={`/api/investigations/${investigation_id}/sketches/${sketch_id}/table`} name={investigation_id} />
- <MoreMenu sketch={sketch} user_id={user_id} />
- <ScanButton />
- </div>
- </div >
- )
-}
-
-export const MemoizedInvestigationNavigation = memo(SketchNavigation);
-
-export { MemoizedInvestigationNavigation as SketchNavigation };
\ No newline at end of file
diff --git a/flowsint-web/src/components/sketches/sketch-selector.tsx b/flowsint-web/src/components/sketches/sketch-selector.tsx
index fa2db652..12984e6d 100644
--- a/flowsint-web/src/components/sketches/sketch-selector.tsx
+++ b/flowsint-web/src/components/sketches/sketch-selector.tsx
@@ -1,5 +1,4 @@
"use client"
-import { useSketch, useSketches } from "@/lib/hooks/sketches";
import { useParams, useRouter } from "next/navigation";
import {
Select,
@@ -11,13 +10,22 @@ import {
import { Skeleton } from "@/components/ui/skeleton";
import { WaypointsIcon } from "lucide-react";
import { Badge } from "../ui/badge";
+import { useQuery } from "@tanstack/react-query";
+import { clientFetch } from "@/lib/client-fetch";
+import { Sketch } from "@/types/sketch";
export default function CaseSelector() {
const router = useRouter()
const { sketch_id, investigation_id } = useParams()
- const { sketches, isLoading } = useSketches(investigation_id as string)
- const sketch = useSketch(sketch_id as string);
+ const { data: sketches, isLoading } = useQuery({
+ queryKey: [process.env.NEXT_PUBLIC_DOCKER_FLOWSINT_API, "dashboard", "sketches", "selector", investigation_id, sketch_id],
+ queryFn: async () => {
+ const data = await clientFetch(`${process.env.NEXT_PUBLIC_FLOWSINT_API}/investigations/${investigation_id}/sketches`)
+ return data
+ },
+ refetchOnWindowFocus: true,
+ })
const handleSelectionChange = (value: string) => {
value === "overview" ? router.push(`/dashboard/investigations/${investigation_id}`) :
@@ -25,14 +33,14 @@ export default function CaseSelector() {
};
return (
<div className="flex items-center">
- {isLoading || sketch.isLoading ? <Skeleton className="h-8 w-40 bg-foreground/10" /> :
- <Select onValueChange={handleSelectionChange} defaultValue={sketch?.data?.id}>
+ {isLoading ? <Skeleton className="h-8 w-40 bg-foreground/10" /> :
+ <Select onValueChange={handleSelectionChange} defaultValue={sketch_id as string || "overview"}>
<SelectTrigger className="min-w-none h-8 rounded-sm w-full hover:bg-foreground/10 font-medium shadow-none border-none text-ellipsis truncate gap-1 inset-shadow-none">
- <SelectValue defaultValue={sketch?.data?.title || ""} placeholder="Select an investigation" />
+ <SelectValue placeholder="Select a sketch" />
</SelectTrigger>
<SelectContent>
<SelectItem className="text-ellipsis truncate" value={"overview"}>{"Overview"}</SelectItem>
- {sketches?.map((sketch) => (
+ {sketches?.map((sketch: Sketch) => (
<SelectItem className="text-ellipsis truncate items-center" key={sketch.id} value={sketch.id}>{sketch.title} <Badge variant={"outline"} className="ml-1 rounded-full shadow-none !flex items-center gap-1"><WaypointsIcon className="!h-3 !w-3" />Sketch</Badge></SelectItem>
))}
</SelectContent>
diff --git a/flowsint-web/src/components/sketches/sketch/launch-transform.tsx b/flowsint-web/src/components/sketches/sketch/launch-transform.tsx
index 53316f24..a1b5cc68 100644
--- a/flowsint-web/src/components/sketches/sketch/launch-transform.tsx
+++ b/flowsint-web/src/components/sketches/sketch/launch-transform.tsx
@@ -1,7 +1,6 @@
"use client"
import { useState } from "react"
-import { useTransforms } from "@/hooks/use-transforms"
import { Button } from "@/components/ui/button"
import { Sparkles } from "lucide-react"
import {
@@ -17,6 +16,8 @@ import { RadioGroup, RadioGroupItem } from "@/components/ui/radio-group"
import { Label } from "@/components/ui/label"
import { useLaunchTransform } from "@/hooks/use-launch-transform"
import { formatDistanceToNow } from "date-fns"
+import { useQuery } from "@tanstack/react-query"
+import { clientFetch } from "@/lib/client-fetch"
interface Transform {
id: string
@@ -29,10 +30,19 @@ interface Transform {
const LaunchTransform = ({ values, type, sketch_id }: { values: string[], type: string, sketch_id: string }) => {
const { launchTransform } = useLaunchTransform()
- const { data: transforms, isLoading } = useTransforms(type)
const [isOpen, setIsOpen] = useState(false)
const [selectedTransform, setSelectedTransform] = useState<Transform | null>(null)
+ const { data: transforms, isLoading } = useQuery({
+ queryKey: [process.env.NEXT_PUBLIC_DOCKER_FLOWSINT_API, "dashboard", "transforms", type],
+ queryFn: async () => {
+ const data = await clientFetch(`${process.env.NEXT_PUBLIC_FLOWSINT_API}/transforms?category=${type}`)
+ return data
+ },
+ refetchOnWindowFocus: true,
+ })
+
+
const handleOpenModal = () => {
setIsOpen(true)
}
diff --git a/flowsint-web/src/components/sketches/sketch/nodes/node-notes-editor.tsx b/flowsint-web/src/components/sketches/sketch/nodes/node-notes-editor.tsx
index 7ff124c9..14c5b4ca 100644
--- a/flowsint-web/src/components/sketches/sketch/nodes/node-notes-editor.tsx
+++ b/flowsint-web/src/components/sketches/sketch/nodes/node-notes-editor.tsx
@@ -4,7 +4,6 @@ import { useState } from "react"
import { useEditor, EditorContent } from "@tiptap/react"
import StarterKit from "@tiptap/starter-kit"
import { Bold, Italic, List, ListOrdered, Heading2 } from "lucide-react"
-import { supabase } from "@/lib/supabase/client"
import { toast } from "sonner"
import { Button } from "@/components/ui/button"
import {
@@ -62,10 +61,7 @@ export function NodeNotesEditor({ openNote, setOpenNote, individualId }: NoteEdi
}
setIsSaving(true)
try {
- const { error } = await supabase.from("individuals").update({
- notes: content
- }).eq("id", individualId)
- if (error) throw error
+ // TODO
toast.success("Note saved successfully")
editor.commands.setContent("")
setOpenNote(false)
diff --git a/flowsint-web/src/components/transforms/editor.tsx b/flowsint-web/src/components/transforms/editor.tsx
index 1790f1d4..dda17d95 100644
--- a/flowsint-web/src/components/transforms/editor.tsx
+++ b/flowsint-web/src/components/transforms/editor.tsx
@@ -30,7 +30,6 @@ import { categoryColors } from "./scanner-data"
import { ResizableHandle, ResizablePanel, ResizablePanelGroup } from "../ui/resizable"
import { FlowControls } from "./controls"
import { getDagreLayoutedElements } from "@/lib/utils"
-import { supabase } from "@/lib/supabase/client"
import { toast } from "sonner"
import { useParams, useRouter } from "next/navigation"
import { TransformModal } from "./save-modal"
@@ -38,6 +37,7 @@ import { useConfirm } from "../use-confirm-dialog"
import TestTransform from "./test-transform"
import { useLaunchTransform } from "@/hooks/use-launch-transform"
import { FlowComputationDrawer } from "./flow-computation-drawer"
+import { clientFetch } from "@/lib/client-fetch"
const nodeTypes: NodeTypes = {
scanner: ScannerNode,
@@ -213,44 +213,29 @@ const FlowEditor = memo(
setLoading(true)
try {
let newTransform
+ const body = JSON.stringify({
+ name: name,
+ description: description,
+ category: [inputType],
+ transform_schema: {
+ nodes,
+ edges,
+ },
+ })
if (transform_id) {
- const { data, error } = await supabase
- .from("transforms")
- .update({
- category: [inputType],
- transform_schema: {
- nodes,
- edges,
- },
- })
- .eq("id", transform_id)
- .select("id")
- .single()
-
- if (error) throw error
- newTransform = data
+ newTransform = await clientFetch(`${process.env.NEXT_PUBLIC_FLOWSINT_API}/transforms/${transform_id}`,
+ { method: "PUT", body: body }
+ )
} else {
- const { data, error } = await supabase
- .from("transforms")
- .insert({
- name: name,
- description: description,
- category: [inputType],
- transform_schema: {
- nodes,
- edges,
- },
- })
- .select("id")
- .single()
-
- if (error) throw error
- newTransform = data
+ newTransform = await clientFetch(`${process.env.NEXT_PUBLIC_FLOWSINT_API}/transforms/create`,
+ { method: "POST", body: body }
+ )
+ if (!newTransform) {
+ toast.error("Error creating transform")
+ return
+ }
}
-
toast.success("Transform saved successfully.")
- // Open the computation drawer after saving
- setShowComputationDrawer(true)
newTransform && !transform_id && router.push(`/dashboard/transforms/${newTransform.id}`)
} catch (error) {
toast.error("Error saving transform" + JSON.stringify(error))
@@ -291,16 +276,7 @@ const FlowEditor = memo(
})
) {
setLoading(true)
- try {
- await supabase.from("transforms").delete().eq("id", transform_id)
- toast.success("transform deleted successfully.")
- router.push("/dashboard/transforms")
- } catch (error) {
- toast.error("Error deleting simulation")
- console.error(error)
- } finally {
- setLoading(false)
- }
+ // TODO
}
}, [transform_id, confirm, router])
diff --git a/flowsint-web/src/components/transforms/flow-computation-drawer.tsx b/flowsint-web/src/components/transforms/flow-computation-drawer.tsx
index 26ecf3f6..2025b123 100644
--- a/flowsint-web/src/components/transforms/flow-computation-drawer.tsx
+++ b/flowsint-web/src/components/transforms/flow-computation-drawer.tsx
@@ -13,9 +13,9 @@ import { Collapsible, CollapsibleContent, CollapsibleTrigger } from "@/component
import { Tabs, TabsList, TabsTrigger } from "@/components/ui/tabs"
// import { CopyButton } from "../copy"
import { useQuery } from "@tanstack/react-query"
-import { toast } from "sonner"
import Loader from "../loader"
import { CopyButton } from "../copy"
+import { clientFetch } from "@/lib/client-fetch"
interface FlowComputationDrawerProps {
open: boolean
@@ -66,19 +66,10 @@ export function FlowComputationDrawer({
queryKey: ["transforms", transformId, "compute"],
queryFn: async () => {
const body = JSON.stringify({ nodes, edges, initialValue: "domain" })
- const url = `${process.env.NEXT_PUBLIC_FLOWSINT_API}/transforms/${transformId}/compute`
- const res = await fetch(url, {
+ const data = await clientFetch(`${process.env.NEXT_PUBLIC_FLOWSINT_API}/transforms/${transformId}/compute`, {
method: "POST",
- headers: {
- "Content-Type": "application/json",
- },
- body: body,
+ body,
})
- if (!res.ok) {
- toast.error("An error occured.")
- }
- const data = await res.json()
- console.log(data)
setTransformsBranches(data.transformBranches as FlowBranch[])
setInitialData(data.initialData)
return data
diff --git a/flowsint-web/src/components/transforms/transform-name-panel.tsx b/flowsint-web/src/components/transforms/transform-name-panel.tsx
index 6f015833..7ceba5c5 100644
--- a/flowsint-web/src/components/transforms/transform-name-panel.tsx
+++ b/flowsint-web/src/components/transforms/transform-name-panel.tsx
@@ -2,10 +2,8 @@
import { useState, useEffect, type KeyboardEvent, useRef } from "react"
import { Panel } from "@xyflow/react"
-import { supabase } from "@/lib/supabase/client"
import { toast } from "sonner"
import { Card } from "../ui/card"
-import { Input } from "../ui/input"
interface TransformDetailsPanelProps {
transform?: {
@@ -66,17 +64,13 @@ export function TransformDetailsPanel({ transform, onUpdate, disabled = false }:
try {
const updates = { [field]: trimmedValue }
- const { error } = await supabase.from("transforms").update(updates).eq("id", transform.id)
-
- if (error) throw error
-
+ // TODO
if (onUpdate) {
onUpdate(updates)
}
toast.success(`${field === "name" ? "Name" : "Description"} updated.`)
} catch (error) {
toast.error(`Failed to update transform ${field}`)
- // Revert to original value on error
if (field === "name") {
setName(transform.name)
} else {
diff --git a/flowsint-web/src/components/ui/custom-edge.tsx b/flowsint-web/src/components/ui/custom-edge.tsx
deleted file mode 100644
index a488b0ba..00000000
--- a/flowsint-web/src/components/ui/custom-edge.tsx
+++ /dev/null
@@ -1,126 +0,0 @@
-// EditableEdge.tsx
-"use client"
-
-import type React from "react"
-import type { EdgeProps } from "@xyflow/react"
-import { memo, useCallback, useState, useRef, useMemo } from "react"
-import { supabase } from "@/lib/supabase/client"
-import { Check, Loader2 } from "lucide-react"
-import { Button } from "@/components/ui/button"
-import { Input } from "@/components/ui/input"
-import { cn } from "@/lib/utils"
-import { ButtonEdge } from "./button-edge"
-import { toast } from "sonner"
-
-const EditableEdge = memo((props: EdgeProps) => {
- const { id, label, data } = props
- const [isEditing, setIsEditing] = useState(false)
- const [isLoading, setIsLoading] = useState(false)
- const [editValue, setEditValue] = useState((label as string) || "")
- const submitButtonRef = useRef<HTMLButtonElement>(null)
-
- // Utilisation de useCallback pour toutes les fonctions gestionnaires
- const handleEditClick = useCallback(() => {
- setIsEditing(true)
- }, [])
-
- const handleInputBlur = useCallback((e: React.FocusEvent) => {
- // Check if the related target (where focus is going) is the submit button
- if (submitButtonRef.current && submitButtonRef.current.contains(e.relatedTarget as Node)) {
- // Don't close the edit mode if clicking on the submit button
- return
- }
- setIsEditing(false)
- }, [])
-
- const handleSave = useCallback(
- async (e: React.FormEvent) => {
- e.preventDefault()
- e.stopPropagation()
- if (!id) return
- setIsLoading(true)
- try {
- const { error } = await supabase
- .from("individuals_individuals")
- .update({ relation_type: editValue })
- .eq("id", id.toString())
- const { error: error2 } = await supabase
- .from("organizations_individuals")
- .update({ relation_type: editValue })
- .eq("id", id.toString())
- const { error: error3 } = await supabase
- .from("organizations_organizations")
- .update({ relation_type: editValue })
- .eq("id", id.toString())
- if (error || error2 || error3) {
- toast.error("An error occurred.")
- } else {
- toast.success("Relation updated.")
- }
- } catch (err) {
- toast.error("An error occurred.")
- } finally {
- setIsLoading(false)
- setIsEditing(false)
- }
- },
- [id, editValue],
- )
-
- const handleInputChange = useCallback((e: React.ChangeEvent<HTMLInputElement>) => {
- setEditValue(e.target.value)
- }, [])
-
- const buttonEdgeProps = useMemo(() => {
- const { label: _, ...restProps } = props;
- return restProps;
- }, [props.sourceX, props.sourceY, props.targetX, props.targetY, props.style, props.markerEnd]);
-
- const formContent = useMemo(() => {
- if (isEditing) {
- return (
- <div className="flex items-center gap-1 bg-background border rounded-md p-1 shadow-sm">
- <Input
- autoFocus
- value={editValue}
- onChange={handleInputChange}
- onBlur={handleInputBlur}
- className="h-5 text-xs max-w-28 rounded-sm"
- />
- <Button
- ref={submitButtonRef}
- size="icon"
- variant="ghost"
- className="h-5 w-5"
- type="submit"
- disabled={isLoading}
- >
- {isLoading ? <Loader2 className="h-3.5 w-3.5 animate-spin" /> : <Check className="h-3.5 w-3.5" />}
- </Button>
- </div>
- );
- }
- return (
- <Button
- onClick={handleEditClick}
- size="sm"
- variant="secondary"
- className={cn("text-xs px-1 py-.5 h-auto", !editValue && "opacity-70")}
- >
- {editValue || ""}
- </Button>
- );
- }, [isEditing, editValue, isLoading, handleInputChange, handleInputBlur, handleEditClick]);
-
- return (
- <ButtonEdge {...buttonEdgeProps}>
- <form onSubmit={handleSave} className="flex items-center justify-center h-full">
- {formContent}
- </form>
- </ButtonEdge>
- )
-});
-
-EditableEdge.displayName = "EditableEdge"
-
-export default EditableEdge
\ No newline at end of file
diff --git a/flowsint-web/src/components/ui/input.tsx b/flowsint-web/src/components/ui/input.tsx
index d5059987..dcf02a6a 100644
--- a/flowsint-web/src/components/ui/input.tsx
+++ b/flowsint-web/src/components/ui/input.tsx
@@ -8,7 +8,7 @@ function Input({ className, type, ...props }: React.ComponentProps<"input">) {
type={type}
data-slot="input"
className={cn(
- "border file:text-foreground placeholder:text-muted-foreground selection:bg-primary selection:text-primary-foreground aria-invalid:outline-destructive/60 aria-invalid:ring-destructive/20 dark:aria-invalid:outline-destructive dark:aria-invalid:ring-destructive/50 ring-ring/10 dark:ring-ring/20 dark:outline-ring/40 outline-ring/50 aria-invalid:outline-destructive/60 dark:aria-invalid:outline-destructive dark:aria-invalid:ring-destructive/40 aria-invalid:ring-destructive/20 aria-invalid:border-destructive/60 dark:aria-invalid:border-destructive flex h-9 w-full min-w-0 rounded border bg-transparent px-3 py-1 text-base bg-card transition-[color,box-shadow] file:inline-flex file:h-7 file:border-0 inset-shadow-sm file:bg-transparent file:text-sm file:font-medium focus-visible:ring-4 focus-visible:outline-1 disabled:pointer-events-none disabled:cursor-not-allowed disabled:opacity-50 aria-invalid:focus-visible:ring-[3px] aria-invalid:focus-visible:outline-none md:text-sm dark:aria-invalid:focus-visible:ring-4",
+ "border file:text-foreground placeholder:text-muted-foreground selection:bg-primary selection:text-primary-foreground aria-invalid:outline-destructive/60 aria-invalid:ring-destructive/20 dark:aria-invalid:outline-destructive dark:aria-invalid:ring-destructive/50 ring-ring/10 dark:ring-ring/20 dark:outline-ring/40 outline-ring/50 aria-invalid:outline-destructive/60 dark:aria-invalid:outline-destructive dark:aria-invalid:ring-destructive/40 aria-invalid:ring-destructive/20 aria-invalid:border-destructive/60 dark:aria-invalid:border-destructive flex h-9 w-full min-w-0 rounded border bg-transparent px-3 py-1 text-base bg-card transition-[color,box-shadow] file:inline-flex file:h-7 file:border-0 file:bg-transparent file:text-sm file:font-medium focus-visible:ring-4 focus-visible:outline-1 disabled:pointer-events-none disabled:cursor-not-allowed disabled:opacity-50 aria-invalid:focus-visible:ring-[3px] aria-invalid:focus-visible:outline-none md:text-sm dark:aria-invalid:focus-visible:ring-4",
className
)}
{...props}
diff --git a/flowsint-web/src/hooks/use-transforms.ts b/flowsint-web/src/hooks/use-transforms.ts
deleted file mode 100644
index 3c702263..00000000
--- a/flowsint-web/src/hooks/use-transforms.ts
+++ /dev/null
@@ -1,17 +0,0 @@
-"use client"
-
-import { useQuery } from "@tanstack/react-query"
-import { toast } from "sonner"
-
-export function useTransforms(type: string) {
- return useQuery({
- queryKey: ["transforms", type],
- queryFn: async () => {
- const response = await fetch(`/api/transforms?type=${encodeURIComponent(type)}`)
- if (!response.ok) {
- toast.error("Failed to fetch transforms")
- }
- return response.json()
- },
- })
-}
diff --git a/flowsint-web/src/lib/actions/auth.ts b/flowsint-web/src/lib/actions/auth.ts
index 9a7de8da..ec9be136 100644
--- a/flowsint-web/src/lib/actions/auth.ts
+++ b/flowsint-web/src/lib/actions/auth.ts
@@ -1,65 +1,43 @@
'use server'
-import { revalidatePath } from 'next/cache'
import { redirect } from 'next/navigation'
-import { createClient } from '@/lib/supabase/server'
-import { encodedRedirect } from "@/lib/utils";
-
-export async function signInWithGithub() {
- const supabase = await createClient()
- const { data, error } = await supabase.auth.signInWithOAuth({
- provider: 'github',
- options: {
- redirectTo: process.env.NEXT_PUBLIC_AUTH_REDIRECT,
- },
- })
- if (error) {
- return encodedRedirect("error", "/login", error.message);
- }
- if (data.url) {
- redirect(data.url)
- }
-}
-
+import { encodedRedirect } from '../utils'
+import { signIn, signOut } from '@/auth'
export async function login(formData: FormData) {
- const supabase = await createClient()
-
- // type-casting here for convenience
- // in practice, you should validate your inputs
- const data = {
- email: formData.get('email') as string,
- password: formData.get('password') as string,
+ try {
+ await signIn("credentials", formData)
+ redirect('/')
+ } catch (error) {
+ if (error) {
+ return encodedRedirect("error", "/login", "Error signing up." + error);
+ }
+ return encodedRedirect("error", "/login", "Error signing up.");
}
+}
- const { error } = await supabase.auth.signInWithPassword(data)
+export async function register(formData: FormData) {
+ const body = JSON.stringify({ email: formData.get('email') as string, password: formData.get('password') as string })
+ const res = await fetch(`${process.env.NEXT_PUBLIC_DOCKER_FLOWSINT_API}/auth/register`, {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: body,
+ })
+ if (res.ok) {
- if (error) {
- return encodedRedirect("error", "/login", error.message);
- }
- revalidatePath('/', 'layout')
- redirect('/dashboard')
-}
+ } else {
+ return encodedRedirect("error", "/login", "An error occurred while signing up.");
-export async function signup(formData: FormData) {
- const supabase = await createClient()
- const data = {
- email: formData.get('email') as string,
- password: formData.get('password') as string,
- }
- const { error } = await supabase.auth.signUp(data)
- if (error) {
- return encodedRedirect("error", "/login", error.message);
}
- revalidatePath('/', 'layout')
- redirect('/')
}
export async function logout() {
- const supabase = await createClient()
- const { error } = await supabase.auth.signOut()
- if (error) {
- redirect('/error')
+ try {
+ await signOut()
+ redirect('/login')
+ } catch (error) {
+ if (error) {
+ return encodedRedirect("error", "/login", "Error logging out.");
+ }
+ return encodedRedirect("error", "/login", "Error logging out.");
}
- revalidatePath('/', 'layout')
- redirect('/login')
}
\ No newline at end of file
diff --git a/flowsint-web/src/lib/actions/investigations.ts b/flowsint-web/src/lib/actions/investigations.ts
index aa4ae553..e40e13f5 100644
--- a/flowsint-web/src/lib/actions/investigations.ts
+++ b/flowsint-web/src/lib/actions/investigations.ts
@@ -1,11 +1,11 @@
"use server"
-import { createClient } from "../supabase/server"
+import { auth } from "@/auth"
import { redirect } from "next/navigation"
+import { serverFetch } from "../server-fetch"
export const createNewInvestigation = async (formData: FormData) => {
- const supabase = await createClient()
- const { data: session, error: userError } = await supabase.auth.getUser()
- if (userError || !session?.user) {
+ const session = auth()
+ if (!session) {
redirect('/login')
}
const data = {
@@ -13,14 +13,14 @@ export const createNewInvestigation = async (formData: FormData) => {
description: formData.get("description"),
}
try {
- const { data: investigation, error } = await supabase.from("investigations").insert({ ...data, owner_id: session?.user?.id }).select("id").single()
- if (error) throw error
- const { data: folder, error: bucketError } = await supabase.storage.from('documents').upload(`${investigation.id}/placeholder`, '')
- if (bucketError) throw bucketError
- return { success: true, id: investigation.id, path: folder.path }
+ const url = `${process.env.NEXT_PUBLIC_DOCKER_FLOWSINT_API}/investigations/create`;
+ const body = JSON.stringify(data)
+ const created = await serverFetch(url, {
+ method: "POST",
+ body: body
+ })
+ return { success: true, id: created.id }
} catch (error) {
- if ((error as { code?: string })?.code === "42501")
- return { success: false, error: "Missing permission to create a new investigation." }
return { success: false, error: "Failed to create new investigation." }
}
}
\ No newline at end of file
diff --git a/flowsint-web/src/lib/actions/sketches.ts b/flowsint-web/src/lib/actions/sketches.ts
index 8a368b6d..98136d6c 100644
--- a/flowsint-web/src/lib/actions/sketches.ts
+++ b/flowsint-web/src/lib/actions/sketches.ts
@@ -1,27 +1,28 @@
"use server"
-import { createClient } from "../supabase/server"
import { redirect } from "next/navigation"
-import { revalidatePath } from "next/cache"
import { NodeData } from "@/types"
+import { auth } from "@/auth"
+import { serverFetch } from "../server-fetch"
-export async function createNewSketch(formData: FormData, investigation_id: string) {
- const supabase = await createClient()
- const { data: session, error: userError } = await supabase.auth.getUser()
- if (userError || !session?.user) {
+export const createNewSketch = async (formData: FormData, investigation_id: string) => {
+ const session = auth()
+ if (!session) {
redirect('/login')
}
const data = {
title: formData.get("title"),
description: formData.get("description"),
+ investigation_id: investigation_id,
}
try {
- const { data: sketch, error } = await supabase.from("sketches").insert({ ...data, owner_id: session?.user?.id, investigation_id }).select("id").single()
- if (error) throw error
- revalidatePath("/")
- return { success: true, id: sketch.id }
+ const url = `${process.env.NEXT_PUBLIC_DOCKER_FLOWSINT_API}/sketches/create`;
+ const body = JSON.stringify(data)
+ const created = await serverFetch(url, {
+ method: "POST",
+ body: body
+ })
+ return { success: true, id: created.id }
} catch (error) {
- if ((error as { code?: string })?.code === "42501")
- return { success: false, error: "Missing permission to create a new sketch." }
return { success: false, error: "Failed to create new sketch." }
}
}
@@ -37,28 +38,13 @@ export async function saveNode(schema: AddNodeSchema) {
if (!sketch_id) {
return { success: false, error: "Missing sketch ID" }
}
- const supabase = await createClient()
- await supabase.auth.refreshSession()
- const { data: { session } } = await supabase.auth.getSession();
- const jwt = session?.access_token;
- const response = await fetch(`${process.env.NEXT_PUBLIC_DOCKER_FLOWSINT_API}/sketch/${sketch_id}/nodes/add`, {
+ const created = await serverFetch(`${process.env.NEXT_PUBLIC_DOCKER_FLOWSINT_API}/sketches/${sketch_id}/nodes/add`, {
method: "POST",
- body: JSON.stringify(node),
- headers: {
- 'Authorization': `Bearer ${jwt}`,
- "Content-Type": "application/json",
- },
+ body: JSON.stringify(node)
})
- const data = await response.json()
- if (!response.ok) {
- return {
- success: false,
- error: "Failed to create new node"
- }
- }
return {
success: true,
- data: data,
+ data: created,
timestamp: new Date().toISOString()
}
} catch (error) {
@@ -91,26 +77,13 @@ export const saveEdge = async (schema: AddEdgeSchema) => {
if (!sketch_id) {
return { success: false, error: "Missing sketch ID" }
}
- const supabase = await createClient()
- await supabase.auth.refreshSession()
- const { data: { session } } = await supabase.auth.getSession();
- const jwt = session?.access_token;
- console.log(body)
- const res = await fetch(`${process.env.NEXT_PUBLIC_DOCKER_FLOWSINT_API}/sketch/${sketch_id}/relations/add`, {
+ const created = await serverFetch(`${process.env.NEXT_PUBLIC_DOCKER_FLOWSINT_API}/sketch/${sketch_id}/relations/add`, {
method: "POST",
- body: JSON.stringify(body),
- headers: {
- Authorization: `Bearer ${jwt}`,
- "Content-Type": "application/json",
- },
- });
- if (!res.ok) {
- throw Error("Failed to create new relation.")
- }
- const data = await res.json();
+ body: JSON.stringify(body)
+ })
return {
success: true,
- data: data,
+ data: created,
timestamp: new Date().toISOString()
}
} catch (error) {
diff --git a/flowsint-web/src/lib/actions/transform.ts b/flowsint-web/src/lib/actions/transform.ts
index 730b8bcc..7d0bcd0f 100644
--- a/flowsint-web/src/lib/actions/transform.ts
+++ b/flowsint-web/src/lib/actions/transform.ts
@@ -1,26 +1,16 @@
'use server'
-import { createClient } from "@/lib/supabase/server";
+
+import { serverFetch } from "../server-fetch";
+
export async function performTransform(values: string[], transform_id: string, sketch_id: string | null) {
- const supabase = await createClient()
- await supabase.auth.refreshSession()
- const { data: { session } } = await supabase.auth.getSession();
- const jwt = session?.access_token;
const url = `${process.env.NEXT_PUBLIC_DOCKER_FLOWSINT_API}/transforms/${transform_id}/launch`;
const body = JSON.stringify({
values: values,
sketch_id: sketch_id
})
- const response = await fetch(url, {
- method: 'POST',
- headers: {
- 'Authorization': `Bearer ${jwt}`,
- "Content-Type": "application/json",
- },
- body
- },
- );
- const resp = await response.json()
- console.log(resp)
- if (response.status !== 200) throw Error(`Error: received status ${response.status}`)
- return { ...resp, status: response.status };
+ const response = await serverFetch(url, {
+ method: "POST",
+ body: body
+ })
+ return { ...response, status: response.status };
}
\ No newline at end of file
diff --git a/flowsint-web/src/lib/client-fetch.ts b/flowsint-web/src/lib/client-fetch.ts
new file mode 100644
index 00000000..73109b94
--- /dev/null
+++ b/flowsint-web/src/lib/client-fetch.ts
@@ -0,0 +1,41 @@
+// lib/fetcherWithSession.ts
+import { getSession } from "next-auth/react"
+import { redirect } from "next/navigation"
+
+export async function clientFetch(
+ url: string,
+ {
+ method = "GET",
+ body,
+ ...customOptions
+ }: RequestInit & { body?: any } = {}
+) {
+ const session = await getSession()
+ if (!session) {
+ throw new Error("Unauthorized")
+ }
+ const token = session.user?.accessToken
+ if (!token) {
+ throw new Error("No access token found")
+ }
+ const headers = new Headers(customOptions.headers || {})
+ headers.set("Authorization", `Bearer ${token}`)
+ const options: RequestInit = {
+ method,
+ headers,
+ ...customOptions,
+ }
+ if (body && !["GET", "HEAD"].includes(method.toUpperCase())) {
+ headers.set("Content-Type", "application/json")
+ options.body = typeof body === "string" ? body : JSON.stringify(body)
+ }
+ const res = await fetch(url, options)
+ if (!res.ok) {
+ if (res.status === 404) {
+ redirect("/not-found")
+ } else {
+ redirect("/error")
+ }
+ }
+ return res.json()
+}
diff --git a/flowsint-web/src/lib/hooks/sketches.ts b/flowsint-web/src/lib/hooks/sketches.ts
deleted file mode 100644
index bd509499..00000000
--- a/flowsint-web/src/lib/hooks/sketches.ts
+++ /dev/null
@@ -1,34 +0,0 @@
-import { supabase } from "@/lib/supabase/client";
-import { useQuery } from "@supabase-cache-helpers/postgrest-swr";
-
-export function useSketches(investigation_id: string) {
- const { data: sketches, count, mutate, isLoading, error } = useQuery(
- supabase
- .from('sketches')
- .select('id, title, description')
- .eq("investigation_id", investigation_id)
- .order("last_updated_at", { ascending: false }),
- {
- revalidateOnFocus: false,
- revalidateOnReconnect: false,
- }
- );
-
- return { sketches, count, isLoading, refetch: mutate, error };
-}
-
-export function useSketch(sketch_id: string | string[] | undefined) {
- if (!sketch_id) return { investigation: null }
- const { data: sketch, mutate, isLoading, error } = useQuery(
- supabase
- .from('sketches')
- .select('id, title, description')
- .eq("id", sketch_id)
- .single(),
- {
- revalidateOnFocus: false,
- revalidateOnReconnect: false,
- }
- );
- return { data: sketch ?? null, isLoading, refetch: mutate, error };
-}
\ No newline at end of file
diff --git a/flowsint-web/src/lib/server-fetch.ts b/flowsint-web/src/lib/server-fetch.ts
new file mode 100644
index 00000000..371e3cfe
--- /dev/null
+++ b/flowsint-web/src/lib/server-fetch.ts
@@ -0,0 +1,47 @@
+import { auth } from "@/auth"
+import { redirect } from "next/navigation"
+
+export async function serverFetch(
+ url: string,
+ {
+ method = "GET",
+ body,
+ ...customOptions
+ }: RequestInit & { method?: string; body?: any } = {}
+) {
+ const session = await auth()
+ if (!session || !session.user?.accessToken) {
+ redirect("/login")
+ }
+
+ const token = session.user.accessToken
+ const headers = new Headers(customOptions.headers || {})
+ headers.set("Authorization", `Bearer ${token}`)
+
+ const upperMethod = method.toUpperCase()
+ const options: RequestInit = {
+ method: upperMethod,
+ headers,
+ ...customOptions,
+ }
+
+ if (body && !["GET", "HEAD"].includes(upperMethod)) {
+ headers.set("Content-Type", "application/json")
+ options.body = typeof body === "string" ? body : JSON.stringify(body)
+ } else {
+ // Pour éviter de passer body inutilement dans un GET/HEAD
+ delete options.body
+ }
+
+ const res = await fetch(url, options)
+
+ if (!res.ok) {
+ if (res.status === 404) {
+ redirect("/not-found")
+ } else {
+ redirect("/error")
+ }
+ }
+
+ return res.json()
+}
diff --git a/flowsint-web/src/lib/supabase/client.ts b/flowsint-web/src/lib/supabase/client.ts
deleted file mode 100644
index e823222b..00000000
--- a/flowsint-web/src/lib/supabase/client.ts
+++ /dev/null
@@ -1,7 +0,0 @@
-import { createBrowserClient } from '@supabase/ssr'
-
-if (!process.env.NEXT_PUBLIC_SUPABASE_URL || !process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY) {
- throw new Error('Missing Supabase environment variables');
-}
-
-export const supabase = createBrowserClient(process.env.NEXT_PUBLIC_SUPABASE_URL, process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY)
\ No newline at end of file
diff --git a/flowsint-web/src/lib/supabase/middleware.ts b/flowsint-web/src/lib/supabase/middleware.ts
deleted file mode 100644
index 21a5df1c..00000000
--- a/flowsint-web/src/lib/supabase/middleware.ts
+++ /dev/null
@@ -1,65 +0,0 @@
-import { createServerClient } from '@supabase/ssr'
-import { NextResponse, type NextRequest } from 'next/server'
-
-export async function updateSession(request: NextRequest) {
- let supabaseResponse = NextResponse.next({
- request,
- })
- const supabase = createServerClient(
- process.env.NEXT_PUBLIC_DOCKER_SUPABASE_URL!,
- process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY!,
- {
- cookies: {
- getAll() {
- return request.cookies.getAll()
- },
- setAll(cookiesToSet) {
- cookiesToSet.forEach(({ name, value, options }) => request.cookies.set(name, value))
- supabaseResponse = NextResponse.next({
- request,
- })
- cookiesToSet.forEach(({ name, value, options }) =>
- supabaseResponse.cookies.set(name, value, options)
- )
- },
- },
- }
- )
-
- // Do not run code between createServerClient and
- // supabase.auth.getUser(). A simple mistake could make it very hard to debug
- // issues with users being randomly logged out.
-
- // IMPORTANT: DO NOT REMOVE auth.getUser()
-
- const {
- data: { user },
- } = await supabase.auth.getUser()
-
- if (
- !user &&
- !request.nextUrl.pathname.startsWith('/login') &&
- !request.nextUrl.pathname.startsWith('/auth') &&
- !request.nextUrl.pathname.startsWith('/api')
- ) {
- // no user, potentially respond by redirecting the user to the login page
- const url = request.nextUrl.clone()
- url.pathname = '/login'
- return NextResponse.redirect(url)
- }
-
- // IMPORTANT: You *must* return the supabaseResponse object as it is.
- // If you're creating a new response object with NextResponse.next() make sure to:
- // 1. Pass the request in it, like so:
- // const myNewResponse = NextResponse.next({ request })
- // 2. Copy over the cookies, like so:
- // myNewResponse.cookies.setAll(supabaseResponse.cookies.getAll())
- // 3. Change the myNewResponse object to fit your needs, but avoid changing
- // the cookies!
- // 4. Finally:
- // return myNewResponse
- // If this is not done, you may be causing the browser and server to go out
- // of sync and terminate the user's session prematurely!
-
- return supabaseResponse
-}
\ No newline at end of file
diff --git a/flowsint-web/src/lib/supabase/server.ts b/flowsint-web/src/lib/supabase/server.ts
deleted file mode 100644
index cbbb6d72..00000000
--- a/flowsint-web/src/lib/supabase/server.ts
+++ /dev/null
@@ -1,43 +0,0 @@
-import { createServerClient } from '@supabase/ssr'
-import { cookies } from 'next/headers'
-
-export async function createClient() {
- const cookieStore = await cookies()
- const supabaseToken = cookieStore.get('sb-token')?.value
-
- return createServerClient(
- process.env.NEXT_PUBLIC_DOCKER_SUPABASE_URL!,
- process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY!,
- {
- auth: {
- persistSession: false,
- // Add the token if it exists
- ...(supabaseToken && {
- autoRefreshToken: false,
- detectSessionInUrl: false,
- storage: {
- getItem: () => supabaseToken,
- setItem: () => { },
- removeItem: () => { },
- },
- }),
- },
- cookies: {
- getAll() {
- return cookieStore.getAll()
- },
- setAll(cookiesToSet) {
- try {
- cookiesToSet.forEach(({ name, value, options }) =>
- cookieStore.set(name, value, options)
- )
- } catch {
- // The `setAll` method was called from a Server Component.
- // This can be ignored if you have middleware refreshing
- // user sessions.
- }
- },
- },
- }
- )
-}
\ No newline at end of file
diff --git a/flowsint-web/src/middleware.ts b/flowsint-web/src/middleware.ts
index f17527fa..f09bb68c 100644
--- a/flowsint-web/src/middleware.ts
+++ b/flowsint-web/src/middleware.ts
@@ -1,8 +1,6 @@
-import { updateSession } from '@/lib/supabase/middleware'
import { NextRequest } from 'next/server'
export async function middleware(request: NextRequest) {
- return await updateSession(request)
}
export const config = {
diff --git a/flowsint-web/yarn.lock b/flowsint-web/yarn.lock
index 24bc166e..da0f73ea 100644
--- a/flowsint-web/yarn.lock
+++ b/flowsint-web/yarn.lock
@@ -37,6 +37,17 @@
resolved "https://registry.yarnpkg.com/@alloc/quick-lru/-/quick-lru-5.2.0.tgz#7bf68b20c0a350f936915fcae06f58e32007ce30"
integrity sha512-UrcABB+4bUrFABwbluTIBErXwvbsU/V7TZWfmbgJfbkwiBuziS9gxdODUyuiecfdGQ85jglMW6juS3+z5TsKLw==
+ version "0.39.1"
+ resolved "https://registry.yarnpkg.com/@auth/core/-/core-0.39.1.tgz#2b42697154f29b9f8c4c76f6978ed94ea6e19219"
+ integrity sha512-McD8slui0oOA1pjR5sPjLPl5Zm//nLP/8T3kr8hxIsvNLvsiudYvPHhDFPjh1KcZ2nFxCkZmP6bRxaaPd/AnLA==
+ dependencies:
+ "@panva/hkdf" "^1.2.1"
+ jose "^6.0.6"
+ oauth4webapi "^3.3.0"
+ preact "10.24.3"
+ preact-render-to-string "6.5.11"
+
"@babel/code-frame@^7.26.2":
version "7.26.2"
resolved "https://registry.yarnpkg.com/@babel/code-frame/-/code-frame-7.26.2.tgz#4b5fab97d33338eff916235055f0ebc21e573a85"
@@ -56,14 +67,6 @@
resolved "https://registry.yarnpkg.com/@babel/helper-validator-identifier/-/helper-validator-identifier-7.25.9.tgz#24b64e2c3ec7cd3b3c547729b8d16871f22cbdc7"
integrity sha512-Ed61U6XJc3CVRfkERJWDz4dJwKe7iLmmJsbOGu9wSloNSFttHV0I8g6UAgb7qnK5ly5bGLPd4oXZlxCdANBOWQ==
-"@babel/runtime-corejs3@^7.16.5":
- version "7.26.7"
- resolved "https://registry.yarnpkg.com/@babel/runtime-corejs3/-/runtime-corejs3-7.26.7.tgz#586756721b532572b8592d825ebbb5bc08f08ad4"
- integrity sha512-55gRV8vGrCIYZnaQHQrD92Lo/hYE3Sj5tmbuf0hhHR7sj2CWhEhHU89hbq+UVDXvFG1zUVXJhUkEq1eAfqXtFw==
- dependencies:
- core-js-pure "^3.30.2"
- regenerator-runtime "^0.14.0"
-
"@babel/runtime@^7.12.5", "@babel/runtime@^7.17.8":
version "7.27.1"
resolved "https://registry.yarnpkg.com/@babel/runtime/-/runtime-7.27.1.tgz#9fce313d12c9a77507f264de74626e87fd0dc541"
@@ -729,6 +732,11 @@
resolved "https://registry.yarnpkg.com/@nolyfill/is-core-module/-/is-core-module-1.0.39.tgz#3dc35ba0f1e66b403c00b39344f870298ebb1c8e"
integrity sha512-nn5ozdjYQpUCZlWGuxcJY/KpxkWQs4DcbMCmKojjyrYDEAGy4Ce19NN4v5MduafTwJlbKc99UA8YhSVqq9yPZA==
+"@panva/hkdf@^1.2.1":
+ version "1.2.1"
+ resolved "https://registry.yarnpkg.com/@panva/hkdf/-/hkdf-1.2.1.tgz#cb0d111ef700136f4580349ff0226bf25c853f23"
+ integrity sha512-6oclG6Y3PiDFcoyk8srjLfVKyMfVCKJ27JwNPViuXziFpmdz+MZnZN/aKY0JGXgYuO/VghU0jcOAZgWXZ1Dmrw==
+
"@parcel/[email protected]":
version "2.5.1"
resolved "https://registry.yarnpkg.com/@parcel/watcher-android-arm64/-/watcher-android-arm64-2.5.1.tgz#507f836d7e2042f798c7d07ad19c3546f9848ac1"
@@ -1882,32 +1890,6 @@
resolved "https://registry.yarnpkg.com/@segment/isodate/-/isodate-1.0.3.tgz#f44e8202d5edd277ce822785239474b2c9411d4a"
integrity sha512-BtanDuvJqnACFkeeYje7pWULVv8RgZaqKHWwGFnL/g/TH/CcZjkIVTfGDp/MAxmilYHUkrX70SqwnYSTNEaN7A==
-"@supabase-cache-helpers/[email protected]":
- version "0.9.0"
- resolved "https://registry.yarnpkg.com/@supabase-cache-helpers/postgrest-core/-/postgrest-core-0.9.0.tgz#4fd05c2a435d08ee5d90a8ece4a9f2a52afe6de9"
- integrity sha512-CkbMOWAZl6az5f3UuzL6vmqBFkbTiOAtNypgGsgQxvD04S025yX/+MnoJl6bWkOXa6MWrft5/YUtY9VNeCMYgQ==
- dependencies:
- fast-equals "5.0.1"
- flat "6.0.1"
- merge-anything "5.1.7"
- xregexp "5.1.1"
-
-"@supabase-cache-helpers/postgrest-swr@^1.10.6":
- version "1.10.6"
- resolved "https://registry.yarnpkg.com/@supabase-cache-helpers/postgrest-swr/-/postgrest-swr-1.10.6.tgz#eb7cae496c50d431418b492ed86ac4eac13e284e"
- integrity sha512-CARB+c42qZol21jEefK+J4PedToVmGyqMg1VtdPVTOzGoVGFdfmaqDzpC77+1eqVpHL71z3ZdERtYuqSwoXZNQ==
- dependencies:
- "@supabase-cache-helpers/postgrest-core" "0.9.0"
- flat "6.0.1"
- server-only "^0.0.1"
-
-"@supabase/[email protected]":
- version "2.67.3"
- resolved "https://registry.yarnpkg.com/@supabase/auth-js/-/auth-js-2.67.3.tgz#a1f5eb22440b0cdbf87fe2ecae662a8dd8bb2028"
- integrity sha512-NJDaW8yXs49xMvWVOkSIr8j46jf+tYHV0wHhrwOaLLMZSFO4g6kKAf+MfzQ2RaD06OCUkUHIzctLAxjTgEVpzw==
- dependencies:
- "@supabase/node-fetch" "^2.6.14"
-
"@supabase/[email protected]":
version "2.69.1"
resolved "https://registry.yarnpkg.com/@supabase/auth-js/-/auth-js-2.69.1.tgz#fcf310d24dfab823ffbf22191e6ceaef933360d8"
@@ -1929,13 +1911,6 @@
dependencies:
whatwg-url "^5.0.0"
-"@supabase/[email protected]":
- version "1.18.1"
- resolved "https://registry.yarnpkg.com/@supabase/postgrest-js/-/postgrest-js-1.18.1.tgz#7ceac0dfbe567d953343c5ae9750f848cc6db744"
- integrity sha512-dWDnoC0MoDHKhaEOrsEKTadWQcBNknZVQcSgNE/Q2wXh05mhCL1ut/jthRUrSbYcqIw/CEjhaeIPp7dLarT0bg==
- dependencies:
- "@supabase/node-fetch" "^2.6.14"
-
"@supabase/[email protected]":
version "1.19.4"
resolved "https://registry.yarnpkg.com/@supabase/postgrest-js/-/postgrest-js-1.19.4.tgz#41de1e4310ce8ddba87becd7e0878f4ad7a659a2"
@@ -1953,14 +1928,6 @@
"@types/ws" "^8.5.10"
ws "^8.18.0"
-"@supabase/ssr@^0.5.2":
- version "0.5.2"
- resolved "https://registry.yarnpkg.com/@supabase/ssr/-/ssr-0.5.2.tgz#04233a0ca23a5bc15e02006fb324b9ed2f9f645d"
- integrity sha512-n3plRhr2Bs8Xun1o4S3k1CDv17iH5QY9YcoEvXX3bxV1/5XSasA0mNXYycFmADIdtdE6BG9MRjP5CGIs8qxC8A==
- dependencies:
- "@types/cookie" "^0.6.0"
- cookie "^0.7.0"
-
"@supabase/[email protected]":
version "2.7.1"
resolved "https://registry.yarnpkg.com/@supabase/storage-js/-/storage-js-2.7.1.tgz#761482f237deec98a59e5af1ace18c7a5e0a69af"
@@ -1980,18 +1947,6 @@
"@supabase/realtime-js" "2.11.2"
"@supabase/storage-js" "2.7.1"
-"@supabase/supabase-js@^2.48.1":
- version "2.48.1"
- resolved "https://registry.yarnpkg.com/@supabase/supabase-js/-/supabase-js-2.48.1.tgz#6bbe6bd799115bd1237510e1c2de6f8ccdd84cd0"
- integrity sha512-VMD+CYk/KxfwGbI4fqwSUVA7CLr1izXpqfFerhnYPSi6LEKD8GoR4kuO5Cc8a+N43LnfSQwLJu4kVm2e4etEmA==
- dependencies:
- "@supabase/auth-js" "2.67.3"
- "@supabase/functions-js" "2.4.4"
- "@supabase/node-fetch" "2.6.15"
- "@supabase/postgrest-js" "1.18.1"
- "@supabase/realtime-js" "2.11.2"
- "@supabase/storage-js" "2.7.1"
-
version "0.1.3"
resolved "https://registry.yarnpkg.com/@swc/counter/-/counter-0.1.3.tgz#cc7463bd02949611c6329596fccd2b0ec782b0e9"
@@ -2340,11 +2295,6 @@
resolved "https://registry.yarnpkg.com/@tweenjs/tween.js/-/tween.js-25.0.0.tgz#7266baebcc3affe62a3a54318a3ea82d904cd0b9"
integrity sha512-XKLA6syeBUaPzx4j3qwMqzzq+V4uo72BnlbOjmuljLrRqdsd3qnzvZZoxvMHZ23ndsRS4aufU6JOZYpCbU6T1A==
-"@types/cookie@^0.6.0":
- version "0.6.0"
- resolved "https://registry.yarnpkg.com/@types/cookie/-/cookie-0.6.0.tgz#eac397f28bf1d6ae0ae081363eca2f425bedf0d5"
- integrity sha512-4Kh9a6B2bQciAhf7FSuMRRkUWecJgJu9nPnx3yzpsfXX/c50REIqpHY4C82bXP90qrLtXtkDxTZosYO3UpOwlA==
-
"@types/d3-array@^3.0.3":
version "3.2.1"
resolved "https://registry.yarnpkg.com/@types/d3-array/-/d3-array-3.2.1.tgz#1f6658e3d2006c4fceac53fde464166859f8b8c5"
@@ -3268,16 +3218,6 @@ concaveman@^1.2.1:
robust-predicates "^2.0.4"
tinyqueue "^2.0.3"
-cookie@^0.7.0:
- version "0.7.2"
- resolved "https://registry.yarnpkg.com/cookie/-/cookie-0.7.2.tgz#556369c472a2ba910f2979891b526b3436237ed7"
- integrity sha512-yki5XnKuf750l50uGTllt6kKILY4nQ1eNIQatoXEByZ5dWgnKqbnqmTrBE5B4N7lrMJKQ2ytWMiTO2o0v6Ew/w==
-
-core-js-pure@^3.30.2:
- version "3.40.0"
- resolved "https://registry.yarnpkg.com/core-js-pure/-/core-js-pure-3.40.0.tgz#d9a019e9160f9b042eeb6abb92242680089d486e"
- integrity sha512-AtDzVIgRrmRKQai62yuSIN5vNiQjcJakJb4fbhVw3ehxx7Lohphvw9SGNWKhLFqSxC4ilD0g/L1huAYFQU3Q6A==
-
core-util-is@~1.0.0:
version "1.0.3"
resolved "https://registry.yarnpkg.com/core-util-is/-/core-util-is-1.0.3.tgz#a6042d3634c2b27e9328f837b965fac83808db85"
@@ -4391,11 +4331,6 @@ fast-diff@^1.1.2:
resolved "https://registry.yarnpkg.com/fast-diff/-/fast-diff-1.3.0.tgz#ece407fa550a64d638536cd727e129c61616e0f0"
integrity sha512-VxPP4NqbUjj6MaAOafWeUn2cXWLcCtljklUtZf0Ind4XQ+QPtmA0b18zZy0jIQx+ExRVCR/ZQpBmik5lXshNsw==
- version "5.0.1"
- resolved "https://registry.yarnpkg.com/fast-equals/-/fast-equals-5.0.1.tgz#a4eefe3c5d1c0d021aeed0bc10ba5e0c12ee405d"
- integrity sha512-WF1Wi8PwwSY7/6Kx0vKXtw8RwuSGoM1bvDaJbu7MxDlR1vovZjIAKrnzyrThgAjm6JDTu0fVgWXDlMGspodfoQ==
-
fast-equals@^5.0.1:
version "5.2.2"
resolved "https://registry.yarnpkg.com/fast-equals/-/fast-equals-5.2.2.tgz#885d7bfb079fac0ce0e8450374bce29e9b742484"
@@ -4476,11 +4411,6 @@ flat-cache@^3.0.4:
keyv "^4.5.3"
rimraf "^3.0.2"
- version "6.0.1"
- resolved "https://registry.yarnpkg.com/flat/-/flat-6.0.1.tgz#09070cf918293b401577f20843edeadf4d3e8755"
- integrity sha512-/3FfIa8mbrg3xE7+wAhWeV+bd7L2Mof+xtZb5dRDKZ+wDvYJK4WDYeIOuOhre5Yv5aQObZrlbRmk3RTSiuQBtw==
-
flatted@^3.2.9:
version "3.3.2"
resolved "https://registry.yarnpkg.com/flatted/-/flatted-3.3.2.tgz#adba1448a9841bec72b42c532ea23dbbedef1a27"
@@ -5120,11 +5050,6 @@ is-weakset@^2.0.3:
call-bound "^1.0.3"
get-intrinsic "^1.2.6"
-is-what@^4.1.8:
- version "4.1.16"
- resolved "https://registry.yarnpkg.com/is-what/-/is-what-4.1.16.tgz#1ad860a19da8b4895ad5495da3182ce2acdd7a6f"
- integrity sha512-ZhMwEosbFJkA0YhFnNDgTM4ZxDRsS6HqTo7qsZM08fehyRYIYa0yHu5R6mgo1n/8MgaPBXiPimPD77baVFYg+A==
-
version "0.0.1"
resolved "https://registry.yarnpkg.com/isarray/-/isarray-0.0.1.tgz#8a18acfca9a8f4177e09abfc6038939b05d1eedf"
@@ -5162,6 +5087,11 @@ jiti@^2.4.2:
resolved "https://registry.yarnpkg.com/jiti/-/jiti-2.4.2.tgz#d19b7732ebb6116b06e2038da74a55366faef560"
integrity sha512-rg9zJN+G4n2nfJl5MW3BMygZX56zKPNVEYYqq7adpmMh4Jn2QNEwhvQlFy6jPVdcod7txZtKHWnyZiA3a0zP7A==
+jose@^6.0.6:
+ version "6.0.11"
+ resolved "https://registry.yarnpkg.com/jose/-/jose-6.0.11.tgz#0b7ea8b3b21a1bda5e00255a044c3a0e43270882"
+ integrity sha512-QxG7EaliDARm1O1S8BGakqncGT9s25bKL1WSf6/oa17Tkqwi8D2ZNglqCF+DsYF88/rV66Q/Q2mFAy697E1DUg==
+
version "3.0.1"
resolved "https://registry.yarnpkg.com/js-cookie/-/js-cookie-3.0.1.tgz#9e39b4c6c2f56563708d7d31f6f5f21873a92414"
@@ -5535,13 +5465,6 @@ memoize-one@^4.0.0:
resolved "https://registry.yarnpkg.com/memoize-one/-/memoize-one-4.1.0.tgz#a2387c58c03fff27ca390c31b764a79addf3f906"
integrity sha512-2GApq0yI/b22J2j9rhbrAlsHb0Qcz+7yWxeLG8h+95sl1XPUgeLimQSOdur4Vw7cUhrBHwaUZxWFZueojqNRzA==
- version "5.1.7"
- resolved "https://registry.yarnpkg.com/merge-anything/-/merge-anything-5.1.7.tgz#94f364d2b0cf21ac76067b5120e429353b3525d7"
- integrity sha512-eRtbOb1N5iyH0tkQDAoQ4Ipsp/5qSR79Dzrz8hEPxRX10RWWR/iQXdoKmBSRCThY1Fh5EhISDtpSc93fpxUniQ==
- dependencies:
- is-what "^4.1.8"
-
merge2@^1.3.0:
version "1.4.1"
resolved "https://registry.yarnpkg.com/merge2/-/merge2-1.4.1.tgz#4368892f885e907455a6fd7dc55c0c9d404990ae"
@@ -5824,6 +5747,13 @@ new-date@^1.0.3:
dependencies:
"@segment/isodate" "1.0.3"
+next-auth@^5.0.0-beta.28:
+ version "5.0.0-beta.28"
+ resolved "https://registry.yarnpkg.com/next-auth/-/next-auth-5.0.0-beta.28.tgz#6a7673f858980aaa92668d5c41e5ec3d800866bc"
+ integrity sha512-2RDR1h3DJb4nizcd5UBBwC2gtyP7j/jTvVLvEtDaFSKUWNfou3Gek2uTNHSga/Q4I/GF+OJobA4mFbRaWJgIDQ==
+ dependencies:
+ "@auth/core" "0.39.1"
+
next-themes@^0.4.4:
version "0.4.4"
resolved "https://registry.yarnpkg.com/next-themes/-/next-themes-0.4.4.tgz#ce6f68a4af543821bbc4755b59c0d3ced55c2d13"
@@ -5935,6 +5865,11 @@ nuqs@^2.4.0:
dependencies:
mitt "^3.0.1"
+oauth4webapi@^3.3.0:
+ version "3.5.1"
+ resolved "https://registry.yarnpkg.com/oauth4webapi/-/oauth4webapi-3.5.1.tgz#93154323df5c2e09bf8884c26693596eaaafc17a"
+ integrity sha512-txg/jZQwcbaF7PMJgY7aoxc9QuCxHVFMiEkDIJ60DwDz3PbtXPQnrzo+3X4IRYGChIwWLabRBRpf1k9hO9+xrQ==
+
version "0.2.1"
resolved "https://registry.yarnpkg.com/obj-case/-/obj-case-0.2.1.tgz#13a554d04e5ca32dfd9d566451fd2b0e11007f1a"
@@ -6201,11 +6136,21 @@ postcss@^8.5.3:
picocolors "^1.1.1"
source-map-js "^1.2.1"
+ version "6.5.11"
+ resolved "https://registry.yarnpkg.com/preact-render-to-string/-/preact-render-to-string-6.5.11.tgz#467e69908a453497bb93d4d1fc35fb749a78e027"
+ integrity sha512-ubnauqoGczeGISiOh6RjX0/cdaF8v/oDXIjO85XALCQjwQP+SB4RDXXtvZ6yTYSjG+PC1QRP2AhPgCEsM2EvUw==
+
preact@10:
version "10.26.2"
resolved "https://registry.yarnpkg.com/preact/-/preact-10.26.2.tgz#d737055584a4d8004ec273e425fb4c30960aa512"
integrity sha512-0gNmv4qpS9HaN3+40CLBAnKe0ZfyE4ZWo5xKlC1rVrr0ckkEvJvAQqKaHANdFKsGstoxrY4AItZ7kZSGVoVjgg==
+ version "10.24.3"
+ resolved "https://registry.yarnpkg.com/preact/-/preact-10.24.3.tgz#086386bd47071e3b45410ef20844c21e23828f64"
+ integrity sha512-Z2dPnBnMUfyQfSQ+GBdsGa16hz35YmLmtTLhM169uW944hYL6xzTYkJjC07j+Wosz733pMWx0fgON3JNw1jJQA==
+
prelude-ls@^1.2.1:
version "1.2.1"
resolved "https://registry.yarnpkg.com/prelude-ls/-/prelude-ls-1.2.1.tgz#debc6489d7a6e6b0e7611888cec880337d316396"
@@ -6928,11 +6873,6 @@ semver@^7.6.0, semver@^7.6.3:
resolved "https://registry.yarnpkg.com/semver/-/semver-7.7.1.tgz#abd5098d82b18c6c81f6074ff2647fd3e7220c9f"
integrity sha512-hlq8tAfn0m/61p4BVRcPzIGr6LKiMwo4VM6dGi6pt4qcRkmNzTcWq6eCEjEh+qXjkMDvPlOFFSGwQjoEa6gyMA==
-server-only@^0.0.1:
- version "0.0.1"
- resolved "https://registry.yarnpkg.com/server-only/-/server-only-0.0.1.tgz#0f366bb6afb618c37c9255a314535dc412cd1c9e"
- integrity sha512-qepMx2JxAa5jjfzxG79yPPq+8BuFToHd1hm7kI+Z4zAq1ftQiP7HcxMhDDItrbtwVeLg/cY2JnKnrcFkmiswNA==
-
set-function-length@^1.2.2:
version "1.2.2"
resolved "https://registry.yarnpkg.com/set-function-length/-/set-function-length-1.2.2.tgz#aac72314198eaed975cf77b2c3b6b880695e5449"
@@ -7848,13 +7788,6 @@ ws@^8.18.0:
resolved "https://registry.yarnpkg.com/ws/-/ws-8.18.0.tgz#0d7505a6eafe2b0e712d232b42279f53bc289bbc"
integrity sha512-8VbfWfHLbbwu3+N6OKsOMpBdT4kXPDDB9cJk2bJ6mh9ucxdlnNvH1e+roYkKmN9Nxw2yjz7VzeO9oOz2zJ04Pw==
- version "5.1.1"
- resolved "https://registry.yarnpkg.com/xregexp/-/xregexp-5.1.1.tgz#6d3fe18819e3143aaf52f9284d34f49a59583ebb"
- integrity sha512-fKXeVorD+CzWvFs7VBuKTYIW63YD1e1osxwQ8caZ6o1jg6pDAbABDG54LCIq0j5cy7PjRvGIq6sef9DYPXpncg==
- dependencies:
- "@babel/runtime-corejs3" "^7.16.5"
-
"xtend@>=4.0.0 <4.1.0-0":
version "4.0.2"
resolved "https://registry.yarnpkg.com/xtend/-/xtend-4.0.2.tgz#bb72779f5fa465186b1f438f674fa347fdb5db54"
diff --git a/package.json b/package.json
index 1246c99b..1284ae92 100644
--- a/package.json
+++ b/package.json
@@ -8,10 +8,7 @@
"license": "MIT",
"scripts": {
"dev": "docker compose up -d",
- "compose:start": "docker compose -f docker-compose.override.yml up -d"
- },
- "devDependencies": {
- "supabase": "^2.19.7"
+ "compose:start": "docker compose -f docker-compose.yml up -d"
},
"dependencies": {
"@testing-library/react": "^16.3.0",