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:
committed by
Carl-Gerhard Lindesvärd
parent
f28802b1c2
commit
d31d9924a5
@@ -24,14 +24,14 @@ import { usePathname, useRouter } from 'next/navigation';
|
||||
import { useState } from 'react';
|
||||
|
||||
import type {
|
||||
getCurrentOrganizations,
|
||||
getOrganizations,
|
||||
getProjectsByOrganizationId,
|
||||
} from '@openpanel/db';
|
||||
import Link from 'next/link';
|
||||
|
||||
interface LayoutProjectSelectorProps {
|
||||
projects: Awaited<ReturnType<typeof getProjectsByOrganizationId>>;
|
||||
organizations?: Awaited<ReturnType<typeof getCurrentOrganizations>>;
|
||||
organizations?: Awaited<ReturnType<typeof getOrganizations>>;
|
||||
align?: 'start' | 'end';
|
||||
}
|
||||
export default function LayoutProjectSelector({
|
||||
|
||||
@@ -1,11 +1,12 @@
|
||||
import { FullPageEmptyState } from '@/components/full-page-empty-state';
|
||||
|
||||
import {
|
||||
getCurrentOrganizations,
|
||||
getCurrentProjects,
|
||||
getDashboardsByProjectId,
|
||||
getOrganizations,
|
||||
getProjects,
|
||||
} from '@openpanel/db';
|
||||
|
||||
import { auth } from '@openpanel/auth/nextjs';
|
||||
import LayoutContent from './layout-content';
|
||||
import { LayoutSidebar } from './layout-sidebar';
|
||||
import SideEffects from './side-effects';
|
||||
@@ -22,9 +23,10 @@ export default async function AppLayout({
|
||||
children,
|
||||
params: { organizationSlug: organizationId, projectId },
|
||||
}: AppLayoutProps) {
|
||||
const { userId } = await auth();
|
||||
const [organizations, projects, dashboards] = await Promise.all([
|
||||
getCurrentOrganizations(),
|
||||
getCurrentProjects(organizationId),
|
||||
getOrganizations(userId),
|
||||
getProjects({ organizationId, userId }),
|
||||
getDashboardsByProjectId(projectId),
|
||||
]);
|
||||
|
||||
|
||||
@@ -48,101 +48,137 @@ export default function CreateInvite({ projects }: Props) {
|
||||
|
||||
const mutation = api.organization.inviteUser.useMutation({
|
||||
onSuccess() {
|
||||
toast('User invited!', {
|
||||
description: 'The user has been invited to the organization.',
|
||||
});
|
||||
toast.success('User has been invited');
|
||||
reset();
|
||||
closeSheet();
|
||||
router.refresh();
|
||||
},
|
||||
onError() {
|
||||
toast.error('Failed to invite user');
|
||||
onError(error) {
|
||||
toast.error('Failed to invite user', {
|
||||
description: error.message,
|
||||
});
|
||||
},
|
||||
});
|
||||
|
||||
return (
|
||||
<Sheet>
|
||||
<Sheet onOpenChange={() => mutation.reset()}>
|
||||
<SheetTrigger asChild>
|
||||
<Button icon={PlusIcon}>Invite user</Button>
|
||||
</SheetTrigger>
|
||||
<SheetContent>
|
||||
<SheetHeader>
|
||||
<div>
|
||||
<SheetTitle>Invite a user</SheetTitle>
|
||||
<SheetDescription>
|
||||
Invite users to your organization. They will recieve an email will
|
||||
instructions.
|
||||
</SheetDescription>
|
||||
{mutation.isSuccess ? (
|
||||
<SheetContent>
|
||||
<SheetHeader>
|
||||
<SheetTitle>User has been invited</SheetTitle>
|
||||
</SheetHeader>
|
||||
<div className="prose">
|
||||
{mutation.data.type === 'is_member' ? (
|
||||
<>
|
||||
<p>
|
||||
Since the user already has an account we have added him/her to
|
||||
your organization. This means you will not see this user in
|
||||
the list of invites.
|
||||
</p>
|
||||
<p>We have also notified the user by email about this.</p>
|
||||
</>
|
||||
) : (
|
||||
<p>
|
||||
We have sent an email with instructions to join the
|
||||
organization.
|
||||
</p>
|
||||
)}
|
||||
<div className="row gap-4 mt-8">
|
||||
<Button onClick={() => mutation.reset()}>
|
||||
Invite another user
|
||||
</Button>
|
||||
<Button variant="outline" onClick={() => closeSheet()}>
|
||||
Close
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</SheetHeader>
|
||||
<form
|
||||
onSubmit={handleSubmit((values) => mutation.mutate(values))}
|
||||
className="flex flex-col gap-8"
|
||||
>
|
||||
<InputWithLabel
|
||||
className="w-full max-w-sm"
|
||||
label="Email"
|
||||
error={formState.errors.email?.message}
|
||||
placeholder="Who do you want to invite?"
|
||||
{...register('email')}
|
||||
/>
|
||||
<div>
|
||||
<Label>What role?</Label>
|
||||
</SheetContent>
|
||||
) : (
|
||||
<SheetContent>
|
||||
<SheetHeader>
|
||||
<div>
|
||||
<SheetTitle>Invite a user</SheetTitle>
|
||||
<SheetDescription>
|
||||
Invite users to your organization. They will recieve an email
|
||||
will instructions.
|
||||
</SheetDescription>
|
||||
</div>
|
||||
</SheetHeader>
|
||||
<form
|
||||
onSubmit={handleSubmit((values) => mutation.mutate(values))}
|
||||
className="flex flex-col gap-8"
|
||||
>
|
||||
<InputWithLabel
|
||||
className="w-full max-w-sm"
|
||||
label="Email"
|
||||
error={formState.errors.email?.message}
|
||||
placeholder="Who do you want to invite?"
|
||||
{...register('email')}
|
||||
/>
|
||||
<div>
|
||||
<Label>What role?</Label>
|
||||
<Controller
|
||||
name="role"
|
||||
control={control}
|
||||
render={({ field }) => (
|
||||
<RadioGroup
|
||||
defaultValue={field.value}
|
||||
onChange={field.onChange}
|
||||
ref={field.ref}
|
||||
onBlur={field.onBlur}
|
||||
className="flex gap-4"
|
||||
>
|
||||
<div className="flex items-center gap-2">
|
||||
<RadioGroupItem value="org:member" id="member" />
|
||||
<Label className="mb-0" htmlFor="member">
|
||||
Member
|
||||
</Label>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<RadioGroupItem value="org:admin" id="admin" />
|
||||
<Label className="mb-0" htmlFor="admin">
|
||||
Admin
|
||||
</Label>
|
||||
</div>
|
||||
</RadioGroup>
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
<Controller
|
||||
name="role"
|
||||
name="access"
|
||||
control={control}
|
||||
render={({ field }) => (
|
||||
<RadioGroup
|
||||
defaultValue={field.value}
|
||||
onChange={field.onChange}
|
||||
ref={field.ref}
|
||||
onBlur={field.onBlur}
|
||||
className="flex gap-4"
|
||||
>
|
||||
<div className="flex items-center gap-2">
|
||||
<RadioGroupItem value="org:member" id="member" />
|
||||
<Label className="mb-0" htmlFor="member">
|
||||
Member
|
||||
</Label>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<RadioGroupItem value="org:admin" id="admin" />
|
||||
<Label className="mb-0" htmlFor="admin">
|
||||
Admin
|
||||
</Label>
|
||||
</div>
|
||||
</RadioGroup>
|
||||
<div>
|
||||
<Label>Restrict access</Label>
|
||||
<ComboboxAdvanced
|
||||
placeholder="Restrict access to projects"
|
||||
value={field.value}
|
||||
onChange={field.onChange}
|
||||
items={projects.map((item) => ({
|
||||
label: item.name,
|
||||
value: item.id,
|
||||
}))}
|
||||
/>
|
||||
<p className="mt-1 text-sm text-muted-foreground">
|
||||
Leave empty to give access to all projects
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
<Controller
|
||||
name="access"
|
||||
control={control}
|
||||
render={({ field }) => (
|
||||
<div>
|
||||
<Label>Restrict access</Label>
|
||||
<ComboboxAdvanced
|
||||
placeholder="Restrict access to projects"
|
||||
value={field.value}
|
||||
onChange={field.onChange}
|
||||
items={projects.map((item) => ({
|
||||
label: item.name,
|
||||
value: item.id,
|
||||
}))}
|
||||
/>
|
||||
<p className="mt-1 text-sm text-muted-foreground">
|
||||
Leave empty to give access to all projects
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
/>
|
||||
<SheetFooter>
|
||||
<Button icon={SendIcon} type="submit" loading={mutation.isLoading}>
|
||||
Invite user
|
||||
</Button>
|
||||
</SheetFooter>
|
||||
</form>
|
||||
</SheetContent>
|
||||
<SheetFooter>
|
||||
<Button
|
||||
icon={SendIcon}
|
||||
type="submit"
|
||||
loading={mutation.isLoading}
|
||||
>
|
||||
Invite user
|
||||
</Button>
|
||||
</SheetFooter>
|
||||
</form>
|
||||
</SheetContent>
|
||||
)}
|
||||
</Sheet>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,11 +1,11 @@
|
||||
import { FullPageEmptyState } from '@/components/full-page-empty-state';
|
||||
import { PageTabs, PageTabsLink } from '@/components/page-tabs';
|
||||
import { Padding } from '@/components/ui/padding';
|
||||
import { auth } from '@clerk/nextjs/server';
|
||||
import { ShieldAlertIcon } from 'lucide-react';
|
||||
import { notFound } from 'next/navigation';
|
||||
import { parseAsStringEnum } from 'nuqs/server';
|
||||
|
||||
import { auth } from '@openpanel/auth/nextjs';
|
||||
import { db } from '@openpanel/db';
|
||||
|
||||
import EditOrganization from './edit-organization';
|
||||
@@ -26,7 +26,7 @@ export default async function Page({
|
||||
const tab = parseAsStringEnum(['org', 'members', 'invites'])
|
||||
.withDefault('org')
|
||||
.parseServerSide(searchParams.tab);
|
||||
const session = auth();
|
||||
const session = await auth();
|
||||
const organization = await db.organization.findUnique({
|
||||
where: {
|
||||
id: organizationId,
|
||||
|
||||
@@ -1,12 +1,11 @@
|
||||
import { Padding } from '@/components/ui/padding';
|
||||
import { auth } from '@clerk/nextjs/server';
|
||||
|
||||
import { auth } from '@openpanel/auth/nextjs';
|
||||
import { getUserById } from '@openpanel/db';
|
||||
|
||||
import EditProfile from './edit-profile';
|
||||
|
||||
export default async function Page() {
|
||||
const { userId } = auth();
|
||||
const { userId } = await auth();
|
||||
const profile = await getUserById(userId!);
|
||||
|
||||
return (
|
||||
|
||||
@@ -1,39 +1,11 @@
|
||||
'use client';
|
||||
|
||||
import { pushModal, useOnPushModal } from '@/modals';
|
||||
import { useUser } from '@clerk/nextjs';
|
||||
import { differenceInDays } from 'date-fns';
|
||||
import { useEffect } from 'react';
|
||||
|
||||
import { useOpenPanel } from '@openpanel/nextjs';
|
||||
|
||||
export default function SideEffects() {
|
||||
const op = useOpenPanel();
|
||||
const { user } = useUser();
|
||||
const accountAgeInDays = differenceInDays(
|
||||
new Date(),
|
||||
user?.createdAt || new Date(),
|
||||
);
|
||||
useOnPushModal('Testimonial', (open) => {
|
||||
if (!open) {
|
||||
user?.update({
|
||||
unsafeMetadata: {
|
||||
...user.unsafeMetadata,
|
||||
testimonial: new Date().toISOString(),
|
||||
},
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
const showTestimonial =
|
||||
user && !user.unsafeMetadata.testimonial && accountAgeInDays > 7;
|
||||
|
||||
useEffect(() => {
|
||||
if (showTestimonial) {
|
||||
pushModal('Testimonial');
|
||||
op.track('testimonials_shown');
|
||||
}
|
||||
}, [showTestimonial]);
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
@@ -4,7 +4,8 @@ import ProjectCard from '@/components/projects/project-card';
|
||||
import { redirect } from 'next/navigation';
|
||||
|
||||
import SettingsToggle from '@/components/settings-toggle';
|
||||
import { getCurrentOrganizations, getCurrentProjects } from '@openpanel/db';
|
||||
import { auth } from '@openpanel/auth/nextjs';
|
||||
import { getOrganizations, getProjects } from '@openpanel/db';
|
||||
import LayoutProjectSelector from './[projectId]/layout-project-selector';
|
||||
|
||||
interface PageProps {
|
||||
@@ -16,9 +17,10 @@ interface PageProps {
|
||||
export default async function Page({
|
||||
params: { organizationSlug: organizationId },
|
||||
}: PageProps) {
|
||||
const { userId } = await auth();
|
||||
const [organizations, projects] = await Promise.all([
|
||||
getCurrentOrganizations(),
|
||||
getCurrentProjects(organizationId),
|
||||
getOrganizations(userId),
|
||||
getProjects({ organizationId, userId }),
|
||||
]);
|
||||
|
||||
const organization = organizations.find((org) => org.id === organizationId);
|
||||
@@ -32,7 +34,7 @@ export default async function Page({
|
||||
}
|
||||
|
||||
if (projects.length === 0) {
|
||||
return redirect('/onboarding');
|
||||
return redirect('/onboarding/project');
|
||||
}
|
||||
|
||||
if (projects.length === 1 && projects[0]) {
|
||||
|
||||
@@ -1,13 +1,15 @@
|
||||
import { redirect } from 'next/navigation';
|
||||
|
||||
import { getCurrentOrganizations } from '@openpanel/db';
|
||||
import { auth } from '@openpanel/auth/nextjs';
|
||||
import { getOrganizations } from '@openpanel/db';
|
||||
|
||||
export default async function Page() {
|
||||
const organizations = await getCurrentOrganizations();
|
||||
const { userId } = await auth();
|
||||
const organizations = await getOrganizations(userId);
|
||||
|
||||
if (organizations.length > 0) {
|
||||
return redirect(`/${organizations[0]?.id}`);
|
||||
}
|
||||
|
||||
return redirect('/onboarding');
|
||||
return redirect('/onboarding/project');
|
||||
}
|
||||
|
||||
@@ -12,7 +12,7 @@ const Page = ({ children }: Props) => {
|
||||
<div className="min-h-screen border-r border-r-background bg-gradient-to-r from-background to-def-200 max-md:hidden">
|
||||
<LiveEventsServer />
|
||||
</div>
|
||||
<div className="min-h-screen">{children}</div>
|
||||
<div className="min-h-screen p-4">{children}</div>
|
||||
</div>
|
||||
</div>
|
||||
</>
|
||||
|
||||
@@ -102,7 +102,7 @@ const useWebEventGenerator = () => {
|
||||
function createNewEvent() {
|
||||
const newEvent = generateEvent();
|
||||
setEvents((prevEvents) => [newEvent, ...prevEvents]);
|
||||
timer = setTimeout(() => createNewEvent(), Math.random() * 1000);
|
||||
timer = setTimeout(() => createNewEvent(), Math.random() * 3000);
|
||||
}
|
||||
|
||||
createNewEvent();
|
||||
|
||||
@@ -1,9 +0,0 @@
|
||||
import { SignIn } from '@clerk/nextjs';
|
||||
|
||||
export default function Page() {
|
||||
return (
|
||||
<div className="flex min-h-screen items-center justify-center p-4">
|
||||
<SignIn signUpUrl="/register" />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
33
apps/dashboard/src/app/(auth)/login/page.tsx
Normal file
33
apps/dashboard/src/app/(auth)/login/page.tsx
Normal file
@@ -0,0 +1,33 @@
|
||||
import { Or } from '@/components/auth/or';
|
||||
import { SignInEmailForm } from '@/components/auth/sign-in-email-form';
|
||||
import { SignInGithub } from '@/components/auth/sign-in-github';
|
||||
import { SignInGoogle } from '@/components/auth/sign-in-google';
|
||||
import { LinkButton } from '@/components/ui/button';
|
||||
import { auth } from '@openpanel/auth/nextjs';
|
||||
import { redirect } from 'next/navigation';
|
||||
|
||||
export default async function Page() {
|
||||
const session = await auth();
|
||||
|
||||
if (session.userId) {
|
||||
return redirect('/');
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="flex h-full center-center w-full">
|
||||
<div className="col gap-8 max-w-md w-full">
|
||||
<div className="col md:row gap-4">
|
||||
<SignInGithub type="sign-in" />
|
||||
<SignInGoogle type="sign-in" />
|
||||
</div>
|
||||
<Or />
|
||||
<div className="card p-8">
|
||||
<SignInEmailForm />
|
||||
</div>
|
||||
<LinkButton variant={'outline'} size="lg" href="/onboarding">
|
||||
No account? Sign up today
|
||||
</LinkButton>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,9 +0,0 @@
|
||||
import { SignUp } from '@clerk/nextjs';
|
||||
|
||||
export default function Page() {
|
||||
return (
|
||||
<div className="flex min-h-screen items-center justify-center p-4">
|
||||
<SignUp signInUrl="/login" />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
17
apps/dashboard/src/app/(auth)/reset-password/page.tsx
Normal file
17
apps/dashboard/src/app/(auth)/reset-password/page.tsx
Normal file
@@ -0,0 +1,17 @@
|
||||
import { ResetPasswordForm } from '@/components/auth/reset-password-form';
|
||||
import { auth } from '@openpanel/auth/nextjs';
|
||||
import { redirect } from 'next/navigation';
|
||||
|
||||
export default async function Page() {
|
||||
const session = await auth();
|
||||
|
||||
if (session.userId) {
|
||||
return redirect('/');
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="flex h-full center-center">
|
||||
<ResetPasswordForm />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,9 +0,0 @@
|
||||
import { AuthenticateWithRedirectCallback } from '@clerk/nextjs';
|
||||
|
||||
export const dynamic = 'force-dynamic';
|
||||
|
||||
const SSOCallback = () => {
|
||||
return <AuthenticateWithRedirectCallback />;
|
||||
};
|
||||
|
||||
export default SSOCallback;
|
||||
@@ -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>
|
||||
);
|
||||
|
||||
@@ -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');
|
||||
|
||||
@@ -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 ? (
|
||||
|
||||
@@ -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>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -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');
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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;
|
||||
@@ -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;
|
||||
@@ -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();
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
@@ -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>
|
||||
|
||||
@@ -1,122 +0,0 @@
|
||||
import type { WebhookEvent } from '@clerk/nextjs/server';
|
||||
import { pathOr } from 'ramda';
|
||||
|
||||
import { AccessLevel, db } from '@openpanel/db';
|
||||
|
||||
export const dynamic = 'force-dynamic';
|
||||
|
||||
export async function POST(request: Request) {
|
||||
const payload: WebhookEvent = await request.json();
|
||||
|
||||
if (payload.type === 'user.created') {
|
||||
const email = payload.data.email_addresses[0]?.email_address;
|
||||
const emails = payload.data.email_addresses.map((e) => e.email_address);
|
||||
|
||||
if (!email) {
|
||||
return Response.json(
|
||||
{ message: 'No email address found' },
|
||||
{ status: 400 },
|
||||
);
|
||||
}
|
||||
|
||||
const user = await db.user.create({
|
||||
data: {
|
||||
id: payload.data.id,
|
||||
email,
|
||||
firstName: payload.data.first_name,
|
||||
lastName: payload.data.last_name,
|
||||
},
|
||||
});
|
||||
|
||||
const memberships = await db.member.findMany({
|
||||
where: {
|
||||
email: {
|
||||
in: emails,
|
||||
},
|
||||
userId: null,
|
||||
},
|
||||
});
|
||||
|
||||
for (const membership of memberships) {
|
||||
const access = pathOr<string[]>([], ['meta', 'access'], membership);
|
||||
await db.$transaction([
|
||||
// Update the member to link it to the user
|
||||
// This will remove the item from invitations
|
||||
db.member.update({
|
||||
where: {
|
||||
id: membership.id,
|
||||
},
|
||||
data: {
|
||||
userId: user.id,
|
||||
},
|
||||
}),
|
||||
db.projectAccess.createMany({
|
||||
data: access
|
||||
.filter((a) => typeof a === 'string')
|
||||
.map((projectId) => ({
|
||||
organizationId: membership.organizationId,
|
||||
projectId: projectId,
|
||||
userId: user.id,
|
||||
level: AccessLevel.read,
|
||||
})),
|
||||
}),
|
||||
]);
|
||||
}
|
||||
}
|
||||
|
||||
if (payload.type === 'organizationMembership.created') {
|
||||
const access = payload.data.public_metadata.access;
|
||||
if (Array.isArray(access)) {
|
||||
await db.projectAccess.createMany({
|
||||
data: access
|
||||
.filter((a): a is string => typeof a === 'string')
|
||||
.map((projectId) => ({
|
||||
organizationId: payload.data.organization.slug,
|
||||
projectId: projectId,
|
||||
userId: payload.data.public_user_data.user_id,
|
||||
level: AccessLevel.read,
|
||||
})),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
if (payload.type === 'user.deleted') {
|
||||
await db.$transaction([
|
||||
db.user.update({
|
||||
where: {
|
||||
id: payload.data.id,
|
||||
},
|
||||
data: {
|
||||
deletedAt: new Date(),
|
||||
firstName: null,
|
||||
lastName: null,
|
||||
},
|
||||
}),
|
||||
db.projectAccess.deleteMany({
|
||||
where: {
|
||||
userId: payload.data.id,
|
||||
},
|
||||
}),
|
||||
db.member.deleteMany({
|
||||
where: {
|
||||
userId: payload.data.id,
|
||||
},
|
||||
}),
|
||||
]);
|
||||
}
|
||||
|
||||
if (payload.type === 'organizationMembership.deleted') {
|
||||
await db.projectAccess.deleteMany({
|
||||
where: {
|
||||
organizationId: payload.data.organization.slug,
|
||||
userId: payload.data.public_user_data.user_id,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
return Response.json({ message: 'Webhook received!' });
|
||||
}
|
||||
|
||||
export function GET() {
|
||||
return Response.json({ message: 'Hello World!' });
|
||||
}
|
||||
@@ -29,7 +29,7 @@ export default function RootLayout({
|
||||
<html lang="en" suppressHydrationWarning>
|
||||
<body
|
||||
className={cn(
|
||||
'grainy min-h-screen bg-def-100 font-sans text-base antialiased',
|
||||
'grainy min-h-screen bg-def-100 font-sans text-base antialiased leading-normal',
|
||||
GeistSans.variable,
|
||||
GeistMono.variable,
|
||||
)}
|
||||
|
||||
@@ -6,7 +6,6 @@ import { ModalProvider } from '@/modals';
|
||||
import type { AppStore } from '@/redux';
|
||||
import makeStore from '@/redux';
|
||||
import { api } from '@/trpc/client';
|
||||
import { ClerkProvider, useAuth } from '@clerk/nextjs';
|
||||
import { OpenPanelComponent } from '@openpanel/nextjs';
|
||||
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
|
||||
import { httpLink } from '@trpc/client';
|
||||
@@ -18,7 +17,6 @@ import { Toaster } from 'sonner';
|
||||
import superjson from 'superjson';
|
||||
|
||||
function AllProviders({ children }: { children: React.ReactNode }) {
|
||||
const { getToken } = useAuth();
|
||||
const [queryClient] = useState(
|
||||
() =>
|
||||
new QueryClient({
|
||||
@@ -44,15 +42,6 @@ function AllProviders({ children }: { children: React.ReactNode }) {
|
||||
mode: 'cors',
|
||||
});
|
||||
},
|
||||
async headers() {
|
||||
const token = await getToken();
|
||||
if (token) {
|
||||
return {
|
||||
Authorization: `Bearer ${token}`,
|
||||
};
|
||||
}
|
||||
return {};
|
||||
},
|
||||
}),
|
||||
],
|
||||
}),
|
||||
@@ -97,9 +86,5 @@ function AllProviders({ children }: { children: React.ReactNode }) {
|
||||
}
|
||||
|
||||
export default function Providers({ children }: { children: React.ReactNode }) {
|
||||
return (
|
||||
<ClerkProvider>
|
||||
<AllProviders>{children}</AllProviders>
|
||||
</ClerkProvider>
|
||||
);
|
||||
return <AllProviders>{children}</AllProviders>;
|
||||
}
|
||||
|
||||
11
apps/dashboard/src/components/auth/or.tsx
Normal file
11
apps/dashboard/src/components/auth/or.tsx
Normal file
@@ -0,0 +1,11 @@
|
||||
import { cn } from '@/utils/cn';
|
||||
|
||||
export function Or({ className }: { className?: string }) {
|
||||
return (
|
||||
<div className={cn('row items-center gap-2', className)}>
|
||||
<div className="h-px w-full bg-border" />
|
||||
<span className="text-muted-foreground">OR</span>
|
||||
<div className="h-px w-full bg-border" />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
57
apps/dashboard/src/components/auth/reset-password-form.tsx
Normal file
57
apps/dashboard/src/components/auth/reset-password-form.tsx
Normal file
@@ -0,0 +1,57 @@
|
||||
'use client';
|
||||
|
||||
import { InputWithLabel } from '@/components/forms/input-with-label';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { api } from '@/trpc/client';
|
||||
import { zodResolver } from '@hookform/resolvers/zod';
|
||||
import { zResetPassword } from '@openpanel/validation';
|
||||
import { useRouter, useSearchParams } from 'next/navigation';
|
||||
import { useForm } from 'react-hook-form';
|
||||
import { toast } from 'sonner';
|
||||
import type { z } from 'zod';
|
||||
|
||||
const validator = zResetPassword;
|
||||
type IForm = z.infer<typeof validator>;
|
||||
|
||||
export function ResetPasswordForm() {
|
||||
const searchParams = useSearchParams();
|
||||
const token = searchParams.get('token') ?? null;
|
||||
const router = useRouter();
|
||||
const mutation = api.auth.resetPassword.useMutation({
|
||||
onSuccess() {
|
||||
toast.success('Password reset successfully', {
|
||||
description: 'You can now login with your new password',
|
||||
});
|
||||
router.push('/login');
|
||||
},
|
||||
onError(error) {
|
||||
toast.error(error.message);
|
||||
},
|
||||
});
|
||||
|
||||
const form = useForm<IForm>({
|
||||
resolver: zodResolver(validator),
|
||||
defaultValues: {
|
||||
token: token ?? '',
|
||||
password: '',
|
||||
},
|
||||
});
|
||||
|
||||
const onSubmit = form.handleSubmit(async (data) => {
|
||||
mutation.mutate(data);
|
||||
});
|
||||
|
||||
return (
|
||||
<div className="col gap-8">
|
||||
<form onSubmit={onSubmit}>
|
||||
<InputWithLabel
|
||||
label="New password"
|
||||
placeholder="New password"
|
||||
type="password"
|
||||
{...form.register('password')}
|
||||
/>
|
||||
<Button type="submit">Reset password</Button>
|
||||
</form>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
67
apps/dashboard/src/components/auth/sign-in-email-form.tsx
Normal file
67
apps/dashboard/src/components/auth/sign-in-email-form.tsx
Normal file
@@ -0,0 +1,67 @@
|
||||
'use client';
|
||||
import { pushModal } from '@/modals';
|
||||
import { api } from '@/trpc/client';
|
||||
import { zodResolver } from '@hookform/resolvers/zod';
|
||||
import { zSignInEmail } from '@openpanel/validation';
|
||||
import { useRouter } from 'next/navigation';
|
||||
import { type SubmitHandler, useForm } from 'react-hook-form';
|
||||
import { toast } from 'sonner';
|
||||
import type { z } from 'zod';
|
||||
import { InputWithLabel } from '../forms/input-with-label';
|
||||
import { Button } from '../ui/button';
|
||||
|
||||
const validator = zSignInEmail;
|
||||
type IForm = z.infer<typeof validator>;
|
||||
|
||||
export function SignInEmailForm() {
|
||||
const router = useRouter();
|
||||
const mutation = api.auth.signInEmail.useMutation({
|
||||
onSuccess(res) {
|
||||
toast.success('Successfully signed in');
|
||||
router.push('/');
|
||||
},
|
||||
onError(error) {
|
||||
toast.error(error.message);
|
||||
},
|
||||
});
|
||||
const form = useForm<IForm>({
|
||||
resolver: zodResolver(validator),
|
||||
});
|
||||
const onSubmit: SubmitHandler<IForm> = (values) => {
|
||||
mutation.mutate({
|
||||
...values,
|
||||
});
|
||||
};
|
||||
|
||||
return (
|
||||
<form
|
||||
onSubmit={form.handleSubmit(onSubmit, (err) => console.log(err))}
|
||||
className="col gap-6"
|
||||
>
|
||||
<h3 className="text-2xl font-medium text-left">Sign in with email</h3>
|
||||
<InputWithLabel
|
||||
{...form.register('email')}
|
||||
error={form.formState.errors.email?.message}
|
||||
label="Email"
|
||||
/>
|
||||
<InputWithLabel
|
||||
{...form.register('password')}
|
||||
error={form.formState.errors.password?.message}
|
||||
label="Password"
|
||||
type="password"
|
||||
/>
|
||||
<Button type="submit">Sign in</Button>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() =>
|
||||
pushModal('RequestPasswordReset', {
|
||||
email: form.getValues('email'),
|
||||
})
|
||||
}
|
||||
className="text-sm text-muted-foreground hover:underline"
|
||||
>
|
||||
Forgot password?
|
||||
</button>
|
||||
</form>
|
||||
);
|
||||
}
|
||||
45
apps/dashboard/src/components/auth/sign-in-github.tsx
Normal file
45
apps/dashboard/src/components/auth/sign-in-github.tsx
Normal file
@@ -0,0 +1,45 @@
|
||||
'use client';
|
||||
|
||||
import { api } from '@/trpc/client';
|
||||
import { useSearchParams } from 'next/navigation';
|
||||
import { Button } from '../ui/button';
|
||||
|
||||
export function SignInGithub({ type }: { type: 'sign-in' | 'sign-up' }) {
|
||||
const searchParams = useSearchParams();
|
||||
const inviteId = searchParams.get('inviteId');
|
||||
const mutation = api.auth.signInOAuth.useMutation({
|
||||
onSuccess(res) {
|
||||
if (res.url) {
|
||||
window.location.href = res.url;
|
||||
}
|
||||
},
|
||||
});
|
||||
const title = () => {
|
||||
if (type === 'sign-in') return 'Sign in with Github';
|
||||
if (type === 'sign-up') return 'Sign up with Github';
|
||||
};
|
||||
return (
|
||||
<Button
|
||||
className="md:flex-1"
|
||||
size="lg"
|
||||
onClick={() =>
|
||||
mutation.mutate({
|
||||
provider: 'github',
|
||||
inviteId: type === 'sign-up' ? inviteId : undefined,
|
||||
})
|
||||
}
|
||||
>
|
||||
<svg
|
||||
className="size-4 mr-2"
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
width="24"
|
||||
height="24"
|
||||
viewBox="0 0 24 24"
|
||||
fill="currentColor"
|
||||
>
|
||||
<path d="M12 0c-6.626 0-12 5.373-12 12 0 5.302 3.438 9.8 8.207 11.387.599.111.793-.261.793-.577v-2.234c-3.338.726-4.033-1.416-4.033-1.416-.546-1.387-1.333-1.756-1.333-1.756-1.089-.745.083-.729.083-.729 1.205.084 1.839 1.237 1.839 1.237 1.07 1.834 2.807 1.304 3.492.997.107-.775.418-1.305.762-1.604-2.665-.305-5.467-1.334-5.467-5.931 0-1.311.469-2.381 1.236-3.221-.124-.303-.535-1.524.117-3.176 0 0 1.008-.322 3.301 1.23.957-.266 1.983-.399 3.003-.404 1.02.005 2.047.138 3.006.404 2.291-1.552 3.297-1.23 3.297-1.23.653 1.653.242 2.874.118 3.176.77.84 1.235 1.911 1.235 3.221 0 4.609-2.807 5.624-5.479 5.921.43.372.823 1.102.823 2.222v3.293c0 .319.192.694.801.576 4.765-1.589 8.199-6.086 8.199-11.386 0-6.627-5.373-12-12-12z" />
|
||||
</svg>
|
||||
{title()}
|
||||
</Button>
|
||||
);
|
||||
}
|
||||
57
apps/dashboard/src/components/auth/sign-in-google.tsx
Normal file
57
apps/dashboard/src/components/auth/sign-in-google.tsx
Normal file
@@ -0,0 +1,57 @@
|
||||
'use client';
|
||||
|
||||
import { api } from '@/trpc/client';
|
||||
import { useSearchParams } from 'next/navigation';
|
||||
import { Button } from '../ui/button';
|
||||
|
||||
export function SignInGoogle({ type }: { type: 'sign-in' | 'sign-up' }) {
|
||||
const searchParams = useSearchParams();
|
||||
const inviteId = searchParams.get('inviteId');
|
||||
const mutation = api.auth.signInOAuth.useMutation({
|
||||
onSuccess(res) {
|
||||
if (res.url) {
|
||||
window.location.href = res.url;
|
||||
}
|
||||
},
|
||||
});
|
||||
const title = () => {
|
||||
if (type === 'sign-in') return 'Sign in with Google';
|
||||
if (type === 'sign-up') return 'Sign up with Google';
|
||||
};
|
||||
return (
|
||||
<Button
|
||||
className="md:flex-1"
|
||||
size="lg"
|
||||
onClick={() =>
|
||||
mutation.mutate({
|
||||
provider: 'google',
|
||||
inviteId: type === 'sign-up' ? inviteId : undefined,
|
||||
})
|
||||
}
|
||||
>
|
||||
<svg
|
||||
className="size-4 mr-2"
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
viewBox="0 0 24 24"
|
||||
>
|
||||
<path
|
||||
fill="#4285F4"
|
||||
d="M22.56 12.25c0-.78-.07-1.53-.2-2.25H12v4.26h5.92c-.26 1.37-1.04 2.53-2.21 3.31v2.77h3.57c2.08-1.92 3.28-4.74 3.28-8.09z"
|
||||
/>
|
||||
<path
|
||||
fill="#34A853"
|
||||
d="M12 23c2.97 0 5.46-.98 7.28-2.66l-3.57-2.77c-.98.66-2.23 1.06-3.71 1.06-2.86 0-5.29-1.93-6.16-4.53H2.18v2.84C3.99 20.53 7.7 23 12 23z"
|
||||
/>
|
||||
<path
|
||||
fill="#FBBC05"
|
||||
d="M5.84 14.09c-.22-.66-.35-1.36-.35-2.09s.13-1.43.35-2.09V7.07H2.18C1.43 8.55 1 10.22 1 12s.43 3.45 1.18 4.93l2.85-2.22.81-.62z"
|
||||
/>
|
||||
<path
|
||||
fill="#EA4335"
|
||||
d="M12 5.38c1.62 0 3.06.56 4.21 1.64l3.15-3.15C17.45 2.09 14.97 1 12 1 7.7 1 3.99 3.47 2.18 7.07l3.66 2.84c.87-2.6 3.3-4.53 6.16-4.53z"
|
||||
/>
|
||||
</svg>
|
||||
{title()}
|
||||
</Button>
|
||||
);
|
||||
}
|
||||
83
apps/dashboard/src/components/auth/sign-up-email-form.tsx
Normal file
83
apps/dashboard/src/components/auth/sign-up-email-form.tsx
Normal file
@@ -0,0 +1,83 @@
|
||||
'use client';
|
||||
|
||||
import { api } from '@/trpc/client';
|
||||
import { zodResolver } from '@hookform/resolvers/zod';
|
||||
import { zSignUpEmail } from '@openpanel/validation';
|
||||
import { useRouter, useSearchParams } from 'next/navigation';
|
||||
import { type SubmitHandler, useForm } from 'react-hook-form';
|
||||
import { toast } from 'sonner';
|
||||
import type { z } from 'zod';
|
||||
import { InputWithLabel } from '../forms/input-with-label';
|
||||
import { Button } from '../ui/button';
|
||||
|
||||
const validator = zSignUpEmail;
|
||||
type IForm = z.infer<typeof validator>;
|
||||
|
||||
export function SignUpEmailForm() {
|
||||
const router = useRouter();
|
||||
const searchParams = useSearchParams();
|
||||
const mutation = api.auth.signUpEmail.useMutation({
|
||||
onSuccess(res) {
|
||||
toast.success('Successfully signed up');
|
||||
router.push('/');
|
||||
},
|
||||
});
|
||||
const form = useForm<IForm>({
|
||||
resolver: zodResolver(validator),
|
||||
});
|
||||
const onSubmit: SubmitHandler<IForm> = (values) => {
|
||||
mutation.mutate({
|
||||
...values,
|
||||
inviteId: searchParams.get('inviteId'),
|
||||
});
|
||||
};
|
||||
return (
|
||||
<form className="col gap-8" onSubmit={form.handleSubmit(onSubmit)}>
|
||||
<div className="row gap-8 w-full flex-1">
|
||||
<InputWithLabel
|
||||
label="First name"
|
||||
className="flex-1"
|
||||
type="text"
|
||||
{...form.register('firstName')}
|
||||
error={form.formState.errors.firstName?.message}
|
||||
/>
|
||||
<InputWithLabel
|
||||
label="Last name"
|
||||
className="flex-1"
|
||||
type="text"
|
||||
{...form.register('lastName')}
|
||||
error={form.formState.errors.lastName?.message}
|
||||
/>
|
||||
</div>
|
||||
<InputWithLabel
|
||||
label="Email"
|
||||
className="w-full"
|
||||
type="email"
|
||||
{...form.register('email')}
|
||||
error={form.formState.errors.email?.message}
|
||||
/>
|
||||
<div className="row gap-8 w-full">
|
||||
<InputWithLabel
|
||||
label="Password"
|
||||
className="flex-1"
|
||||
type="password"
|
||||
{...form.register('password')}
|
||||
error={form.formState.errors.password?.message}
|
||||
/>
|
||||
<InputWithLabel
|
||||
label="Confirm password"
|
||||
className="flex-1"
|
||||
type="password"
|
||||
{...form.register('confirmPassword')}
|
||||
error={form.formState.errors.confirmPassword?.message}
|
||||
/>
|
||||
</div>
|
||||
<div className="grid grid-cols-2 gap-8">
|
||||
<div />
|
||||
<Button type="submit" className="w-full" size="lg">
|
||||
Create account
|
||||
</Button>
|
||||
</div>
|
||||
</form>
|
||||
);
|
||||
}
|
||||
@@ -37,8 +37,13 @@ export const WithLabel = ({
|
||||
)}
|
||||
</Label>
|
||||
{error && (
|
||||
<Tooltiper asChild content={error}>
|
||||
<div className="flex items-center gap-1 leading-none text-destructive">
|
||||
<Tooltiper
|
||||
asChild
|
||||
content={error}
|
||||
tooltipClassName="max-w-80 leading-normal"
|
||||
align="end"
|
||||
>
|
||||
<div className="flex items-center gap-1 leading-none text-destructive">
|
||||
Issues
|
||||
<BanIcon size={14} />
|
||||
</div>
|
||||
|
||||
@@ -18,7 +18,9 @@ import { useTheme } from 'next-themes';
|
||||
import * as React from 'react';
|
||||
|
||||
import { useAppParams } from '@/hooks/useAppParams';
|
||||
import { useAuth } from '@clerk/nextjs';
|
||||
import { useLogout } from '@/hooks/useLogout';
|
||||
import { api } from '@/trpc/client';
|
||||
import { useRouter } from 'next/navigation';
|
||||
import { ProjectLink } from './links';
|
||||
|
||||
interface Props {
|
||||
@@ -26,9 +28,10 @@ interface Props {
|
||||
}
|
||||
|
||||
export default function SettingsToggle({ className }: Props) {
|
||||
const router = useRouter();
|
||||
const { setTheme, theme } = useTheme();
|
||||
const { projectId } = useAppParams();
|
||||
const auth = useAuth();
|
||||
const logout = useLogout();
|
||||
|
||||
return (
|
||||
<DropdownMenu>
|
||||
@@ -101,12 +104,7 @@ export default function SettingsToggle({ className }: Props) {
|
||||
</DropdownMenuSubContent>
|
||||
</DropdownMenuSub>
|
||||
<DropdownMenuSeparator />
|
||||
<DropdownMenuItem
|
||||
className="text-red-600"
|
||||
onClick={() => {
|
||||
auth.signOut();
|
||||
}}
|
||||
>
|
||||
<DropdownMenuItem className="text-red-600" onClick={() => logout()}>
|
||||
Logout
|
||||
</DropdownMenuItem>
|
||||
</DropdownMenuContent>
|
||||
|
||||
@@ -44,10 +44,10 @@ export function useColumns(
|
||||
),
|
||||
},
|
||||
{
|
||||
accessorKey: 'access',
|
||||
accessorKey: 'projectAccess',
|
||||
header: 'Access',
|
||||
cell: ({ row }) => {
|
||||
const access = pathOr<string[]>([], ['meta', 'access'], row.original);
|
||||
const access = row.original.projectAccess;
|
||||
return (
|
||||
<>
|
||||
{access.map((id) => {
|
||||
@@ -102,7 +102,7 @@ function ActionCell({ row }: { row: Row<IServiceInvite> }) {
|
||||
<DropdownMenuItem
|
||||
className="text-destructive"
|
||||
onClick={() => {
|
||||
revoke.mutate({ memberId: row.original.id });
|
||||
revoke.mutate({ inviteId: row.original.id });
|
||||
}}
|
||||
>
|
||||
Revoke invite
|
||||
|
||||
@@ -15,6 +15,7 @@ import { useRef, useState } from 'react';
|
||||
import { toast } from 'sonner';
|
||||
|
||||
import { ACTIONS } from '@/components/data-table';
|
||||
import { useAuth } from '@/hooks/useAuth';
|
||||
import type { IServiceMember, IServiceProject } from '@openpanel/db';
|
||||
|
||||
export function useColumns(projects: IServiceProject[]) {
|
||||
@@ -77,6 +78,8 @@ function AccessCell({
|
||||
row: Row<IServiceMember>;
|
||||
projects: IServiceProject[];
|
||||
}) {
|
||||
const auth = useAuth();
|
||||
const currentUserId = auth.data?.userId;
|
||||
const initial = useRef(row.original.access.map((item) => item.projectId));
|
||||
const [access, setAccess] = useState<string[]>(
|
||||
row.original.access.map((item) => item.projectId),
|
||||
@@ -88,6 +91,16 @@ function AccessCell({
|
||||
},
|
||||
});
|
||||
|
||||
if (auth.isLoading) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (currentUserId === row.original.userId) {
|
||||
return (
|
||||
<div className="text-muted-foreground">Can't change your own access</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<ComboboxAdvanced
|
||||
placeholder="Restrict access to projects"
|
||||
|
||||
@@ -1,17 +1,16 @@
|
||||
'use client';
|
||||
|
||||
import { SignOutButton as ClerkSignOutButton } from '@clerk/nextjs';
|
||||
import { LogOutIcon } from 'lucide-react';
|
||||
|
||||
import { useLogout } from '@/hooks/useLogout';
|
||||
import { Button } from './ui/button';
|
||||
|
||||
const SignOutButton = () => {
|
||||
const logout = useLogout();
|
||||
return (
|
||||
<ClerkSignOutButton>
|
||||
<Button variant={'secondary'} icon={LogOutIcon}>
|
||||
Sign out
|
||||
</Button>
|
||||
</ClerkSignOutButton>
|
||||
<Button variant={'secondary'} icon={LogOutIcon} onClick={() => logout()}>
|
||||
Sign out
|
||||
</Button>
|
||||
);
|
||||
};
|
||||
|
||||
|
||||
@@ -17,23 +17,24 @@ export default function Syntax({ code }: SyntaxProps) {
|
||||
<div className="group relative">
|
||||
<button
|
||||
type="button"
|
||||
className="absolute right-1 top-1 rounded bg-card p-2 opacity-0 transition-opacity group-hover:opacity-100"
|
||||
className="absolute right-1 top-1 rounded bg-card p-2 opacity-0 transition-opacity group-hover:opacity-100 row items-center gap-2"
|
||||
onClick={() => {
|
||||
clipboard(code);
|
||||
}}
|
||||
>
|
||||
<span>Copy</span>
|
||||
<CopyIcon size={12} />
|
||||
</button>
|
||||
<SyntaxHighlighter
|
||||
// wrapLongLines
|
||||
style={docco}
|
||||
language="html"
|
||||
customStyle={{
|
||||
borderRadius: '0.5rem',
|
||||
padding: '1rem',
|
||||
paddingTop: '0.5rem',
|
||||
paddingBottom: '0.5rem',
|
||||
fontSize: 14,
|
||||
lineHeight: 1.3,
|
||||
}}
|
||||
>
|
||||
{code}
|
||||
|
||||
@@ -87,7 +87,7 @@ const SheetHeader = ({
|
||||
}: React.HTMLAttributes<HTMLDivElement>) => (
|
||||
<div
|
||||
className={cn(
|
||||
'relative -m-6 mb-6 flex justify-between rounded-t-lg border-b bg-def-100 p-6',
|
||||
'relative -m-6 mb-0 flex justify-between rounded-t-lg border-b bg-def-100 p-6',
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
|
||||
@@ -41,6 +41,7 @@ interface TooltiperProps {
|
||||
tooltipClassName?: string;
|
||||
onClick?: () => void;
|
||||
side?: 'top' | 'right' | 'bottom' | 'left';
|
||||
align?: 'start' | 'center' | 'end';
|
||||
delayDuration?: number;
|
||||
sideOffset?: number;
|
||||
disabled?: boolean;
|
||||
@@ -56,6 +57,7 @@ export function Tooltiper({
|
||||
delayDuration = 0,
|
||||
sideOffset = 10,
|
||||
disabled = false,
|
||||
align,
|
||||
}: TooltiperProps) {
|
||||
if (disabled) return children;
|
||||
return (
|
||||
@@ -68,6 +70,7 @@ export function Tooltiper({
|
||||
sideOffset={sideOffset}
|
||||
side={side}
|
||||
className={tooltipClassName}
|
||||
align={align}
|
||||
>
|
||||
{content}
|
||||
</TooltipContent>
|
||||
|
||||
5
apps/dashboard/src/hooks/useAuth.tsx
Normal file
5
apps/dashboard/src/hooks/useAuth.tsx
Normal file
@@ -0,0 +1,5 @@
|
||||
import { api } from '@/trpc/client';
|
||||
|
||||
export function useAuth() {
|
||||
return api.auth.session.useQuery();
|
||||
}
|
||||
15
apps/dashboard/src/hooks/useLogout.ts
Normal file
15
apps/dashboard/src/hooks/useLogout.ts
Normal file
@@ -0,0 +1,15 @@
|
||||
import { api } from '@/trpc/client';
|
||||
import { useRouter } from 'next/navigation';
|
||||
|
||||
export function useLogout() {
|
||||
const router = useRouter();
|
||||
const signOut = api.auth.signOut.useMutation({
|
||||
onSuccess() {
|
||||
setTimeout(() => {
|
||||
router.push('/login');
|
||||
}, 0);
|
||||
},
|
||||
});
|
||||
|
||||
return () => signOut.mutate();
|
||||
}
|
||||
@@ -1,6 +1,5 @@
|
||||
'use client';
|
||||
|
||||
import { useAuth } from '@clerk/nextjs';
|
||||
import debounce from 'lodash.debounce';
|
||||
import { use, useEffect, useMemo, useState } from 'react';
|
||||
import useWebSocket from 'react-use-websocket';
|
||||
@@ -18,19 +17,10 @@ export default function useWS<T>(
|
||||
onMessage: (event: T) => void,
|
||||
options?: UseWSOptions,
|
||||
) {
|
||||
const auth = useAuth();
|
||||
const ws = String(process.env.NEXT_PUBLIC_API_URL)
|
||||
.replace(/^https/, 'wss')
|
||||
.replace(/^http/, 'ws');
|
||||
const [baseUrl, setBaseUrl] = useState(`${ws}${path}`);
|
||||
const [token, setToken] = useState<string | null>(null);
|
||||
const socketUrl = useMemo(() => {
|
||||
const parseUrl = new URL(baseUrl);
|
||||
if (token) {
|
||||
parseUrl.searchParams.set('token', token);
|
||||
}
|
||||
return parseUrl.toString();
|
||||
}, [baseUrl, token]);
|
||||
|
||||
const debouncedOnMessage = useMemo(() => {
|
||||
if (options?.debounce) {
|
||||
@@ -39,18 +29,12 @@ export default function useWS<T>(
|
||||
return onMessage;
|
||||
}, [options?.debounce?.delay]);
|
||||
|
||||
useEffect(() => {
|
||||
if (auth.isSignedIn) {
|
||||
auth.getToken().then(setToken);
|
||||
}
|
||||
}, [auth]);
|
||||
|
||||
useEffect(() => {
|
||||
if (baseUrl === `${ws}${path}`) return;
|
||||
setBaseUrl(`${ws}${path}`);
|
||||
}, [path, baseUrl, ws]);
|
||||
|
||||
useWebSocket(socketUrl, {
|
||||
useWebSocket(baseUrl, {
|
||||
shouldReconnect: () => true,
|
||||
onMessage(event) {
|
||||
try {
|
||||
|
||||
@@ -1,30 +1,80 @@
|
||||
import { clerkMiddleware, createRouteMatcher } from '@clerk/nextjs/server';
|
||||
import { NextResponse } from 'next/server';
|
||||
import { COOKIE_MAX_AGE, COOKIE_OPTIONS } from '@openpanel/auth/constants';
|
||||
import { type NextRequest, NextResponse } from 'next/server';
|
||||
|
||||
function createRouteMatcher(patterns: string[]) {
|
||||
// Convert route patterns to regex patterns
|
||||
const regexPatterns = patterns.map((pattern) => {
|
||||
// Replace route parameters (:id) with regex capture groups
|
||||
const regexPattern = pattern
|
||||
.replace(/\//g, '\\/') // Escape forward slashes
|
||||
.replace(/:\w+/g, '([^/]+)') // Convert :param to capture groups
|
||||
.replace(/\(\.\*\)\?/g, '(?:.*)?'); // Handle optional wildcards
|
||||
|
||||
return new RegExp(`^${regexPattern}$`);
|
||||
});
|
||||
|
||||
// Return a matcher function
|
||||
return (req: { url: string }) => {
|
||||
const pathname = new URL(req.url).pathname;
|
||||
return regexPatterns.some((regex) => regex.test(pathname));
|
||||
};
|
||||
}
|
||||
|
||||
// This example protects all routes including api/trpc routes
|
||||
// Please edit this to allow other routes to be public as needed.
|
||||
// See https://clerk.com/docs/references/nextjs/auth-middleware for more information about configuring your Middleware
|
||||
const isPublicRoute = createRouteMatcher([
|
||||
'/share/overview/:id',
|
||||
'/api/clerk/(.*)?',
|
||||
'/login(.*)?',
|
||||
'/reset-password(.*)?',
|
||||
'/register(.*)?',
|
||||
'/sso-callback(.*)?',
|
||||
'/onboarding',
|
||||
]);
|
||||
|
||||
export default clerkMiddleware(
|
||||
(auth, req) => {
|
||||
if (process.env.MAINTENANCE_MODE && !req.url.includes('/maintenance')) {
|
||||
return NextResponse.redirect(new URL('/maintenance', req.url), 307);
|
||||
export default (request: NextRequest) => {
|
||||
if (request.method === 'GET') {
|
||||
const response = NextResponse.next();
|
||||
const token = request.cookies.get('session')?.value ?? null;
|
||||
|
||||
if (!isPublicRoute(request) && token === null) {
|
||||
return NextResponse.redirect(new URL('/login', request.url));
|
||||
}
|
||||
if (!isPublicRoute(req)) {
|
||||
auth().protect();
|
||||
|
||||
if (token !== null) {
|
||||
// Only extend cookie expiration on GET requests since we can be sure
|
||||
// a new session wasn't set when handling the request.
|
||||
response.cookies.set('session', token, {
|
||||
maxAge: COOKIE_MAX_AGE,
|
||||
...COOKIE_OPTIONS,
|
||||
});
|
||||
}
|
||||
},
|
||||
{
|
||||
debug: !!process.env.CLERK_DEBUG,
|
||||
},
|
||||
);
|
||||
return response;
|
||||
}
|
||||
|
||||
const originHeader = request.headers.get('Origin');
|
||||
// NOTE: You may need to use `X-Forwarded-Host` instead
|
||||
const hostHeader = request.headers.get('Host');
|
||||
if (originHeader === null || hostHeader === null) {
|
||||
return new NextResponse(null, {
|
||||
status: 403,
|
||||
});
|
||||
}
|
||||
let origin: URL;
|
||||
try {
|
||||
origin = new URL(originHeader);
|
||||
} catch {
|
||||
return new NextResponse(null, {
|
||||
status: 403,
|
||||
});
|
||||
}
|
||||
if (origin.host !== hostHeader) {
|
||||
return new NextResponse(null, {
|
||||
status: 403,
|
||||
});
|
||||
}
|
||||
|
||||
return NextResponse.next();
|
||||
};
|
||||
|
||||
export const config = {
|
||||
matcher: [
|
||||
|
||||
@@ -1,91 +0,0 @@
|
||||
'use client';
|
||||
|
||||
import {
|
||||
InputOTP,
|
||||
InputOTPGroup,
|
||||
InputOTPSlot,
|
||||
} from '@/components/ui/input-otp';
|
||||
import { getClerkError } from '@/utils/clerk-error';
|
||||
import { useSignUp } from '@clerk/nextjs';
|
||||
import { useRouter } from 'next/navigation';
|
||||
import { useState } from 'react';
|
||||
import { toast } from 'sonner';
|
||||
|
||||
import { popModal } from '.';
|
||||
import { ModalContent, ModalHeader } from './Modal/Container';
|
||||
|
||||
type Props = {
|
||||
email: string;
|
||||
};
|
||||
|
||||
export default function VerifyEmail({ email }: Props) {
|
||||
const { signUp, setActive, isLoaded } = useSignUp();
|
||||
const router = useRouter();
|
||||
const [code, setCode] = useState('');
|
||||
|
||||
return (
|
||||
<ModalContent
|
||||
onPointerDownOutside={(e) => e.preventDefault()}
|
||||
onEscapeKeyDown={(e) => e.preventDefault()}
|
||||
>
|
||||
<ModalHeader
|
||||
title="Verify your email"
|
||||
text={
|
||||
<p>
|
||||
Please enter the verification code sent to your{' '}
|
||||
<span className="font-semibold">{email}</span>.
|
||||
</p>
|
||||
}
|
||||
/>
|
||||
|
||||
<InputOTP
|
||||
maxLength={6}
|
||||
value={code}
|
||||
onChange={setCode}
|
||||
onComplete={async () => {
|
||||
if (!isLoaded) {
|
||||
return toast.info('Sign up is not available at the moment');
|
||||
}
|
||||
|
||||
try {
|
||||
const completeSignUp = await signUp.attemptEmailAddressVerification(
|
||||
{
|
||||
code,
|
||||
},
|
||||
);
|
||||
|
||||
if (completeSignUp.status !== 'complete') {
|
||||
// The status can also be `abandoned` or `missing_requirements`
|
||||
// Please see https://clerk.com/docs/references/react/use-sign-up#result-status for more information
|
||||
return toast.error('Invalid code');
|
||||
}
|
||||
|
||||
// Check the status to see if it is complete
|
||||
// If complete, the user has been created -- set the session active
|
||||
if (completeSignUp.status === 'complete') {
|
||||
await setActive({ session: completeSignUp.createdSessionId });
|
||||
router.push('/onboarding');
|
||||
popModal();
|
||||
}
|
||||
} catch (e) {
|
||||
const error = getClerkError(e);
|
||||
if (error) {
|
||||
toast.error(error.longMessage);
|
||||
} else {
|
||||
toast.error('An error occurred, please try again later');
|
||||
}
|
||||
}
|
||||
}}
|
||||
>
|
||||
<InputOTPGroup>
|
||||
<InputOTPSlot index={0} />
|
||||
<InputOTPSlot index={1} />
|
||||
<InputOTPSlot index={2} />
|
||||
<InputOTPSlot index={3} />
|
||||
<InputOTPSlot index={4} />
|
||||
<InputOTPSlot index={5} />
|
||||
</InputOTPGroup>
|
||||
</InputOTP>
|
||||
</ModalContent>
|
||||
);
|
||||
}
|
||||
@@ -14,6 +14,9 @@ const Loading = () => (
|
||||
);
|
||||
|
||||
const modals = {
|
||||
RequestPasswordReset: dynamic(() => import('./request-reset-password'), {
|
||||
loading: Loading,
|
||||
}),
|
||||
EditEvent: dynamic(() => import('./edit-event'), {
|
||||
loading: Loading,
|
||||
}),
|
||||
@@ -56,9 +59,6 @@ const modals = {
|
||||
OnboardingTroubleshoot: dynamic(() => import('./OnboardingTroubleshoot'), {
|
||||
loading: Loading,
|
||||
}),
|
||||
VerifyEmail: dynamic(() => import('./VerifyEmail'), {
|
||||
loading: Loading,
|
||||
}),
|
||||
DateRangerPicker: dynamic(() => import('./DateRangerPicker'), {
|
||||
loading: Loading,
|
||||
}),
|
||||
|
||||
73
apps/dashboard/src/modals/request-reset-password.tsx
Normal file
73
apps/dashboard/src/modals/request-reset-password.tsx
Normal file
@@ -0,0 +1,73 @@
|
||||
'use client';
|
||||
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { DialogFooter } from '@/components/ui/dialog';
|
||||
import { api, handleError } from '@/trpc/client';
|
||||
import { zodResolver } from '@hookform/resolvers/zod';
|
||||
import { SendIcon } from 'lucide-react';
|
||||
import { useRouter } from 'next/navigation';
|
||||
import { useForm } from 'react-hook-form';
|
||||
import { toast } from 'sonner';
|
||||
import type { z } from 'zod';
|
||||
|
||||
import { InputWithLabel } from '@/components/forms/input-with-label';
|
||||
import { zRequestResetPassword } from '@openpanel/validation';
|
||||
import { popModal } from '.';
|
||||
import { ModalContent, ModalHeader } from './Modal/Container';
|
||||
|
||||
const validation = zRequestResetPassword;
|
||||
type IForm = z.infer<typeof validation>;
|
||||
|
||||
type Props = {
|
||||
email?: string;
|
||||
};
|
||||
|
||||
export default function RequestPasswordReset({ email }: Props) {
|
||||
const router = useRouter();
|
||||
const form = useForm<IForm>({
|
||||
resolver: zodResolver(validation),
|
||||
defaultValues: {
|
||||
email: email ?? '',
|
||||
},
|
||||
});
|
||||
const mutation = api.auth.requestResetPassword.useMutation({
|
||||
onError: handleError,
|
||||
onSuccess() {
|
||||
toast.success('You should receive an email shortly!');
|
||||
popModal();
|
||||
},
|
||||
});
|
||||
|
||||
const onSubmit = form.handleSubmit((values) => {
|
||||
mutation.mutate({
|
||||
email: values.email,
|
||||
});
|
||||
});
|
||||
|
||||
return (
|
||||
<ModalContent>
|
||||
<ModalHeader title="Request password reset" />
|
||||
<form className="flex flex-col gap-4" onSubmit={onSubmit}>
|
||||
<InputWithLabel
|
||||
label="Email"
|
||||
placeholder="Your email address"
|
||||
error={form.formState.errors.email?.message}
|
||||
{...form.register('email')}
|
||||
/>
|
||||
|
||||
<DialogFooter>
|
||||
<Button
|
||||
type="button"
|
||||
variant={'secondary'}
|
||||
onClick={() => popModal()}
|
||||
>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button type="submit" icon={SendIcon} loading={mutation.isLoading}>
|
||||
Continue
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</form>
|
||||
</ModalContent>
|
||||
);
|
||||
}
|
||||
@@ -43,6 +43,27 @@
|
||||
--radius: 0.5rem;
|
||||
}
|
||||
|
||||
.prose {
|
||||
--tw-prose-body: #374151;
|
||||
--tw-prose-headings: #111827;
|
||||
--tw-prose-lead: #4b5563;
|
||||
--tw-prose-links: #2563eb;
|
||||
--tw-prose-bold: #111827;
|
||||
--tw-prose-counters: #6b7280;
|
||||
--tw-prose-bullets: #d1d5db;
|
||||
--tw-prose-hr: #e5e7eb;
|
||||
--tw-prose-quotes: #111827;
|
||||
--tw-prose-quote-borders: #e5e7eb;
|
||||
--tw-prose-captions: #6b7280;
|
||||
--tw-prose-kbd: #111827;
|
||||
--tw-prose-kbd-shadows: 17 24 39;
|
||||
--tw-prose-code: #111827;
|
||||
--tw-prose-pre-code: #e5e7eb;
|
||||
--tw-prose-pre-bg: #f9fafb;
|
||||
--tw-prose-th-borders: #d1d5db;
|
||||
--tw-prose-td-borders: #e5e7eb;
|
||||
}
|
||||
|
||||
.dark {
|
||||
--highlight: 221.44 100% 62.04%;
|
||||
|
||||
@@ -80,6 +101,27 @@
|
||||
--input: 0 0% 15.1%; /* #262626 */
|
||||
--ring: 0 0% 83.9%; /* #d6d6d6 */
|
||||
}
|
||||
|
||||
.dark .prose {
|
||||
--tw-prose-body: #e5e7eb;
|
||||
--tw-prose-headings: #f3f4f6;
|
||||
--tw-prose-lead: #9ca3af;
|
||||
--tw-prose-links: #60a5fa;
|
||||
--tw-prose-bold: #f3f4f6;
|
||||
--tw-prose-counters: #9ca3af;
|
||||
--tw-prose-bullets: #6b7280;
|
||||
--tw-prose-hr: #4b5563;
|
||||
--tw-prose-quotes: #f3f4f6;
|
||||
--tw-prose-quote-borders: #4b5563;
|
||||
--tw-prose-captions: #9ca3af;
|
||||
--tw-prose-kbd: #f3f4f6;
|
||||
--tw-prose-kbd-shadows: 255 255 255;
|
||||
--tw-prose-code: #f3f4f6;
|
||||
--tw-prose-pre-code: #d1d5db;
|
||||
--tw-prose-pre-bg: #1f2937;
|
||||
--tw-prose-th-borders: #4b5563;
|
||||
--tw-prose-td-borders: #374151;
|
||||
}
|
||||
}
|
||||
|
||||
@layer base {
|
||||
|
||||
@@ -1,14 +0,0 @@
|
||||
interface ClerkError extends Error {
|
||||
longMessage: string;
|
||||
}
|
||||
|
||||
export function getClerkError(e: unknown): ClerkError | null {
|
||||
if (e && typeof e === 'object' && 'errors' in e && Array.isArray(e.errors)) {
|
||||
const error = e.errors[0];
|
||||
if ('longMessage' in error && typeof error.longMessage === 'string') {
|
||||
return error as ClerkError;
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
@@ -1,8 +1,13 @@
|
||||
import { toast } from 'sonner';
|
||||
|
||||
export function clipboard(value: string | number) {
|
||||
export function clipboard(value: string | number, description?: null | string) {
|
||||
navigator.clipboard.writeText(value.toString());
|
||||
toast('Copied to clipboard', {
|
||||
description: value.toString(),
|
||||
});
|
||||
toast(
|
||||
'Copied to clipboard',
|
||||
description !== null
|
||||
? {
|
||||
description: description ?? value.toString(),
|
||||
}
|
||||
: {},
|
||||
);
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user