mirror of
https://github.com/dograh-hq/dograh.git
synced 2026-06-28 08:49:42 +02:00
commit
e8e11da7e3
19 changed files with 462 additions and 68 deletions
|
|
@ -66,11 +66,11 @@ class MPSServiceKeyClient:
|
||||||
# Transform the response to match our expected format
|
# Transform the response to match our expected format
|
||||||
return {
|
return {
|
||||||
"id": data.get("id"),
|
"id": data.get("id"),
|
||||||
"name": data.get("name"),
|
"name": data.get("name") or name,
|
||||||
"service_key": data.get("service_key"), # Only returned on creation
|
"service_key": data.get("service_key"),
|
||||||
"key_prefix": data.get("service_key", "")[:8]
|
"key_prefix": data.get("key_prefix") or (data.get("service_key", "")[:8]
|
||||||
if data.get("service_key")
|
if data.get("service_key")
|
||||||
else "",
|
else ""),
|
||||||
"expires_at": data.get("expires_at"),
|
"expires_at": data.get("expires_at"),
|
||||||
"created_at": data.get("created_at"),
|
"created_at": data.get("created_at"),
|
||||||
"is_active": data.get("is_active", True),
|
"is_active": data.get("is_active", True),
|
||||||
|
|
|
||||||
|
|
@ -15,7 +15,7 @@ from pipecat.services.openai.llm import OpenAILLMContext
|
||||||
from pipecat.transports.base_transport import BaseTransport
|
from pipecat.transports.base_transport import BaseTransport
|
||||||
from pipecat.utils.enums import EndTaskReason
|
from pipecat.utils.enums import EndTaskReason
|
||||||
|
|
||||||
from api.constants import VOICEMAIL_RECORDING_DURATION
|
from api.constants import DEPLOYMENT_MODE, ENABLE_TRACING, VOICEMAIL_RECORDING_DURATION
|
||||||
from api.services.gender.gender_service import GenderService
|
from api.services.gender.gender_service import GenderService
|
||||||
from api.services.workflow.disposition_mapper import (
|
from api.services.workflow.disposition_mapper import (
|
||||||
apply_disposition_mapping,
|
apply_disposition_mapping,
|
||||||
|
|
@ -480,7 +480,9 @@ class PipecatEngine:
|
||||||
async def _handle_start_node(self, node: Node) -> None:
|
async def _handle_start_node(self, node: Node) -> None:
|
||||||
"""Handle start node execution."""
|
"""Handle start node execution."""
|
||||||
# Handle voicemail detection setup (before any returns)
|
# Handle voicemail detection setup (before any returns)
|
||||||
if node.detect_voicemail:
|
# Lets check ENABLE_TRACING to make sure we have prompt access from
|
||||||
|
# langfuse
|
||||||
|
if node.detect_voicemail and DEPLOYMENT_MODE == 'saas' and ENABLE_TRACING:
|
||||||
if not self._audio_buffer:
|
if not self._audio_buffer:
|
||||||
logger.warning(
|
logger.warning(
|
||||||
"Voicemail detection enabled but no audio buffer available - skipping detection"
|
"Voicemail detection enabled but no audio buffer available - skipping detection"
|
||||||
|
|
|
||||||
47
docker-compose-local.yaml
Normal file
47
docker-compose-local.yaml
Normal file
|
|
@ -0,0 +1,47 @@
|
||||||
|
services:
|
||||||
|
postgres:
|
||||||
|
image: postgres:17
|
||||||
|
environment:
|
||||||
|
POSTGRES_USER: postgres
|
||||||
|
POSTGRES_PASSWORD: postgres
|
||||||
|
POSTGRES_DB: postgres
|
||||||
|
logging:
|
||||||
|
driver: "json-file"
|
||||||
|
options:
|
||||||
|
max-size: "10m"
|
||||||
|
max-file: "3"
|
||||||
|
ports:
|
||||||
|
- "5432:5432"
|
||||||
|
volumes:
|
||||||
|
- postgres_data:/var/lib/postgresql/data
|
||||||
|
healthcheck:
|
||||||
|
test: ["CMD-SHELL", "pg_isready -U postgres"]
|
||||||
|
interval: 3s
|
||||||
|
timeout: 3s
|
||||||
|
retries: 10
|
||||||
|
networks:
|
||||||
|
- app-network
|
||||||
|
|
||||||
|
redis:
|
||||||
|
image: redis:7
|
||||||
|
ports:
|
||||||
|
- "6379:6379"
|
||||||
|
command: >
|
||||||
|
--requirepass redissecret
|
||||||
|
volumes:
|
||||||
|
- redis_data:/data
|
||||||
|
healthcheck:
|
||||||
|
test: ["CMD", "redis-cli", "-a", "redissecret", "ping"]
|
||||||
|
interval: 3s
|
||||||
|
timeout: 10s
|
||||||
|
retries: 10
|
||||||
|
networks:
|
||||||
|
- app-network
|
||||||
|
|
||||||
|
volumes:
|
||||||
|
postgres_data:
|
||||||
|
redis_data:
|
||||||
|
|
||||||
|
networks:
|
||||||
|
app-network:
|
||||||
|
driver: bridge
|
||||||
|
|
@ -83,8 +83,6 @@ services:
|
||||||
MINIO_BUCKET: "voice-audio"
|
MINIO_BUCKET: "voice-audio"
|
||||||
MINIO_SECURE: "false"
|
MINIO_SECURE: "false"
|
||||||
|
|
||||||
MPS_API_URL: "https://dograh.a.pinggy.link"
|
|
||||||
|
|
||||||
# Langfuse
|
# Langfuse
|
||||||
ENABLE_TRACING: "false"
|
ENABLE_TRACING: "false"
|
||||||
# LANGFUSE_SECRET_KEY: ""
|
# LANGFUSE_SECRET_KEY: ""
|
||||||
|
|
@ -169,6 +167,9 @@ services:
|
||||||
# Server-side URL (SSR, internal Docker network)
|
# Server-side URL (SSR, internal Docker network)
|
||||||
BACKEND_URL: "http://api:8000"
|
BACKEND_URL: "http://api:8000"
|
||||||
|
|
||||||
|
# Controls some feature flags like voicemail detection
|
||||||
|
NEXT_PUBLIC_DEPLOYMENT_MODE: "oss"
|
||||||
|
|
||||||
# Posthog
|
# Posthog
|
||||||
NEXT_PUBLIC_ENABLE_POSTHOG: "true"
|
NEXT_PUBLIC_ENABLE_POSTHOG: "true"
|
||||||
NEXT_PUBLIC_POSTHOG_KEY: "phc_st6dverimoydkpM5m0a9aeAr8znUYWznEaQa8v80E2D"
|
NEXT_PUBLIC_POSTHOG_KEY: "phc_st6dverimoydkpM5m0a9aeAr8znUYWznEaQa8v80E2D"
|
||||||
|
|
|
||||||
|
|
@ -1,20 +1,32 @@
|
||||||
import { redirect } from "next/navigation";
|
import { redirect } from "next/navigation";
|
||||||
|
|
||||||
import { getServerAuthProvider, getServerUser } from "@/lib/auth/server";
|
import { getServerAuthProvider, getServerUser } from "@/lib/auth/server";
|
||||||
|
import logger from '@/lib/logger';
|
||||||
import { getRedirectUrl } from "@/lib/utils";
|
import { getRedirectUrl } from "@/lib/utils";
|
||||||
|
|
||||||
|
export const dynamic = 'force-dynamic';
|
||||||
|
|
||||||
export default async function AfterSignInPage() {
|
export default async function AfterSignInPage() {
|
||||||
|
logger.debug('[AfterSignInPage] Starting after-sign-in page');
|
||||||
const authProvider = getServerAuthProvider();
|
const authProvider = getServerAuthProvider();
|
||||||
|
logger.debug('[AfterSignInPage] Auth provider:', authProvider);
|
||||||
|
logger.debug('[AfterSignInPage] Getting server user...');
|
||||||
const user = await getServerUser();
|
const user = await getServerUser();
|
||||||
|
logger.debug('[AfterSignInPage] Got user:', { hasUser: !!user, userId: user?.id });
|
||||||
|
|
||||||
if (authProvider === 'stack' && user && 'getAuthJson' in user) {
|
if (authProvider === 'stack' && user && 'getAuthJson' in user) {
|
||||||
|
logger.debug('[AfterSignInPage] Stack user detected, getting auth token...');
|
||||||
const token = await user.getAuthJson();
|
const token = await user.getAuthJson();
|
||||||
|
logger.debug('[AfterSignInPage] Got token:', { hasToken: !!token?.accessToken });
|
||||||
const permissions = 'listPermissions' in user && 'selectedTeam' in user
|
const permissions = 'listPermissions' in user && 'selectedTeam' in user
|
||||||
? await user.listPermissions(user.selectedTeam!) ?? []
|
? await user.listPermissions(user.selectedTeam!) ?? []
|
||||||
: [];
|
: [];
|
||||||
|
logger.debug('[AfterSignInPage] Got permissions:', { count: permissions.length });
|
||||||
const redirectUrl = await getRedirectUrl(token?.accessToken ?? "", permissions);
|
const redirectUrl = await getRedirectUrl(token?.accessToken ?? "", permissions);
|
||||||
|
logger.debug('[AfterSignInPage] Redirecting to:', redirectUrl);
|
||||||
redirect(redirectUrl);
|
redirect(redirectUrl);
|
||||||
}
|
}
|
||||||
// For local provider or if user is not available, redirect to create-workflow
|
// For local provider or if user is not available, redirect to create-workflow
|
||||||
|
logger.debug('[AfterSignInPage] Fallback redirect to /create-workflow');
|
||||||
redirect('/create-workflow');
|
redirect('/create-workflow');
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -21,10 +21,18 @@ import { Input } from '@/components/ui/input';
|
||||||
import { Label } from '@/components/ui/label';
|
import { Label } from '@/components/ui/label';
|
||||||
import { Skeleton } from '@/components/ui/skeleton';
|
import { Skeleton } from '@/components/ui/skeleton';
|
||||||
import { useAuth } from '@/lib/auth';
|
import { useAuth } from '@/lib/auth';
|
||||||
|
import logger from '@/lib/logger';
|
||||||
|
|
||||||
export default function APIKeysPage() {
|
export default function APIKeysPage() {
|
||||||
const { user, getAccessToken, redirectToLogin, loading } = useAuth();
|
const { user, getAccessToken, redirectToLogin, loading } = useAuth();
|
||||||
|
|
||||||
|
logger.debug('[APIKeysPage] Component render', {
|
||||||
|
loading,
|
||||||
|
hasUser: !!user,
|
||||||
|
userId: user?.id,
|
||||||
|
timestamp: new Date().toISOString()
|
||||||
|
});
|
||||||
|
|
||||||
const [apiKeys, setApiKeys] = useState<ApiKeyResponse[]>([]);
|
const [apiKeys, setApiKeys] = useState<ApiKeyResponse[]>([]);
|
||||||
const [serviceKeys, setServiceKeys] = useState<ServiceKeyResponse[]>([]);
|
const [serviceKeys, setServiceKeys] = useState<ServiceKeyResponse[]>([]);
|
||||||
const [isLoading, setIsLoading] = useState(true);
|
const [isLoading, setIsLoading] = useState(true);
|
||||||
|
|
@ -49,12 +57,24 @@ export default function APIKeysPage() {
|
||||||
}, [loading, user, redirectToLogin]);
|
}, [loading, user, redirectToLogin]);
|
||||||
|
|
||||||
const fetchApiKeys = useCallback(async () => {
|
const fetchApiKeys = useCallback(async () => {
|
||||||
if (!user) return;
|
logger.debug('[APIKeysPage] fetchApiKeys called', {
|
||||||
|
loading,
|
||||||
|
hasUser: !!user,
|
||||||
|
userId: user?.id
|
||||||
|
});
|
||||||
|
|
||||||
|
// Follow the pattern from UserConfigContext - check both loading and user
|
||||||
|
if (loading || !user) {
|
||||||
|
logger.debug('[APIKeysPage] fetchApiKeys - skipping due to loading or no user');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
setIsLoading(true);
|
setIsLoading(true);
|
||||||
setError(null);
|
setError(null);
|
||||||
|
logger.debug('[APIKeysPage] fetchApiKeys - calling getAccessToken...');
|
||||||
const accessToken = await getAccessToken();
|
const accessToken = await getAccessToken();
|
||||||
|
logger.debug('[APIKeysPage] fetchApiKeys - got access token');
|
||||||
|
|
||||||
const response = await getApiKeysApiV1UserApiKeysGet({
|
const response = await getApiKeysApiV1UserApiKeysGet({
|
||||||
query: {
|
query: {
|
||||||
|
|
@ -76,15 +96,27 @@ export default function APIKeysPage() {
|
||||||
} finally {
|
} finally {
|
||||||
setIsLoading(false);
|
setIsLoading(false);
|
||||||
}
|
}
|
||||||
}, [user, getAccessToken, showArchived]);
|
}, [loading, user, getAccessToken, showArchived]);
|
||||||
|
|
||||||
const fetchServiceKeys = useCallback(async () => {
|
const fetchServiceKeys = useCallback(async () => {
|
||||||
if (!user) return;
|
logger.debug('[APIKeysPage] fetchServiceKeys called', {
|
||||||
|
loading,
|
||||||
|
hasUser: !!user,
|
||||||
|
userId: user?.id
|
||||||
|
});
|
||||||
|
|
||||||
|
// Follow the pattern from UserConfigContext - check both loading and user
|
||||||
|
if (loading || !user) {
|
||||||
|
logger.debug('[APIKeysPage] fetchServiceKeys - skipping due to loading or no user');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
setIsServiceKeysLoading(true);
|
setIsServiceKeysLoading(true);
|
||||||
setError(null);
|
setError(null);
|
||||||
|
logger.debug('[APIKeysPage] fetchServiceKeys - calling getAccessToken...');
|
||||||
const accessToken = await getAccessToken();
|
const accessToken = await getAccessToken();
|
||||||
|
logger.debug('[APIKeysPage] fetchServiceKeys - got access token');
|
||||||
|
|
||||||
const response = await getServiceKeysApiV1UserServiceKeysGet({
|
const response = await getServiceKeysApiV1UserServiceKeysGet({
|
||||||
query: {
|
query: {
|
||||||
|
|
@ -104,13 +136,15 @@ export default function APIKeysPage() {
|
||||||
} finally {
|
} finally {
|
||||||
setIsServiceKeysLoading(false);
|
setIsServiceKeysLoading(false);
|
||||||
}
|
}
|
||||||
}, [user, getAccessToken, showServiceArchived]);
|
}, [loading, user, getAccessToken, showServiceArchived]);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
|
logger.debug('[APIKeysPage] useEffect for fetchApiKeys triggered');
|
||||||
fetchApiKeys();
|
fetchApiKeys();
|
||||||
}, [fetchApiKeys]);
|
}, [fetchApiKeys]);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
|
logger.debug('[APIKeysPage] useEffect for fetchServiceKeys triggered');
|
||||||
fetchServiceKeys();
|
fetchServiceKeys();
|
||||||
}, [fetchServiceKeys]);
|
}, [fetchServiceKeys]);
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -6,6 +6,14 @@ import { useState } from 'react';
|
||||||
import { createWorkflowFromTemplateApiV1WorkflowCreateTemplatePost } from '@/client/sdk.gen';
|
import { createWorkflowFromTemplateApiV1WorkflowCreateTemplatePost } from '@/client/sdk.gen';
|
||||||
import { Button } from '@/components/ui/button';
|
import { Button } from '@/components/ui/button';
|
||||||
import { Card, CardContent, CardDescription, CardHeader } from '@/components/ui/card';
|
import { Card, CardContent, CardDescription, CardHeader } from '@/components/ui/card';
|
||||||
|
import {
|
||||||
|
Dialog,
|
||||||
|
DialogContent,
|
||||||
|
DialogDescription,
|
||||||
|
DialogFooter,
|
||||||
|
DialogHeader,
|
||||||
|
DialogTitle,
|
||||||
|
} from '@/components/ui/dialog';
|
||||||
import { Input } from '@/components/ui/input';
|
import { Input } from '@/components/ui/input';
|
||||||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
|
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
|
||||||
import { useAuth } from '@/lib/auth';
|
import { useAuth } from '@/lib/auth';
|
||||||
|
|
@ -16,6 +24,8 @@ export default function CreateWorkflowPage() {
|
||||||
const { user, getAccessToken } = useAuth();
|
const { user, getAccessToken } = useAuth();
|
||||||
const [isLoading, setIsLoading] = useState(false);
|
const [isLoading, setIsLoading] = useState(false);
|
||||||
const [error, setError] = useState<string | null>(null);
|
const [error, setError] = useState<string | null>(null);
|
||||||
|
const [showSuccessModal, setShowSuccessModal] = useState(false);
|
||||||
|
const [workflowId, setWorkflowId] = useState<string | null>(null);
|
||||||
|
|
||||||
const [callType, setCallType] = useState<'INBOUND' | 'OUTBOUND'>('INBOUND');
|
const [callType, setCallType] = useState<'INBOUND' | 'OUTBOUND'>('INBOUND');
|
||||||
const [useCase, setUseCase] = useState('');
|
const [useCase, setUseCase] = useState('');
|
||||||
|
|
@ -51,7 +61,8 @@ export default function CreateWorkflowPage() {
|
||||||
});
|
});
|
||||||
|
|
||||||
if (response.data?.id) {
|
if (response.data?.id) {
|
||||||
router.push(`/workflow/${response.data.id}`);
|
setWorkflowId(String(response.data.id));
|
||||||
|
setShowSuccessModal(true);
|
||||||
}
|
}
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
setError('Failed to create workflow. Please try again.');
|
setError('Failed to create workflow. Please try again.');
|
||||||
|
|
@ -61,6 +72,12 @@ export default function CreateWorkflowPage() {
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
const handleModalContinue = () => {
|
||||||
|
if (workflowId) {
|
||||||
|
router.push(`/workflow/${workflowId}`);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="min-h-[calc(100vh-64px)] flex items-center justify-center p-4 bg-gradient-to-br from-gray-50 to-gray-100 dark:from-gray-900 dark:to-gray-800">
|
<div className="min-h-[calc(100vh-64px)] flex items-center justify-center p-4 bg-gradient-to-br from-gray-50 to-gray-100 dark:from-gray-900 dark:to-gray-800">
|
||||||
<Card className="w-full max-w-4xl shadow-xl border-0 bg-white/95 dark:bg-gray-900/95 backdrop-blur">
|
<Card className="w-full max-w-4xl shadow-xl border-0 bg-white/95 dark:bg-gray-900/95 backdrop-blur">
|
||||||
|
|
@ -165,6 +182,79 @@ export default function CreateWorkflowPage() {
|
||||||
</div>
|
</div>
|
||||||
</CardContent>
|
</CardContent>
|
||||||
</Card>
|
</Card>
|
||||||
|
|
||||||
|
{/* Loading Overlay */}
|
||||||
|
{isLoading && (
|
||||||
|
<div className="fixed inset-0 z-50 flex items-center justify-center bg-black/60 backdrop-blur-sm">
|
||||||
|
<Card className="w-full max-w-md p-8 bg-white dark:bg-gray-900 border-0 shadow-2xl">
|
||||||
|
<div className="flex flex-col items-center space-y-6">
|
||||||
|
{/* Animated spinner */}
|
||||||
|
<div className="relative">
|
||||||
|
<div className="w-20 h-20 border-4 border-gray-200 dark:border-gray-700 rounded-full"></div>
|
||||||
|
<div className="absolute top-0 left-0 w-20 h-20 border-4 border-transparent border-t-blue-600 rounded-full animate-spin"></div>
|
||||||
|
<div className="absolute top-2 left-2 w-16 h-16 border-4 border-transparent border-t-purple-600 rounded-full animate-spin-slow"></div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="text-center space-y-2">
|
||||||
|
<h3 className="text-xl font-bold bg-gradient-to-r from-blue-600 to-purple-600 bg-clip-text text-transparent">
|
||||||
|
Creating Your Workflow
|
||||||
|
</h3>
|
||||||
|
<p className="text-sm text-gray-600 dark:text-gray-400 max-w-xs">
|
||||||
|
We're setting up your voice agent with your specifications. This will just take a moment...
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Animated dots */}
|
||||||
|
<div className="flex space-x-2">
|
||||||
|
<div className="w-2 h-2 bg-blue-600 rounded-full animate-bounce" style={{ animationDelay: '0ms' }}></div>
|
||||||
|
<div className="w-2 h-2 bg-purple-600 rounded-full animate-bounce" style={{ animationDelay: '150ms' }}></div>
|
||||||
|
<div className="w-2 h-2 bg-blue-600 rounded-full animate-bounce" style={{ animationDelay: '300ms' }}></div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</Card>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{/* Success Modal */}
|
||||||
|
<Dialog open={showSuccessModal} onOpenChange={setShowSuccessModal}>
|
||||||
|
<DialogContent className="sm:max-w-lg">
|
||||||
|
<DialogHeader>
|
||||||
|
<DialogTitle className="text-xl font-bold flex items-center gap-2">
|
||||||
|
<svg className="w-6 h-6 text-green-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||||
|
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z" />
|
||||||
|
</svg>
|
||||||
|
Workflow Created Successfully!
|
||||||
|
</DialogTitle>
|
||||||
|
<DialogDescription asChild>
|
||||||
|
<div className="text-base mt-4 space-y-3 text-gray-700 dark:text-gray-300">
|
||||||
|
<p>
|
||||||
|
A starter template has been generated for your use case, with some randomised data and sample actions.
|
||||||
|
</p>
|
||||||
|
<p>
|
||||||
|
The voice bot is pre-set to communicate in English with an American accent.
|
||||||
|
</p>
|
||||||
|
<p>
|
||||||
|
You're encouraged to first test the bot and then modify it to your specific requirements and location (currency/accent etc).
|
||||||
|
</p>
|
||||||
|
<p className="pt-2 text-sm">
|
||||||
|
Feel free to join our <span className="font-semibold text-blue-600 dark:text-blue-400">Slack channel</span> for any queries and star us on <span className="font-semibold text-gray-900 dark:text-gray-100">GitHub</span>.
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
</DialogDescription>
|
||||||
|
</DialogHeader>
|
||||||
|
<DialogFooter className="mt-6">
|
||||||
|
<Button
|
||||||
|
onClick={handleModalContinue}
|
||||||
|
className="w-full bg-gradient-to-r from-blue-600 to-purple-600 hover:from-blue-700 hover:to-purple-700 font-semibold"
|
||||||
|
>
|
||||||
|
Continue to Workflow
|
||||||
|
<svg className="w-4 h-4 ml-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||||
|
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M13 7l5 5m0 0l-5 5m5-5H6" />
|
||||||
|
</svg>
|
||||||
|
</Button>
|
||||||
|
</DialogFooter>
|
||||||
|
</DialogContent>
|
||||||
|
</Dialog>
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -123,3 +123,16 @@
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@keyframes spin-slow {
|
||||||
|
from {
|
||||||
|
transform: rotate(0deg);
|
||||||
|
}
|
||||||
|
to {
|
||||||
|
transform: rotate(360deg);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
.animate-spin-slow {
|
||||||
|
animation: spin-slow 3s linear infinite;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -6,6 +6,8 @@ import logger from '@/lib/logger';
|
||||||
|
|
||||||
import CreateIntegrationButton from "./CreateIntegrationButton";
|
import CreateIntegrationButton from "./CreateIntegrationButton";
|
||||||
|
|
||||||
|
export const dynamic = 'force-dynamic';
|
||||||
|
|
||||||
// Server component for integration list
|
// Server component for integration list
|
||||||
async function IntegrationList() {
|
async function IntegrationList() {
|
||||||
const authProvider = getServerAuthProvider();
|
const authProvider = getServerAuthProvider();
|
||||||
|
|
|
||||||
|
|
@ -6,6 +6,8 @@ import { getServerAuthProvider, isServerAuthenticated } from '@/lib/auth/server'
|
||||||
|
|
||||||
import LoopTalkLayout from "./LoopTalkLayout";
|
import LoopTalkLayout from "./LoopTalkLayout";
|
||||||
|
|
||||||
|
export const dynamic = 'force-dynamic';
|
||||||
|
|
||||||
async function PageContent() {
|
async function PageContent() {
|
||||||
const authProvider = getServerAuthProvider();
|
const authProvider = getServerAuthProvider();
|
||||||
const isAuthenticated = await isServerAuthenticated();
|
const isAuthenticated = await isServerAuthenticated();
|
||||||
|
|
|
||||||
|
|
@ -5,29 +5,42 @@ import { getServerAuthProvider,getServerUser } from "@/lib/auth/server";
|
||||||
import logger from '@/lib/logger';
|
import logger from '@/lib/logger';
|
||||||
import { getRedirectUrl } from "@/lib/utils";
|
import { getRedirectUrl } from "@/lib/utils";
|
||||||
|
|
||||||
|
export const dynamic = 'force-dynamic';
|
||||||
|
|
||||||
export default async function Home() {
|
export default async function Home() {
|
||||||
|
logger.debug('[HomePage] Starting Home page render');
|
||||||
const authProvider = getServerAuthProvider();
|
const authProvider = getServerAuthProvider();
|
||||||
|
logger.debug('[HomePage] Auth provider:', authProvider);
|
||||||
|
|
||||||
// For local/OSS provider, always redirect to workflow page
|
// For local/OSS provider, always redirect to workflow page
|
||||||
if (authProvider === 'local') {
|
if (authProvider === 'local') {
|
||||||
logger.debug('Redirecting to workflow page for local provider');
|
logger.debug('[HomePage] Redirecting to workflow page for local provider');
|
||||||
redirect('/create-workflow');
|
redirect('/create-workflow');
|
||||||
}
|
}
|
||||||
|
|
||||||
|
logger.debug('[HomePage] Getting server user...');
|
||||||
const user = await getServerUser();
|
const user = await getServerUser();
|
||||||
|
|
||||||
logger.debug(`authProvider: ${authProvider}, user: ${JSON.stringify(user)}`);
|
logger.debug('[HomePage] Server user result:', {
|
||||||
|
hasUser: !!user,
|
||||||
|
userId: user?.id,
|
||||||
|
authProvider
|
||||||
|
});
|
||||||
|
|
||||||
if (user) {
|
if (user) {
|
||||||
try {
|
try {
|
||||||
// For Stack provider, get the token and permissions
|
// For Stack provider, get the token and permissions
|
||||||
if (authProvider === 'stack' && 'getAuthJson' in user) {
|
if (authProvider === 'stack' && 'getAuthJson' in user) {
|
||||||
|
logger.debug('[HomePage] Getting auth token from Stack user...');
|
||||||
const token = await user.getAuthJson();
|
const token = await user.getAuthJson();
|
||||||
|
logger.debug('[HomePage] Got auth token:', { hasToken: !!token?.accessToken });
|
||||||
const permissions = 'listPermissions' in user && 'selectedTeam' in user
|
const permissions = 'listPermissions' in user && 'selectedTeam' in user
|
||||||
? await user.listPermissions(user.selectedTeam!) ?? []
|
? await user.listPermissions(user.selectedTeam!) ?? []
|
||||||
: [];
|
: [];
|
||||||
|
logger.debug('[HomePage] Got permissions:', { count: permissions.length });
|
||||||
|
logger.debug('[HomePage] Getting redirect URL...');
|
||||||
const redirectUrl = await getRedirectUrl(token?.accessToken ?? "", permissions);
|
const redirectUrl = await getRedirectUrl(token?.accessToken ?? "", permissions);
|
||||||
logger.debug(`redirectUrl: ${redirectUrl}`);
|
logger.debug('[HomePage] Redirecting to:', redirectUrl);
|
||||||
redirect(redirectUrl);
|
redirect(redirectUrl);
|
||||||
}
|
}
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
|
|
|
||||||
|
|
@ -67,6 +67,7 @@ const WorkflowHeader = ({ isDirty, workflowName, rfInstance, onRun, workflowId,
|
||||||
const { user, getAccessToken } = useAuth();
|
const { user, getAccessToken } = useAuth();
|
||||||
|
|
||||||
const hasValidationErrors = workflowValidationErrors.length > 0;
|
const hasValidationErrors = workflowValidationErrors.length > 0;
|
||||||
|
const isOSSDeployment = process.env.NEXT_PUBLIC_DEPLOYMENT_MODE === 'oss';
|
||||||
|
|
||||||
// Reset call-related state whenever the dialog is closed so that a new call can be placed
|
// Reset call-related state whenever the dialog is closed so that a new call can be placed
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
|
|
@ -195,15 +196,17 @@ const WorkflowHeader = ({ isDirty, workflowName, rfInstance, onRun, workflowId,
|
||||||
<Phone className="mr-2 h-4 w-4" />
|
<Phone className="mr-2 h-4 w-4" />
|
||||||
Web Call
|
Web Call
|
||||||
</Button>
|
</Button>
|
||||||
<Button
|
{!isOSSDeployment && (
|
||||||
variant="outline"
|
<Button
|
||||||
size="sm"
|
variant="outline"
|
||||||
onClick={() => setDialogOpen(true)}
|
size="sm"
|
||||||
disabled={hasValidationErrors}
|
onClick={() => setDialogOpen(true)}
|
||||||
>
|
disabled={hasValidationErrors}
|
||||||
<Phone className="mr-2 h-4 w-4" />
|
>
|
||||||
Phone Call
|
<Phone className="mr-2 h-4 w-4" />
|
||||||
</Button>
|
Phone Call
|
||||||
|
</Button>
|
||||||
|
)}
|
||||||
|
|
||||||
{isDirty ? (
|
{isDirty ? (
|
||||||
<Button
|
<Button
|
||||||
|
|
|
||||||
|
|
@ -13,6 +13,8 @@ import logger from '@/lib/logger';
|
||||||
|
|
||||||
import WorkflowLayout from "./WorkflowLayout";
|
import WorkflowLayout from "./WorkflowLayout";
|
||||||
|
|
||||||
|
export const dynamic = 'force-dynamic';
|
||||||
|
|
||||||
// Server component for workflow templates
|
// Server component for workflow templates
|
||||||
async function WorkflowTemplatesList() {
|
async function WorkflowTemplatesList() {
|
||||||
try {
|
try {
|
||||||
|
|
|
||||||
|
|
@ -170,6 +170,7 @@ const StartCallEditForm = ({
|
||||||
delayedStartDuration,
|
delayedStartDuration,
|
||||||
setDelayedStartDuration
|
setDelayedStartDuration
|
||||||
}: StartCallEditFormProps) => {
|
}: StartCallEditFormProps) => {
|
||||||
|
const isOSS = process.env.NEXT_PUBLIC_DEPLOYMENT_MODE === 'oss';
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="grid gap-2">
|
<div className="grid gap-2">
|
||||||
|
|
@ -240,19 +241,21 @@ const StartCallEditForm = ({
|
||||||
</Label>
|
</Label>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<div className="flex items-center space-x-2">
|
{!isOSS && (
|
||||||
<Switch
|
<div className="flex items-center space-x-2">
|
||||||
id="detect-voicemail"
|
<Switch
|
||||||
checked={detectVoicemail}
|
id="detect-voicemail"
|
||||||
onCheckedChange={setDetectVoicemail}
|
checked={detectVoicemail}
|
||||||
/>
|
onCheckedChange={setDetectVoicemail}
|
||||||
<Label htmlFor="detect-voicemail">
|
/>
|
||||||
Detect Voicemail
|
<Label htmlFor="detect-voicemail">
|
||||||
</Label>
|
Detect Voicemail
|
||||||
<Label className="text-xs text-gray-500">
|
</Label>
|
||||||
Automatically detect and end call if voicemail is reached.
|
<Label className="text-xs text-gray-500">
|
||||||
</Label>
|
Automatically detect and end call if voicemail is reached.
|
||||||
</div>
|
</Label>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
<div className="flex flex-col space-y-2">
|
<div className="flex flex-col space-y-2">
|
||||||
<div className="flex items-center space-x-2">
|
<div className="flex items-center space-x-2">
|
||||||
<Switch
|
<Switch
|
||||||
|
|
|
||||||
|
|
@ -2,11 +2,25 @@
|
||||||
|
|
||||||
import React from 'react';
|
import React from 'react';
|
||||||
|
|
||||||
|
import logger from '@/lib/logger';
|
||||||
|
|
||||||
import { useAuthContext } from '../providers/AuthProvider';
|
import { useAuthContext } from '../providers/AuthProvider';
|
||||||
|
|
||||||
export function useAuth() {
|
export function useAuth() {
|
||||||
|
const renderCount = React.useRef(0);
|
||||||
|
renderCount.current++;
|
||||||
|
|
||||||
const context = useAuthContext();
|
const context = useAuthContext();
|
||||||
|
|
||||||
|
logger.debug('[useAuth] Hook called', {
|
||||||
|
renderCount: renderCount.current,
|
||||||
|
hasUser: !!context.user,
|
||||||
|
userId: context.user?.id,
|
||||||
|
isAuthenticated: context.isAuthenticated,
|
||||||
|
loading: context.loading,
|
||||||
|
provider: context.provider
|
||||||
|
});
|
||||||
|
|
||||||
// Memoize functions that are recreated on every render
|
// Memoize functions that are recreated on every render
|
||||||
const logout = React.useCallback(() => context.service.logout(), [context.service]);
|
const logout = React.useCallback(() => context.service.logout(), [context.service]);
|
||||||
const redirectToLogin = React.useCallback(() => context.service.redirectToLogin(), [context.service]);
|
const redirectToLogin = React.useCallback(() => context.service.redirectToLogin(), [context.service]);
|
||||||
|
|
|
||||||
|
|
@ -3,10 +3,28 @@
|
||||||
import { StackClientApp,StackProvider, StackTheme, useUser as useStackUser } from '@stackframe/stack';
|
import { StackClientApp,StackProvider, StackTheme, useUser as useStackUser } from '@stackframe/stack';
|
||||||
import React, { useEffect, useState } from 'react';
|
import React, { useEffect, useState } from 'react';
|
||||||
|
|
||||||
|
import logger from '@/lib/logger';
|
||||||
|
|
||||||
import { StackAuthService } from '../services';
|
import { StackAuthService } from '../services';
|
||||||
import type { AuthUser } from '../types';
|
import type { AuthUser } from '../types';
|
||||||
import { AuthContext } from './AuthProvider';
|
import { AuthContext } from './AuthProvider';
|
||||||
|
|
||||||
|
// Create a singleton StackClientApp instance to prevent multiple initializations
|
||||||
|
let stackClientAppInstance: StackClientApp<true, string> | null = null;
|
||||||
|
|
||||||
|
function getStackClientApp(): StackClientApp<true, string> {
|
||||||
|
if (!stackClientAppInstance) {
|
||||||
|
logger.debug('[StackProviderWrapper] Creating singleton StackClientApp instance');
|
||||||
|
stackClientAppInstance = new StackClientApp({
|
||||||
|
tokenStore: "nextjs-cookie",
|
||||||
|
urls: {
|
||||||
|
afterSignIn: "/after-sign-in"
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
return stackClientAppInstance;
|
||||||
|
}
|
||||||
|
|
||||||
interface StackProviderWrapperProps {
|
interface StackProviderWrapperProps {
|
||||||
service: StackAuthService;
|
service: StackAuthService;
|
||||||
children: React.ReactNode;
|
children: React.ReactNode;
|
||||||
|
|
@ -14,29 +32,84 @@ interface StackProviderWrapperProps {
|
||||||
|
|
||||||
// Stack-specific context provider that uses the useUser hook
|
// Stack-specific context provider that uses the useUser hook
|
||||||
function StackAuthContextProvider({ service, children }: { service: StackAuthService; children: React.ReactNode }) {
|
function StackAuthContextProvider({ service, children }: { service: StackAuthService; children: React.ReactNode }) {
|
||||||
const [loading, setLoading] = useState(true);
|
const renderCount = React.useRef(0);
|
||||||
|
const lastUserId = React.useRef<string | undefined>(undefined);
|
||||||
|
renderCount.current++;
|
||||||
|
|
||||||
|
logger.debug(`[StackAuthContextProvider] Render #${renderCount.current} - Starting`);
|
||||||
|
|
||||||
const stackUser = useStackUser(); // Always call the hook
|
const stackUser = useStackUser(); // Always call the hook
|
||||||
|
const [isInitialized, setIsInitialized] = useState(false);
|
||||||
|
|
||||||
|
// Track if user actually changed
|
||||||
|
const userChanged = lastUserId.current !== stackUser?.id;
|
||||||
|
if (userChanged) {
|
||||||
|
lastUserId.current = stackUser?.id;
|
||||||
|
}
|
||||||
|
|
||||||
|
logger.debug(`[StackAuthContextProvider] Render #${renderCount.current} - stackUser:`, {
|
||||||
|
hasUser: !!stackUser,
|
||||||
|
userId: stackUser?.id,
|
||||||
|
isInitialized,
|
||||||
|
userChanged
|
||||||
|
});
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
// Set the user instance in the service
|
// Only log and update if user actually changed
|
||||||
if (service instanceof StackAuthService && stackUser) {
|
if (!userChanged && isInitialized) {
|
||||||
service.setUserInstance(stackUser);
|
return;
|
||||||
setLoading(false);
|
|
||||||
} else if (!stackUser) {
|
|
||||||
setLoading(false);
|
|
||||||
}
|
}
|
||||||
}, [service, stackUser]);
|
|
||||||
|
|
||||||
const getAccessToken = React.useCallback(() => service.getAccessToken(), [service]);
|
logger.debug('[StackAuthContextProvider] useEffect triggered (user changed)', {
|
||||||
|
hasUser: !!stackUser,
|
||||||
|
userId: stackUser?.id,
|
||||||
|
isInitialized,
|
||||||
|
isStackAuthService: service instanceof StackAuthService
|
||||||
|
});
|
||||||
|
|
||||||
const contextValue = React.useMemo(() => ({
|
// Only update the service once when user becomes available
|
||||||
service,
|
if (!isInitialized && service instanceof StackAuthService && stackUser) {
|
||||||
user: stackUser as AuthUser, // Pass the actual Stack CurrentUser
|
logger.debug('[StackAuthContextProvider] Setting user instance in service', {
|
||||||
isAuthenticated: service.isAuthenticated(),
|
userId: stackUser.id
|
||||||
loading,
|
});
|
||||||
getAccessToken,
|
service.setUserInstance(stackUser);
|
||||||
provider: service.getProviderName(),
|
setIsInitialized(true);
|
||||||
}), [service, stackUser, loading, getAccessToken]);
|
}
|
||||||
|
}, [service, stackUser, isInitialized, userChanged]);
|
||||||
|
|
||||||
|
const getAccessToken = React.useCallback(() => {
|
||||||
|
logger.debug('[StackAuthContextProvider] getAccessToken called');
|
||||||
|
return service.getAccessToken();
|
||||||
|
}, [service]);
|
||||||
|
|
||||||
|
// Stabilize the context value to prevent unnecessary re-renders
|
||||||
|
const contextValue = React.useMemo(() => {
|
||||||
|
const isAuth = service.isAuthenticated();
|
||||||
|
// IMPORTANT: Stay in loading state until service is initialized (has user set)
|
||||||
|
// Even if stackUser exists, we're still loading until setUserInstance is called
|
||||||
|
const loadingState = !isInitialized;
|
||||||
|
|
||||||
|
const value = {
|
||||||
|
service,
|
||||||
|
user: stackUser as AuthUser, // Pass the actual Stack CurrentUser
|
||||||
|
isAuthenticated: isAuth,
|
||||||
|
loading: loadingState, // Loading until service is initialized
|
||||||
|
getAccessToken,
|
||||||
|
provider: service.getProviderName(),
|
||||||
|
};
|
||||||
|
|
||||||
|
logger.debug('[StackAuthContextProvider] Context value created', {
|
||||||
|
isAuthenticated: isAuth,
|
||||||
|
loading: loadingState,
|
||||||
|
hasUser: !!value.user,
|
||||||
|
userId: stackUser?.id,
|
||||||
|
isInitialized,
|
||||||
|
provider: value.provider,
|
||||||
|
serviceHasUser: isAuth
|
||||||
|
});
|
||||||
|
|
||||||
|
return value;
|
||||||
|
}, [service, stackUser, isInitialized, getAccessToken]);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<AuthContext.Provider value={contextValue}>
|
<AuthContext.Provider value={contextValue}>
|
||||||
|
|
@ -46,13 +119,10 @@ function StackAuthContextProvider({ service, children }: { service: StackAuthSer
|
||||||
}
|
}
|
||||||
|
|
||||||
export function StackProviderWrapper({ service, children }: StackProviderWrapperProps) {
|
export function StackProviderWrapper({ service, children }: StackProviderWrapperProps) {
|
||||||
// Create the Stack client app here, only when actually needed
|
logger.debug('[StackProviderWrapper] Rendering wrapper');
|
||||||
const stackClientApp = new StackClientApp({
|
|
||||||
tokenStore: "nextjs-cookie",
|
// Use the singleton instance
|
||||||
urls: {
|
const stackClientApp = getStackClientApp();
|
||||||
afterSignIn: "/after-sign-in"
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<StackProvider app={stackClientApp}>
|
<StackProvider app={stackClientApp}>
|
||||||
|
|
|
||||||
|
|
@ -1,16 +1,30 @@
|
||||||
|
import logger from '@/lib/logger';
|
||||||
|
|
||||||
import type { AuthProvider } from '../types';
|
import type { AuthProvider } from '../types';
|
||||||
import type { IAuthService } from './interface';
|
import type { IAuthService } from './interface';
|
||||||
import { LocalAuthService } from './localAuthService';
|
import { LocalAuthService } from './localAuthService';
|
||||||
import { StackAuthService } from './stackAuthService';
|
import { StackAuthService } from './stackAuthService';
|
||||||
|
|
||||||
|
// Singleton instances for auth services
|
||||||
|
let stackServiceInstance: StackAuthService | null = null;
|
||||||
|
let localServiceInstance: LocalAuthService | null = null;
|
||||||
|
|
||||||
export function createAuthService(provider?: AuthProvider | string): IAuthService {
|
export function createAuthService(provider?: AuthProvider | string): IAuthService {
|
||||||
const authProvider = provider || process.env.NEXT_PUBLIC_AUTH_PROVIDER || 'stack';
|
const authProvider = provider || process.env.NEXT_PUBLIC_AUTH_PROVIDER || 'stack';
|
||||||
|
|
||||||
switch (authProvider) {
|
switch (authProvider) {
|
||||||
case 'stack':
|
case 'stack':
|
||||||
return new StackAuthService();
|
if (!stackServiceInstance) {
|
||||||
|
logger.debug('[createAuthService] Creating singleton StackAuthService instance');
|
||||||
|
stackServiceInstance = new StackAuthService();
|
||||||
|
}
|
||||||
|
return stackServiceInstance;
|
||||||
case 'local':
|
case 'local':
|
||||||
return new LocalAuthService();
|
if (!localServiceInstance) {
|
||||||
|
logger.debug('[createAuthService] Creating singleton LocalAuthService instance');
|
||||||
|
localServiceInstance = new LocalAuthService();
|
||||||
|
}
|
||||||
|
return localServiceInstance;
|
||||||
// Future providers can be added here
|
// Future providers can be added here
|
||||||
// case 'auth0':
|
// case 'auth0':
|
||||||
// return new Auth0Service();
|
// return new Auth0Service();
|
||||||
|
|
@ -18,7 +32,10 @@ export function createAuthService(provider?: AuthProvider | string): IAuthServic
|
||||||
// return new SupabaseService();
|
// return new SupabaseService();
|
||||||
default:
|
default:
|
||||||
console.warn(`Unknown auth provider: ${authProvider}, falling back to local`);
|
console.warn(`Unknown auth provider: ${authProvider}, falling back to local`);
|
||||||
return new LocalAuthService();
|
if (!localServiceInstance) {
|
||||||
|
localServiceInstance = new LocalAuthService();
|
||||||
|
}
|
||||||
|
return localServiceInstance;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -8,24 +8,62 @@ import type { IAuthService } from './interface';
|
||||||
|
|
||||||
export class StackAuthService implements IAuthService {
|
export class StackAuthService implements IAuthService {
|
||||||
private userInstance: CurrentUser | null = null;
|
private userInstance: CurrentUser | null = null;
|
||||||
|
private callCount = {
|
||||||
|
setUserInstance: 0,
|
||||||
|
getAccessToken: 0,
|
||||||
|
refreshToken: 0,
|
||||||
|
getCurrentUser: 0,
|
||||||
|
isAuthenticated: 0
|
||||||
|
};
|
||||||
|
|
||||||
// Set the user instance from the Stack useUser hook
|
// Set the user instance from the Stack useUser hook
|
||||||
setUserInstance(user: CurrentUser) {
|
setUserInstance(user: CurrentUser) {
|
||||||
|
this.callCount.setUserInstance++;
|
||||||
|
logger.debug('[StackAuthService] setUserInstance called', {
|
||||||
|
callCount: this.callCount.setUserInstance,
|
||||||
|
userId: user?.id,
|
||||||
|
hadPreviousUser: !!this.userInstance,
|
||||||
|
previousUserId: this.userInstance?.id,
|
||||||
|
timestamp: new Date().toISOString()
|
||||||
|
});
|
||||||
this.userInstance = user;
|
this.userInstance = user;
|
||||||
|
logger.debug('[StackAuthService] setUserInstance completed - user is now set');
|
||||||
}
|
}
|
||||||
|
|
||||||
async getAccessToken(): Promise<string> {
|
async getAccessToken(): Promise<string> {
|
||||||
|
this.callCount.getAccessToken++;
|
||||||
|
logger.debug('[StackAuthService] getAccessToken called', {
|
||||||
|
callCount: this.callCount.getAccessToken,
|
||||||
|
hasUser: !!this.userInstance,
|
||||||
|
userId: this.userInstance?.id
|
||||||
|
});
|
||||||
|
|
||||||
if (!this.userInstance) {
|
if (!this.userInstance) {
|
||||||
|
logger.error('[StackAuthService] getAccessToken - User not initialized');
|
||||||
throw new Error('User not initialized');
|
throw new Error('User not initialized');
|
||||||
}
|
}
|
||||||
|
|
||||||
|
logger.debug('[StackAuthService] Calling user.getAuthJson()');
|
||||||
const authJson = await this.userInstance.getAuthJson();
|
const authJson = await this.userInstance.getAuthJson();
|
||||||
|
logger.debug('[StackAuthService] getAuthJson returned', {
|
||||||
|
hasToken: !!authJson.accessToken,
|
||||||
|
tokenLength: authJson.accessToken?.length
|
||||||
|
});
|
||||||
|
|
||||||
if (!authJson.accessToken) {
|
if (!authJson.accessToken) {
|
||||||
|
logger.error('[StackAuthService] No access token available');
|
||||||
throw new Error('No access token available');
|
throw new Error('No access token available');
|
||||||
}
|
}
|
||||||
return authJson.accessToken;
|
return authJson.accessToken;
|
||||||
}
|
}
|
||||||
|
|
||||||
async refreshToken(): Promise<string> {
|
async refreshToken(): Promise<string> {
|
||||||
|
this.callCount.refreshToken++;
|
||||||
|
logger.debug('[StackAuthService] refreshToken called', {
|
||||||
|
callCount: this.callCount.refreshToken,
|
||||||
|
hasUser: !!this.userInstance
|
||||||
|
});
|
||||||
|
|
||||||
if (!this.userInstance) {
|
if (!this.userInstance) {
|
||||||
throw new Error('User not initialized');
|
throw new Error('User not initialized');
|
||||||
}
|
}
|
||||||
|
|
@ -38,12 +76,27 @@ export class StackAuthService implements IAuthService {
|
||||||
}
|
}
|
||||||
|
|
||||||
async getCurrentUser(): Promise<CurrentUser | null> {
|
async getCurrentUser(): Promise<CurrentUser | null> {
|
||||||
|
this.callCount.getCurrentUser++;
|
||||||
|
logger.debug('[StackAuthService] getCurrentUser called', {
|
||||||
|
callCount: this.callCount.getCurrentUser,
|
||||||
|
hasUser: !!this.userInstance,
|
||||||
|
userId: this.userInstance?.id
|
||||||
|
});
|
||||||
// Return the actual Stack user instance
|
// Return the actual Stack user instance
|
||||||
return this.userInstance;
|
return this.userInstance;
|
||||||
}
|
}
|
||||||
|
|
||||||
isAuthenticated(): boolean {
|
isAuthenticated(): boolean {
|
||||||
return !!this.userInstance;
|
this.callCount.isAuthenticated++;
|
||||||
|
const isAuth = !!this.userInstance;
|
||||||
|
logger.debug('[StackAuthService] isAuthenticated called', {
|
||||||
|
callCount: this.callCount.isAuthenticated,
|
||||||
|
result: isAuth,
|
||||||
|
hasUserInstance: !!this.userInstance,
|
||||||
|
userId: this.userInstance?.id,
|
||||||
|
timestamp: new Date().toISOString()
|
||||||
|
});
|
||||||
|
return isAuth;
|
||||||
}
|
}
|
||||||
|
|
||||||
redirectToLogin(): void {
|
redirectToLogin(): void {
|
||||||
|
|
|
||||||
|
|
@ -27,27 +27,43 @@ export function debounce<T extends (...args: unknown[]) => unknown>(func: T, wai
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function getRedirectUrl(token: string, permissions: { id: string }[] = []) {
|
export async function getRedirectUrl(token: string, permissions: { id: string }[] = []) {
|
||||||
|
console.log('[getRedirectUrl] Called with:', {
|
||||||
|
hasToken: !!token,
|
||||||
|
tokenLength: token?.length,
|
||||||
|
permissionsCount: permissions.length,
|
||||||
|
permissions: permissions.map(p => p.id)
|
||||||
|
});
|
||||||
try {
|
try {
|
||||||
|
console.log('[getRedirectUrl] Calling getAuthUserApiV1UserAuthUserGet...');
|
||||||
const authUser = await getAuthUserApiV1UserAuthUserGet({
|
const authUser = await getAuthUserApiV1UserAuthUserGet({
|
||||||
headers: {
|
headers: {
|
||||||
Authorization: `Bearer ${token}`,
|
Authorization: `Bearer ${token}`,
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
console.log('[getRedirectUrl] Auth user response:', {
|
||||||
|
hasData: !!authUser.data,
|
||||||
|
isSuperuser: authUser.data?.is_superuser,
|
||||||
|
userId: authUser.data?.id
|
||||||
|
});
|
||||||
if (authUser.data?.is_superuser) {
|
if (authUser.data?.is_superuser) {
|
||||||
|
console.log('[getRedirectUrl] User is superuser, redirecting to /superadmin');
|
||||||
return "/superadmin";
|
return "/superadmin";
|
||||||
}
|
}
|
||||||
|
|
||||||
const hasAdminPermission = permissions.some(p => p.id === 'admin');
|
const hasAdminPermission = permissions.some(p => p.id === 'admin');
|
||||||
|
console.log('[getRedirectUrl] Admin permission check:', { hasAdminPermission });
|
||||||
|
|
||||||
// If the user doesn't have admin permissions, redirect them to
|
// If the user doesn't have admin permissions, redirect them to
|
||||||
// usage page
|
// usage page
|
||||||
if (!hasAdminPermission) {
|
if (!hasAdminPermission) {
|
||||||
|
console.log('[getRedirectUrl] No admin permission, redirecting to /usage');
|
||||||
return "/usage";
|
return "/usage";
|
||||||
}
|
}
|
||||||
|
|
||||||
|
console.log('[getRedirectUrl] Has admin permission, redirecting to /create-workflow');
|
||||||
return "/create-workflow";
|
return "/create-workflow";
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error("Failed to fetch auth user:", error);
|
console.error("[getRedirectUrl] Failed to fetch auth user:", error);
|
||||||
// Re-throw the error so the caller can handle it
|
// Re-throw the error so the caller can handle it
|
||||||
throw error;
|
throw error;
|
||||||
}
|
}
|
||||||
|
|
|
||||||
Loading…
Add table
Add a link
Reference in a new issue