feature(auth): replace clerk.com with custom auth (#103)

* feature(auth): replace clerk.com with custom auth

* minor fixes

* remove notification preferences

* decrease live events interval

fix(api): cookies..

# Conflicts:
#	.gitignore
#	apps/api/src/index.ts
#	apps/dashboard/src/app/providers.tsx
#	packages/trpc/src/trpc.ts
This commit is contained in:
Carl-Gerhard Lindesvärd
2024-12-18 21:30:39 +01:00
committed by Carl-Gerhard Lindesvärd
parent f28802b1c2
commit d31d9924a5
151 changed files with 18484 additions and 12853 deletions

View File

@@ -11,7 +11,12 @@ export const OnboardingDescription = ({
children,
className,
}: Pick<Props, 'children' | 'className'>) => (
<div className={cn('font-medium text-muted-foreground', className)}>
<div
className={cn(
'font-medium text-muted-foreground leading-normal [&_a]:underline [&_a]:font-semibold',
className,
)}
>
{children}
</div>
);

View File

@@ -1,5 +1,6 @@
import { getCurrentOrganizations, getProjectWithClients } from '@openpanel/db';
import { getOrganizations, getProjectWithClients } from '@openpanel/db';
import { auth } from '@openpanel/auth/nextjs';
import OnboardingConnect from './onboarding-connect';
type Props = {
@@ -9,7 +10,8 @@ type Props = {
};
const Connect = async ({ params: { projectId } }: Props) => {
const orgs = await getCurrentOrganizations();
const { userId } = await auth();
const orgs = await getOrganizations(userId);
const organizationId = orgs[0]?.id;
if (!organizationId) {
throw new Error('No organization found');

View File

@@ -33,13 +33,6 @@ const VerifyListener = ({ client, events: _events, onVerified }: Props) => {
const isConnected = events.length > 0;
const renderBadge = () => {
if (isConnected) {
return <Badge variant={'success'}>Connected</Badge>;
}
return <Badge variant={'destructive'}>Not connected</Badge>;
};
const renderIcon = () => {
if (isConnected) {
return (
@@ -61,9 +54,6 @@ const VerifyListener = ({ client, events: _events, onVerified }: Props) => {
<div className="flex items-center gap-2 text-2xl capitalize">
{client?.name}
</div>
<div className="mt-2 text-sm font-semibold text-muted-foreground">
Connection status: {renderBadge()}
</div>
<div
className={cn(
@@ -75,7 +65,7 @@ const VerifyListener = ({ client, events: _events, onVerified }: Props) => {
>
{renderIcon()}
<div className="flex-1">
<div className="text-lg font-semibold">
<div className="text-lg font-semibold leading-normal">
{isConnected ? 'Success' : 'Waiting for events'}
</div>
{isConnected ? (

View File

@@ -4,10 +4,24 @@ import { ButtonContainer } from '@/components/button-container';
import { LinkButton } from '@/components/ui/button';
import { cn } from '@/utils/cn';
import Link from 'next/link';
import { useState } from 'react';
import { useEffect, useState } from 'react';
import type { IServiceEvent, IServiceProjectWithClients } from '@openpanel/db';
import type {
IServiceClient,
IServiceEvent,
IServiceProjectWithClients,
} from '@openpanel/db';
import Syntax from '@/components/syntax';
import {
Accordion,
AccordionContent,
AccordionItem,
AccordionTrigger,
} from '@/components/ui/accordion';
import { useClientSecret } from '@/hooks/useClientSecret';
import { clipboard } from '@/utils/clipboard';
import { local } from 'd3';
import OnboardingLayout, {
OnboardingDescription,
} from '../../../onboarding-layout';
@@ -36,29 +50,15 @@ const Verify = ({ project, events }: Props) => {
</OnboardingDescription>
}
>
{/*
Sadly we cant have a verify for each type since we use the same client for all different types (website, app, backend)
Pros: the user just need to keep track of one client id/secret
Cons: we cant verify each type individually
Might be a good idea to add a verify for each type in the future, but for now we will just have one verify for all types
{project.types.map((type) => {
const Component = {
website: VerifyWeb,
app: VerifyApp,
backend: VerifyBackend,
}[type];
return <Component key={type} client={client} events={events} />;
})} */}
<VerifyListener
project={project}
client={client}
events={events}
onVerified={setVerified}
/>
<CurlPreview project={project} />
<ButtonContainer>
<LinkButton
href={`/onboarding/${project.id}/connect`}
@@ -80,7 +80,7 @@ const Verify = ({ project, events }: Props) => {
)}
<LinkButton
href="/"
href={`/${project.organizationId}/${project.id}`}
size="lg"
className={cn(
'min-w-28 self-start',
@@ -96,3 +96,48 @@ const Verify = ({ project, events }: Props) => {
};
export default Verify;
function CurlPreview({ project }: { project: IServiceProjectWithClients }) {
const [secret] = useClientSecret();
const client = project.clients[0];
if (!client) {
return null;
}
const code = `curl -X POST ${process.env.NEXT_PUBLIC_API_URL}/track \\
-H "Content-Type: application/json" \\
-H "openpanel-client-id: ${client.id}" \\
-H "openpanel-client-secret: ${secret}" \\
-H "User-Agent: ${window.navigator.userAgent}" \\
-d '{
"type": "track",
"payload": {
"name": "screen_view",
"properties": {
"__title": "Testing OpenPanel - ${project.name}",
"__path": "${project.domain}",
"__referrer": "${process.env.NEXT_PUBLIC_DASHBOARD_URL}"
}
}
}'`;
return (
<div className="card">
<Accordion type="single" collapsible>
<AccordionItem value="item-1">
<AccordionTrigger
className="px-6"
onClick={() => {
clipboard(code, null);
}}
>
Try out the curl command
</AccordionTrigger>
<AccordionContent className="p-0">
<Syntax code={code} />
</AccordionContent>
</AccordionItem>
</Accordion>
</div>
);
}

View File

@@ -3,11 +3,12 @@ import { escape } from 'sqlstring';
import {
TABLE_NAMES,
getCurrentOrganizations,
getEvents,
getOrganizations,
getProjectWithClients,
} from '@openpanel/db';
import { auth } from '@openpanel/auth/nextjs';
import OnboardingVerify from './onboarding-verify';
type Props = {
@@ -17,7 +18,8 @@ type Props = {
};
const Verify = async ({ params: { projectId } }: Props) => {
const orgs = await getCurrentOrganizations();
const { userId } = await auth();
const orgs = await getOrganizations(userId);
const organizationId = orgs[0]?.id;
if (!organizationId) {
throw new Error('No organization found');

View File

@@ -1,9 +1,78 @@
import { getCurrentOrganizations } from '@openpanel/db';
import { Or } from '@/components/auth/or';
import { SignInGithub } from '@/components/auth/sign-in-github';
import { SignInGoogle } from '@/components/auth/sign-in-google';
import { SignUpEmailForm } from '@/components/auth/sign-up-email-form';
import { auth } from '@openpanel/auth/nextjs';
import { getInviteById } from '@openpanel/db';
import Link from 'next/link';
import { redirect } from 'next/navigation';
import OnboardingLayout, { OnboardingDescription } from '../onboarding-layout';
import OnboardingTracking from './onboarding-tracking';
const Page = async ({
searchParams,
}: { searchParams: { inviteId: string } }) => {
const session = await auth();
const inviteId = await searchParams.inviteId;
const invite = inviteId ? await getInviteById(inviteId) : null;
const hasInviteExpired = invite?.expiresAt && invite.expiresAt < new Date();
if (session.userId) {
return redirect('/');
}
const Tracking = async () => {
return <OnboardingTracking organizations={await getCurrentOrganizations()} />;
return (
<div>
<OnboardingLayout
className="max-w-screen-sm"
title="Create an account"
description={
<OnboardingDescription>
Lets start with creating you account. By creating an account you
accept the{' '}
<Link target="_blank" href="https://openpanel.dev/terms">
Terms of Service
</Link>{' '}
and{' '}
<Link target="_blank" href="https://openpanel.dev/privacy">
Privacy Policy
</Link>
.
</OnboardingDescription>
}
>
{invite && !hasInviteExpired && (
<div className="card p-8 mb-8 col gap-2">
<h2 className="text-2xl font-medium">
Invitation to {invite.organization.name}
</h2>
<p>
After you have created your account, you will be added to the
organization.
</p>
</div>
)}
{invite && hasInviteExpired && (
<div className="card p-8 mb-8 col gap-2">
<h2 className="text-2xl font-medium">
Invitation to {invite.organization.name} has expired
</h2>
<p>
The invitation has expired. Please contact the organization owner
to get a new invitation.
</p>
</div>
)}
<div className="col md:row gap-4">
<SignInGithub type="sign-up" />
<SignInGoogle type="sign-up" />
</div>
<Or className="my-8" />
<div className="col gap-8 p-8 card">
<h2 className="text-2xl font-medium">Sign up with email</h2>
<SignUpEmailForm />
</div>
</OnboardingLayout>
</div>
);
};
export default Tracking;
export default Page;

View File

@@ -26,11 +26,13 @@ import type { z } from 'zod';
import type { IServiceOrganization } from '@openpanel/db';
import { zOnboardingProject } from '@openpanel/validation';
import OnboardingLayout, { OnboardingDescription } from '../onboarding-layout';
import OnboardingLayout, {
OnboardingDescription,
} from '../../onboarding-layout';
type IForm = z.infer<typeof zOnboardingProject>;
const Tracking = ({
export const OnboardingCreateProject = ({
organizations,
}: {
organizations: IServiceOrganization[];
@@ -260,5 +262,3 @@ const Tracking = ({
</form>
);
};
export default Tracking;

View File

@@ -0,0 +1,11 @@
import { auth } from '@openpanel/auth/nextjs';
import { getOrganizations } from '@openpanel/db';
import { OnboardingCreateProject } from './onboarding-create-project';
const Page = async () => {
const { userId } = await auth();
const organizations = await getOrganizations(userId);
return <OnboardingCreateProject organizations={organizations} />;
};
export default Page;

View File

@@ -1,22 +1,47 @@
'use client';
import { useLogout } from '@/hooks/useLogout';
import { showConfirm } from '@/modals';
import { api } from '@/trpc/client';
import { useAuth } from '@clerk/nextjs';
import { ChevronLastIcon } from 'lucide-react';
import { usePathname, useRouter } from 'next/navigation';
import { ChevronLastIcon, LogInIcon } from 'lucide-react';
import Link from 'next/link';
import {
usePathname,
useRouter,
useSelectedLayoutSegments,
} from 'next/navigation';
import { useEffect } from 'react';
const PUBLIC_SEGMENTS = [['onboarding']];
const SkipOnboarding = () => {
const router = useRouter();
const pathname = usePathname();
const res = api.onboarding.skipOnboardingCheck.useQuery();
const auth = useAuth();
const segments = useSelectedLayoutSegments();
const isPublic = PUBLIC_SEGMENTS.some((segment) =>
segments.every((s, index) => s === segment[index]),
);
const res = api.onboarding.skipOnboardingCheck.useQuery(undefined, {
enabled: !isPublic,
});
const logout = useLogout();
useEffect(() => {
res.refetch();
}, [pathname]);
if (!pathname.startsWith('/onboarding')) return null;
// Do not show skip onboarding for the first step (register account)
if (isPublic) {
return (
<Link
href="/login"
className="flex items-center gap-2 text-muted-foreground"
>
Login
<LogInIcon size={16} />
</Link>
);
}
return (
<button
@@ -29,8 +54,7 @@ const SkipOnboarding = () => {
title: 'Skip onboarding?',
text: 'Are you sure you want to skip onboarding? Since you do not have any projects, you will be logged out.',
onConfirm() {
auth.signOut();
router.replace(process.env.NEXT_PUBLIC_CLERK_SIGN_IN_URL!);
logout();
},
});
}

View File

@@ -17,15 +17,15 @@ type Props = {
function useSteps(path: string) {
const steps: Step[] = [
{
name: 'Account creation',
status: 'pending',
match: '/sign-up',
},
{
name: 'General',
name: 'Create an account',
status: 'pending',
match: '/onboarding',
},
{
name: 'Create a project',
status: 'pending',
match: '/onboarding/project',
},
{
name: 'Connect your data',
status: 'pending',
@@ -75,7 +75,7 @@ const Steps = ({ className }: Props) => {
{steps.map((step, index) => (
<div
className={cn(
'flex flex-shrink-0 items-center gap-2 self-start px-3 py-1.5',
'flex flex-shrink-0 items-center gap-4 self-start px-3 py-1.5',
step.status === 'current' &&
'rounded-xl border border-border bg-card',
step.status === 'completed' &&
@@ -108,7 +108,7 @@ const Steps = ({ className }: Props) => {
</div>
</div>
<div className=" font-medium">{step.name}</div>
<div className="font-medium">{step.name}</div>
</div>
))}
</div>