wip: clerk auth
This commit is contained in:
@@ -1,10 +1,10 @@
|
||||
import PageLayout from '@/app/(app)/page-layout';
|
||||
import { getSession } from '@/server/auth';
|
||||
import {
|
||||
createRecentDashboard,
|
||||
getDashboardById,
|
||||
} from '@/server/services/dashboard.service';
|
||||
import { getReportsByDashboardId } from '@/server/services/reports.service';
|
||||
import { auth } from '@clerk/nextjs';
|
||||
import { revalidateTag } from 'next/cache';
|
||||
|
||||
import { ListReports } from './list-reports';
|
||||
@@ -20,10 +20,10 @@ interface PageProps {
|
||||
export default async function Page({
|
||||
params: { organizationId, projectId, dashboardId },
|
||||
}: PageProps) {
|
||||
const session = await getSession();
|
||||
const { userId } = auth();
|
||||
|
||||
const dashboard = await getDashboardById(dashboardId);
|
||||
const reports = await getReportsByDashboardId(dashboardId);
|
||||
const userId = session?.user.id;
|
||||
if (userId && dashboard) {
|
||||
await createRecentDashboard({
|
||||
userId,
|
||||
@@ -35,7 +35,7 @@ export default async function Page({
|
||||
}
|
||||
|
||||
return (
|
||||
<PageLayout title={dashboard.name} organizationId={organizationId}>
|
||||
<PageLayout title={dashboard.name}>
|
||||
<ListReports reports={reports} />
|
||||
</PageLayout>
|
||||
);
|
||||
|
||||
@@ -6,18 +6,15 @@ import { ListDashboards } from './list-dashboards';
|
||||
|
||||
interface PageProps {
|
||||
params: {
|
||||
organizationId: string;
|
||||
projectId: string;
|
||||
};
|
||||
}
|
||||
|
||||
export default async function Page({
|
||||
params: { organizationId, projectId },
|
||||
}: PageProps) {
|
||||
export default async function Page({ params: { projectId } }: PageProps) {
|
||||
const dashboards = await getDashboardsByProjectId(projectId);
|
||||
|
||||
return (
|
||||
<PageLayout title="Dashboards" organizationId={organizationId}>
|
||||
<PageLayout title="Dashboards">
|
||||
<HeaderDashboards projectId={projectId} />
|
||||
<ListDashboards dashboards={dashboards} />
|
||||
</PageLayout>
|
||||
|
||||
@@ -4,15 +4,12 @@ import { ListEvents } from './list-events';
|
||||
|
||||
interface PageProps {
|
||||
params: {
|
||||
organizationId: string;
|
||||
projectId: string;
|
||||
};
|
||||
}
|
||||
export default function Page({
|
||||
params: { organizationId, projectId },
|
||||
}: PageProps) {
|
||||
export default function Page({ params: { projectId } }: PageProps) {
|
||||
return (
|
||||
<PageLayout title="Events" organizationId={organizationId}>
|
||||
<PageLayout title="Events">
|
||||
<ListEvents projectId={projectId} />
|
||||
</PageLayout>
|
||||
);
|
||||
|
||||
@@ -2,16 +2,9 @@ import PageLayout from '@/app/(app)/page-layout';
|
||||
|
||||
import OverviewMetrics from './overview-metrics';
|
||||
|
||||
interface PageProps {
|
||||
params: {
|
||||
organizationId: string;
|
||||
projectId: string;
|
||||
};
|
||||
}
|
||||
|
||||
export default function Page({ params: { organizationId } }: PageProps) {
|
||||
export default function Page() {
|
||||
return (
|
||||
<PageLayout title="Overview" organizationId={organizationId}>
|
||||
<PageLayout title="Overview">
|
||||
<OverviewMetrics />
|
||||
</PageLayout>
|
||||
);
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
import PageLayout from '@/app/(app)/page-layout';
|
||||
import { ListProperties } from '@/components/events/ListProperties';
|
||||
import { ProfileAvatar } from '@/components/profiles/ProfileAvatar';
|
||||
import { Avatar } from '@/components/ui/avatar';
|
||||
import { Widget, WidgetBody, WidgetHead } from '@/components/Widget';
|
||||
import {
|
||||
getProfileById,
|
||||
@@ -14,14 +13,13 @@ import ListProfileEvents from './list-profile-events';
|
||||
|
||||
interface PageProps {
|
||||
params: {
|
||||
organizationId: string;
|
||||
projectId: string;
|
||||
profileId: string;
|
||||
};
|
||||
}
|
||||
|
||||
export default async function Page({
|
||||
params: { organizationId, projectId, profileId },
|
||||
params: { projectId, profileId },
|
||||
}: PageProps) {
|
||||
const profile = await getProfileById(profileId);
|
||||
const profiles = (
|
||||
@@ -35,7 +33,6 @@ export default async function Page({
|
||||
{getProfileName(profile)}
|
||||
</div>
|
||||
}
|
||||
organizationId={organizationId}
|
||||
>
|
||||
<div className="p-4">
|
||||
<div className="grid gap-4 grid-cols-1 md:grid-cols-2 mb-8">
|
||||
|
||||
@@ -12,7 +12,7 @@ export default function Page({
|
||||
params: { organizationId, projectId },
|
||||
}: PageProps) {
|
||||
return (
|
||||
<PageLayout title="Events" organizationId={organizationId}>
|
||||
<PageLayout title="Events">
|
||||
<ListProfiles projectId={projectId} organizationId={organizationId} />
|
||||
</PageLayout>
|
||||
);
|
||||
|
||||
@@ -6,15 +6,12 @@ import ReportEditor from '../report-editor';
|
||||
|
||||
interface PageProps {
|
||||
params: {
|
||||
organizationId: string;
|
||||
projectId: string;
|
||||
reportId: string;
|
||||
};
|
||||
}
|
||||
|
||||
export default async function Page({
|
||||
params: { organizationId, reportId },
|
||||
}: PageProps) {
|
||||
export default async function Page({ params: { reportId } }: PageProps) {
|
||||
const report = await getReportById(reportId);
|
||||
return (
|
||||
<PageLayout
|
||||
@@ -24,7 +21,6 @@ export default async function Page({
|
||||
<Pencil size={16} />
|
||||
</div>
|
||||
}
|
||||
organizationId={organizationId}
|
||||
>
|
||||
<ReportEditor report={report} />
|
||||
</PageLayout>
|
||||
|
||||
@@ -19,7 +19,6 @@ export default function Page({ params: { organizationId } }: PageProps) {
|
||||
<Pencil size={16} />
|
||||
</div>
|
||||
}
|
||||
organizationId={organizationId}
|
||||
>
|
||||
<ReportEditor reportId={null} />
|
||||
</PageLayout>
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
import { getProjectWithMostEvents } from '@/server/services/project.service';
|
||||
import { redirect } from 'next/navigation';
|
||||
|
||||
import PageLayout from '../page-layout';
|
||||
|
||||
interface PageProps {
|
||||
params: {
|
||||
organizationId: string;
|
||||
@@ -14,5 +16,11 @@ export default async function Page({ params: { organizationId } }: PageProps) {
|
||||
return redirect(`/${organizationId}/${project.id}`);
|
||||
}
|
||||
|
||||
return null;
|
||||
return (
|
||||
<PageLayout title="Projects">
|
||||
<div className="p-4">
|
||||
<h1>Create your first project</h1>
|
||||
</div>
|
||||
</PageLayout>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -13,7 +13,7 @@ export default async function Page({ params: { organizationId } }: PageProps) {
|
||||
const clients = await getClientsByOrganizationId(organizationId);
|
||||
|
||||
return (
|
||||
<PageLayout title="Clients" organizationId={organizationId}>
|
||||
<PageLayout title="Clients">
|
||||
<ListClients clients={clients} />
|
||||
</PageLayout>
|
||||
);
|
||||
|
||||
@@ -5,7 +5,7 @@ import { InputWithLabel } from '@/components/forms/InputWithLabel';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { toast } from '@/components/ui/use-toast';
|
||||
import { Widget, WidgetBody, WidgetHead } from '@/components/Widget';
|
||||
import type { getOrganizationById } from '@/server/services/organization.service';
|
||||
import type { getOrganizationBySlug } from '@/server/services/organization.service';
|
||||
import { useRouter } from 'next/navigation';
|
||||
import { useForm } from 'react-hook-form';
|
||||
import { z } from 'zod';
|
||||
@@ -17,7 +17,7 @@ const validator = z.object({
|
||||
|
||||
type IForm = z.infer<typeof validator>;
|
||||
interface EditOrganizationProps {
|
||||
organization: Awaited<ReturnType<typeof getOrganizationById>>;
|
||||
organization: Awaited<ReturnType<typeof getOrganizationBySlug>>;
|
||||
}
|
||||
export default function EditOrganization({
|
||||
organization,
|
||||
@@ -64,10 +64,3 @@ export default function EditOrganization({
|
||||
</form>
|
||||
);
|
||||
}
|
||||
|
||||
// <ContentSection
|
||||
// title="Invite user"
|
||||
// text="Invite users to this organization. You can invite several users with (,)"
|
||||
// >
|
||||
|
||||
// </ContentSection>
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
import PageLayout from '@/app/(app)/page-layout';
|
||||
import { getOrganizationById } from '@/server/services/organization.service';
|
||||
import { getInvitesByOrganizationId } from '@/server/services/user.service';
|
||||
import { getOrganizationBySlug } from '@/server/services/organization.service';
|
||||
|
||||
import EditOrganization from './edit-organization';
|
||||
import InvitedUsers from './invited-users';
|
||||
@@ -12,11 +11,11 @@ interface PageProps {
|
||||
}
|
||||
|
||||
export default async function Page({ params: { organizationId } }: PageProps) {
|
||||
const organization = await getOrganizationById(organizationId);
|
||||
const invites = await getInvitesByOrganizationId(organizationId);
|
||||
const organization = await getOrganizationBySlug(organizationId);
|
||||
const invites = [];
|
||||
|
||||
return (
|
||||
<PageLayout title={organization.name} organizationId={organizationId}>
|
||||
<PageLayout title={organization.name}>
|
||||
<div className="p-4 grid grid-cols-1 lg:grid-cols-2 gap-4">
|
||||
<EditOrganization organization={organization} />
|
||||
<InvitedUsers invites={invites} organizationId={organizationId} />
|
||||
|
||||
@@ -1,15 +1,10 @@
|
||||
'use client';
|
||||
|
||||
import { api, handleError } from '@/app/_trpc/client';
|
||||
import { ContentHeader, ContentSection } from '@/components/Content';
|
||||
import { InputError } from '@/components/forms/InputError';
|
||||
import { InputWithLabel } from '@/components/forms/InputWithLabel';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { toast } from '@/components/ui/use-toast';
|
||||
import { Widget, WidgetBody, WidgetHead } from '@/components/Widget';
|
||||
import type { getOrganizationById } from '@/server/services/organization.service';
|
||||
import type { getProfileById } from '@/server/services/profile.service';
|
||||
import type { getUserById } from '@/server/services/user.service';
|
||||
import { zodResolver } from '@hookform/resolvers/zod';
|
||||
import { useRouter } from 'next/navigation';
|
||||
@@ -17,7 +12,8 @@ import { useForm } from 'react-hook-form';
|
||||
import { z } from 'zod';
|
||||
|
||||
const validator = z.object({
|
||||
name: z.string().min(2),
|
||||
firstName: z.string().min(2),
|
||||
lastName: z.string().min(2),
|
||||
email: z.string().email(),
|
||||
});
|
||||
|
||||
@@ -31,7 +27,8 @@ export default function EditProfile({ profile }: EditProfileProps) {
|
||||
const { register, handleSubmit, reset, formState } = useForm<IForm>({
|
||||
resolver: zodResolver(validator),
|
||||
defaultValues: {
|
||||
name: profile.name ?? '',
|
||||
firstName: profile.firstName ?? '',
|
||||
lastName: profile.lastName ?? '',
|
||||
email: profile.email ?? '',
|
||||
},
|
||||
});
|
||||
@@ -63,12 +60,19 @@ export default function EditProfile({ profile }: EditProfileProps) {
|
||||
</WidgetHead>
|
||||
<WidgetBody className="flex flex-col gap-4">
|
||||
<InputWithLabel
|
||||
label="Name"
|
||||
placeholder="Your name"
|
||||
defaultValue={profile.name ?? ''}
|
||||
{...register('name')}
|
||||
label="First name"
|
||||
placeholder="Your first name"
|
||||
defaultValue={profile.firstName ?? ''}
|
||||
{...register('firstName')}
|
||||
/>
|
||||
<InputWithLabel
|
||||
label="Last name"
|
||||
placeholder="Your last name"
|
||||
defaultValue={profile.lastName ?? ''}
|
||||
{...register('lastName')}
|
||||
/>
|
||||
<InputWithLabel
|
||||
disabled
|
||||
label="Email"
|
||||
placeholder="Your email"
|
||||
defaultValue={profile.email ?? ''}
|
||||
|
||||
@@ -1,22 +1,16 @@
|
||||
import PageLayout from '@/app/(app)/page-layout';
|
||||
import { getSession } from '@/server/auth';
|
||||
import { getUserById } from '@/server/services/user.service';
|
||||
import { auth } from '@clerk/nextjs';
|
||||
|
||||
import EditProfile from './edit-profile';
|
||||
import { Logout } from './logout';
|
||||
|
||||
interface PageProps {
|
||||
params: {
|
||||
organizationId: string;
|
||||
};
|
||||
}
|
||||
|
||||
export default async function Page({ params: { organizationId } }: PageProps) {
|
||||
const session = await getSession();
|
||||
const profile = await getUserById(session?.user.id!);
|
||||
export default async function Page() {
|
||||
const { userId } = auth();
|
||||
const profile = await getUserById(userId!);
|
||||
|
||||
return (
|
||||
<PageLayout title={profile.name} organizationId={organizationId}>
|
||||
<PageLayout title={profile.lastName}>
|
||||
<div className="p-4 flex flex-col gap-4">
|
||||
<EditProfile profile={profile} />
|
||||
<Logout />
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import PageLayout from '@/app/(app)/page-layout';
|
||||
import { getProjectsByOrganizationId } from '@/server/services/project.service';
|
||||
import { getProjectsByOrganizationSlug } from '@/server/services/project.service';
|
||||
|
||||
import ListProjects from './list-projects';
|
||||
|
||||
@@ -10,10 +10,10 @@ interface PageProps {
|
||||
}
|
||||
|
||||
export default async function Page({ params: { organizationId } }: PageProps) {
|
||||
const projects = await getProjectsByOrganizationId(organizationId);
|
||||
const projects = await getProjectsByOrganizationSlug(organizationId);
|
||||
|
||||
return (
|
||||
<PageLayout title="Projects" organizationId={organizationId}>
|
||||
<PageLayout title="Projects">
|
||||
<ListProjects projects={projects} />
|
||||
</PageLayout>
|
||||
);
|
||||
|
||||
@@ -134,7 +134,7 @@ export default function LayoutMenu({
|
||||
</span>
|
||||
</div>
|
||||
}
|
||||
href={`/${item.organization_id}/${item.project_id}/${item.dashboard_id}`}
|
||||
href={`/${item.organization_slug}/${item.project_id}/${item.dashboard_id}`}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
|
||||
@@ -14,7 +14,7 @@ export default function LayoutOrganizationSelector({
|
||||
const params = useAppParams();
|
||||
|
||||
const organization = organizations.find(
|
||||
(item) => item.id === params.organizationId
|
||||
(item) => item.slug === params.organizationId
|
||||
);
|
||||
|
||||
if (!organization) {
|
||||
|
||||
@@ -1,20 +1,18 @@
|
||||
'use client';
|
||||
|
||||
import { Combobox } from '@/components/ui/combobox';
|
||||
import type { getProjectsByOrganizationId } from '@/server/services/project.service';
|
||||
import { useParams, usePathname, useRouter } from 'next/navigation';
|
||||
import { useAppParams } from '@/hooks/useAppParams';
|
||||
import type { getCurrentProjects } from '@/server/services/project.service';
|
||||
import { usePathname, useRouter } from 'next/navigation';
|
||||
|
||||
interface LayoutProjectSelectorProps {
|
||||
projects: Awaited<ReturnType<typeof getProjectsByOrganizationId>>;
|
||||
organizationId: string | null;
|
||||
projects: Awaited<ReturnType<typeof getCurrentProjects>>;
|
||||
}
|
||||
export default function LayoutProjectSelector({
|
||||
projects,
|
||||
organizationId,
|
||||
}: LayoutProjectSelectorProps) {
|
||||
const router = useRouter();
|
||||
const params = useParams<{ projectId: string }>();
|
||||
const projectId = params?.projectId ? params.projectId : null;
|
||||
const { organizationId, projectId } = useAppParams();
|
||||
const pathname = usePathname() || '';
|
||||
|
||||
return (
|
||||
@@ -27,7 +25,7 @@ export default function LayoutProjectSelector({
|
||||
// we know its safe to just replace the current projectId
|
||||
// since the rest of the url is to a static page
|
||||
// e.g. /[organizationId]/[projectId]/events
|
||||
if (params && projectId && Object.keys(params).length === 2) {
|
||||
if (organizationId && projectId) {
|
||||
router.push(pathname.replace(projectId, value));
|
||||
} else {
|
||||
router.push(`/${organizationId}/${value}`);
|
||||
|
||||
@@ -2,7 +2,6 @@
|
||||
|
||||
import { useEffect, useState } from 'react';
|
||||
import { Logo } from '@/components/Logo';
|
||||
import type { IServiceRecentDashboards } from '@/server/services/dashboard.service';
|
||||
import type { IServiceOrganization } from '@/server/services/organization.service';
|
||||
import { cn } from '@/utils/cn';
|
||||
import { Rotate as Hamburger } from 'hamburger-react';
|
||||
@@ -13,15 +12,11 @@ import LayoutMenu from './layout-menu';
|
||||
import LayoutOrganizationSelector from './layout-organization-selector';
|
||||
|
||||
interface LayoutSidebarProps {
|
||||
recentDashboards: IServiceRecentDashboards;
|
||||
organizations: IServiceOrganization[];
|
||||
}
|
||||
export function LayoutSidebar({
|
||||
organizations,
|
||||
recentDashboards,
|
||||
}: LayoutSidebarProps) {
|
||||
export function LayoutSidebar({ organizations }: LayoutSidebarProps) {
|
||||
const [active, setActive] = useState(false);
|
||||
const fallbackProjectId = recentDashboards[0]?.project_id ?? null;
|
||||
const fallbackProjectId = null;
|
||||
const pathname = usePathname();
|
||||
useEffect(() => {
|
||||
setActive(false);
|
||||
@@ -54,7 +49,7 @@ export function LayoutSidebar({
|
||||
</div>
|
||||
<div className="flex flex-col p-4 gap-2 flex-grow overflow-auto">
|
||||
<LayoutMenu
|
||||
recentDashboards={recentDashboards}
|
||||
recentDashboards={[]}
|
||||
fallbackProjectId={fallbackProjectId}
|
||||
/>
|
||||
{/* Placeholder for LayoutOrganizationSelector */}
|
||||
|
||||
@@ -1,8 +1,5 @@
|
||||
import { getSession } from '@/server/auth';
|
||||
import { getRecentDashboardsByUserId } from '@/server/services/dashboard.service';
|
||||
import { getOrganizations } from '@/server/services/organization.service';
|
||||
|
||||
import Auth from '../auth';
|
||||
import { LayoutSidebar } from './layout-sidebar';
|
||||
|
||||
interface AppLayoutProps {
|
||||
@@ -10,19 +7,11 @@ interface AppLayoutProps {
|
||||
}
|
||||
|
||||
export default async function AppLayout({ children }: AppLayoutProps) {
|
||||
const session = await getSession();
|
||||
const organizations = await getOrganizations();
|
||||
const recentDashboards = session?.user.id
|
||||
? await getRecentDashboardsByUserId(session?.user.id)
|
||||
: [];
|
||||
|
||||
if (!session) {
|
||||
return <Auth />;
|
||||
}
|
||||
|
||||
return (
|
||||
<div id="dashboard">
|
||||
<LayoutSidebar {...{ organizations, recentDashboards }} />
|
||||
<LayoutSidebar {...{ organizations }} />
|
||||
<div className="lg:pl-72 transition-all">{children}</div>
|
||||
</div>
|
||||
);
|
||||
|
||||
@@ -1,32 +1,21 @@
|
||||
import { getProjectsByOrganizationId } from '@/server/services/project.service';
|
||||
import { getCurrentProjects } from '@/server/services/project.service';
|
||||
|
||||
import LayoutProjectSelector from './layout-project-selector';
|
||||
|
||||
interface PageLayoutProps {
|
||||
children: React.ReactNode;
|
||||
title: React.ReactNode;
|
||||
organizationId: string | null;
|
||||
}
|
||||
|
||||
export default async function PageLayout({
|
||||
children,
|
||||
title,
|
||||
organizationId,
|
||||
}: PageLayoutProps) {
|
||||
const projects = organizationId
|
||||
? await getProjectsByOrganizationId(organizationId)
|
||||
: [];
|
||||
export default async function PageLayout({ children, title }: PageLayoutProps) {
|
||||
const projects = await getCurrentProjects();
|
||||
|
||||
return (
|
||||
<>
|
||||
<div className="h-16 border-b border-border flex-shrink-0 sticky top-0 bg-white px-4 flex items-center justify-between z-20 pl-12 lg:pl-4">
|
||||
<div className="text-xl font-medium">{title}</div>
|
||||
|
||||
{projects.length > 0 && (
|
||||
<LayoutProjectSelector
|
||||
projects={projects}
|
||||
organizationId={organizationId}
|
||||
/>
|
||||
)}
|
||||
{projects.length > 0 && <LayoutProjectSelector projects={projects} />}
|
||||
</div>
|
||||
<div>{children}</div>
|
||||
</>
|
||||
|
||||
@@ -1,26 +1,13 @@
|
||||
import { ModalWrapper } from '@/modals';
|
||||
import { ModalContent, ModalHeader } from '@/modals/Modal/Container';
|
||||
import { getOrganizations } from '@/server/services/organization.service';
|
||||
import { CreateOrganization } from '@clerk/nextjs';
|
||||
import { redirect } from 'next/navigation';
|
||||
|
||||
import { db } from '@mixan/db';
|
||||
|
||||
import { ListOrganizations } from './list-organizations';
|
||||
|
||||
export default async function Page() {
|
||||
const organizations = await db.organization.findMany();
|
||||
const organizations = await getOrganizations();
|
||||
|
||||
if (organizations.length === 1 && organizations[0]?.id) {
|
||||
redirect(`/${organizations[0].id}`);
|
||||
if (organizations.length === 0) {
|
||||
return <CreateOrganization />;
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="fixed top-0 left-0 right-0 bottom-0 bg-[rgba(0,0,0,0.2)] z-50">
|
||||
<ModalWrapper>
|
||||
<ModalContent>
|
||||
<ModalHeader title="Select organization" onClose={false} />
|
||||
<ListOrganizations organizations={organizations} />
|
||||
</ModalContent>
|
||||
</ModalWrapper>
|
||||
</div>
|
||||
);
|
||||
return redirect(`/${organizations[0]?.slug}`);
|
||||
}
|
||||
|
||||
@@ -1,20 +0,0 @@
|
||||
import { cookies } from 'next/headers';
|
||||
import { NextResponse } from 'next/server';
|
||||
|
||||
export const dynamic = 'force-dynamic'; // defaults to auto
|
||||
export function GET(req: Request) {
|
||||
const qwe = new URL(req.url);
|
||||
const item = qwe.searchParams.entries();
|
||||
const {
|
||||
value: [key, value],
|
||||
} = item.next();
|
||||
|
||||
if (key && value) {
|
||||
cookies().set(`@mixan-${key}`, JSON.stringify(value), {
|
||||
httpOnly: true,
|
||||
expires: new Date(Date.now() + 1000 * 60 * 60 * 24 * 365),
|
||||
});
|
||||
}
|
||||
|
||||
return NextResponse.json({ key, value });
|
||||
}
|
||||
@@ -1,66 +0,0 @@
|
||||
import { randomUUID } from 'crypto';
|
||||
import { db, getId } from '@/server/db';
|
||||
import { hashPassword } from '@/server/services/hash.service';
|
||||
import { NextResponse } from 'next/server';
|
||||
|
||||
const userName = 'demo';
|
||||
const userPassword = 'demo';
|
||||
const userEmail = 'demo@demo.com';
|
||||
const organizationName = 'Demo Org';
|
||||
const projectName = 'Demo Project';
|
||||
|
||||
export async function GET() {
|
||||
try {
|
||||
const counts = await db.$transaction([
|
||||
db.user.count(),
|
||||
db.organization.count(),
|
||||
db.project.count(),
|
||||
db.client.count(),
|
||||
]);
|
||||
|
||||
if (counts.some((count) => count > 0)) {
|
||||
return NextResponse.json({ message: 'Already setup' });
|
||||
}
|
||||
|
||||
const organization = await db.organization.create({
|
||||
data: {
|
||||
id: await getId('organization', organizationName),
|
||||
name: organizationName,
|
||||
},
|
||||
});
|
||||
|
||||
const user = await db.user.create({
|
||||
data: {
|
||||
name: userName,
|
||||
password: await hashPassword(userPassword),
|
||||
email: userEmail,
|
||||
organization_id: organization.id,
|
||||
},
|
||||
});
|
||||
|
||||
const project = await db.project.create({
|
||||
data: {
|
||||
id: await getId('project', projectName),
|
||||
name: projectName,
|
||||
organization_id: organization.id,
|
||||
},
|
||||
});
|
||||
const secret = randomUUID();
|
||||
const client = await db.client.create({
|
||||
data: {
|
||||
name: `${projectName} Client`,
|
||||
project_id: project.id,
|
||||
organization_id: organization.id,
|
||||
secret: await hashPassword(secret),
|
||||
},
|
||||
});
|
||||
|
||||
return NextResponse.json({
|
||||
clientId: client.id,
|
||||
clientSecret: secret,
|
||||
user,
|
||||
});
|
||||
} catch (error) {
|
||||
return NextResponse.json({ error: 'Failed to setup' });
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
import { appRouter } from '@/server/api/root';
|
||||
import { getSession } from '@/server/auth';
|
||||
import { auth } from '@clerk/nextjs';
|
||||
import { fetchRequestHandler } from '@trpc/server/adapters/fetch';
|
||||
|
||||
const handler = (req: Request) =>
|
||||
@@ -7,10 +7,9 @@ const handler = (req: Request) =>
|
||||
endpoint: '/api/trpc',
|
||||
req,
|
||||
router: appRouter,
|
||||
createContext: async () => {
|
||||
const session = await getSession();
|
||||
createContext: () => {
|
||||
return {
|
||||
session,
|
||||
session: auth(),
|
||||
};
|
||||
},
|
||||
});
|
||||
|
||||
@@ -4,8 +4,6 @@ import Providers from './providers';
|
||||
|
||||
import '@/styles/globals.css';
|
||||
|
||||
import { getSession } from '@/server/auth';
|
||||
|
||||
export const metadata = {};
|
||||
|
||||
export const viewport = {
|
||||
@@ -20,14 +18,12 @@ export default async function RootLayout({
|
||||
}: {
|
||||
children: React.ReactNode;
|
||||
}) {
|
||||
const session = await getSession();
|
||||
|
||||
return (
|
||||
<html lang="en" className="light">
|
||||
<body
|
||||
className={cn('min-h-screen font-sans antialiased grainy bg-slate-50')}
|
||||
>
|
||||
<Providers session={session}>{children}</Providers>
|
||||
<Providers>{children}</Providers>
|
||||
</body>
|
||||
</html>
|
||||
);
|
||||
|
||||
@@ -7,20 +7,13 @@ import { TooltipProvider } from '@/components/ui/tooltip';
|
||||
import { ModalProvider } from '@/modals';
|
||||
import type { AppStore } from '@/redux';
|
||||
import makeStore from '@/redux';
|
||||
import { ClerkProvider } from '@clerk/nextjs';
|
||||
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
|
||||
import { httpLink } from '@trpc/client';
|
||||
import type { Session } from 'next-auth';
|
||||
import { SessionProvider } from 'next-auth/react';
|
||||
import { Provider as ReduxProvider } from 'react-redux';
|
||||
import superjson from 'superjson';
|
||||
|
||||
export default function Providers({
|
||||
children,
|
||||
session,
|
||||
}: {
|
||||
children: React.ReactNode;
|
||||
session: Session | null;
|
||||
}) {
|
||||
export default function Providers({ children }: { children: React.ReactNode }) {
|
||||
const [queryClient] = useState(
|
||||
() =>
|
||||
new QueryClient({
|
||||
@@ -51,7 +44,7 @@ export default function Providers({
|
||||
}
|
||||
|
||||
return (
|
||||
<SessionProvider session={session}>
|
||||
<ClerkProvider>
|
||||
<ReduxProvider store={storeRef.current}>
|
||||
<api.Provider client={trpcClient} queryClient={queryClient}>
|
||||
<QueryClientProvider client={queryClient}>
|
||||
@@ -63,6 +56,6 @@ export default function Providers({
|
||||
</QueryClientProvider>
|
||||
</api.Provider>
|
||||
</ReduxProvider>
|
||||
</SessionProvider>
|
||||
</ClerkProvider>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,97 +0,0 @@
|
||||
import { api, handleError } from '@/app/_trpc/client';
|
||||
import { ContentHeader, ContentSection } from '@/components/Content';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { toast } from '@/components/ui/use-toast';
|
||||
import { zodResolver } from '@hookform/resolvers/zod';
|
||||
import { useForm } from 'react-hook-form';
|
||||
import { z } from 'zod';
|
||||
|
||||
import { InputError } from '../forms/InputError';
|
||||
|
||||
const validator = z
|
||||
.object({
|
||||
oldPassword: z.string().min(1),
|
||||
password: z.string().min(8),
|
||||
confirmPassword: z.string().min(8),
|
||||
})
|
||||
.superRefine(({ confirmPassword, password }, ctx) => {
|
||||
if (confirmPassword !== password) {
|
||||
ctx.addIssue({
|
||||
path: ['confirmPassword'],
|
||||
code: 'custom',
|
||||
message: 'The passwords did not match',
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
type IForm = z.infer<typeof validator>;
|
||||
|
||||
export function ChangePassword() {
|
||||
const mutation = api.user.changePassword.useMutation({
|
||||
onSuccess() {
|
||||
toast({
|
||||
title: 'Success',
|
||||
description: 'You have updated your password',
|
||||
});
|
||||
},
|
||||
onError: handleError,
|
||||
});
|
||||
|
||||
const { register, handleSubmit, formState } = useForm<IForm>({
|
||||
resolver: zodResolver(validator),
|
||||
defaultValues: {
|
||||
oldPassword: '',
|
||||
password: '',
|
||||
confirmPassword: '',
|
||||
},
|
||||
});
|
||||
|
||||
return (
|
||||
<form
|
||||
onSubmit={handleSubmit((values) => {
|
||||
mutation.mutate(values);
|
||||
})}
|
||||
className="flex flex-col divide-y divide-border"
|
||||
>
|
||||
<ContentHeader
|
||||
title="Change password"
|
||||
text="Need to change your password?"
|
||||
>
|
||||
<Button type="submit" disabled={!formState.isDirty}>
|
||||
Change it!
|
||||
</Button>
|
||||
</ContentHeader>
|
||||
<ContentSection
|
||||
title="Old password"
|
||||
text={<InputError {...formState.errors.oldPassword} />}
|
||||
>
|
||||
<Input
|
||||
type="password"
|
||||
{...register('oldPassword')}
|
||||
placeholder="Old password"
|
||||
/>
|
||||
</ContentSection>
|
||||
<ContentSection
|
||||
title="New password"
|
||||
text={<InputError {...formState.errors.password} />}
|
||||
>
|
||||
<Input
|
||||
type="password"
|
||||
{...register('password')}
|
||||
placeholder="New password"
|
||||
/>
|
||||
</ContentSection>
|
||||
<ContentSection
|
||||
title="Confirm password"
|
||||
text={<InputError {...formState.errors.confirmPassword} />}
|
||||
>
|
||||
<Input
|
||||
type="password"
|
||||
{...register('confirmPassword')}
|
||||
placeholder="Confirm password"
|
||||
/>
|
||||
</ContentSection>
|
||||
</form>
|
||||
);
|
||||
}
|
||||
@@ -1,24 +1,12 @@
|
||||
import type { NextRequest } from 'next/server';
|
||||
import { NextResponse } from 'next/server';
|
||||
import { authMiddleware } from '@clerk/nextjs';
|
||||
|
||||
export const config = { matcher: ['/api/sdk/:path*'] };
|
||||
// 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
|
||||
export default authMiddleware({
|
||||
publicRoutes: [],
|
||||
});
|
||||
|
||||
export const cors = {
|
||||
'Access-Control-Allow-Origin': '*',
|
||||
'Access-Control-Allow-Methods': 'POST, PUT, OPTIONS',
|
||||
'Access-Control-Allow-Headers':
|
||||
'Content-Type, Authorization, Mixan-Client-Id, Mixan-Client-Secret',
|
||||
export const config = {
|
||||
matcher: ['/((?!.+\\.[\\w]+$|_next).*)', '/', '/(api|trpc)(.*)'],
|
||||
};
|
||||
|
||||
export function middleware(request: NextRequest) {
|
||||
const response = NextResponse.next();
|
||||
|
||||
if (request.method === 'OPTIONS') {
|
||||
return NextResponse.json({}, { headers: cors });
|
||||
}
|
||||
|
||||
Object.entries(cors).forEach(([key, value]) => {
|
||||
response.headers.append(key, value);
|
||||
});
|
||||
return response;
|
||||
}
|
||||
|
||||
@@ -14,7 +14,7 @@ export const clientRouter = createTRPCRouter({
|
||||
.query(async ({ input: { organizationId } }) => {
|
||||
return db.client.findMany({
|
||||
where: {
|
||||
organization_id: organizationId,
|
||||
organization_slug: organizationId,
|
||||
},
|
||||
include: {
|
||||
project: true,
|
||||
@@ -66,7 +66,7 @@ export const clientRouter = createTRPCRouter({
|
||||
const secret = randomUUID();
|
||||
const client = await db.client.create({
|
||||
data: {
|
||||
organization_id: input.organizationId,
|
||||
organization_slug: input.organizationId,
|
||||
project_id: input.projectId,
|
||||
name: input.name,
|
||||
secret: input.withCors ? null : await hashPassword(secret),
|
||||
|
||||
@@ -44,7 +44,7 @@ export const dashboardRouter = createTRPCRouter({
|
||||
return db.dashboard.findMany({
|
||||
where: {
|
||||
project: {
|
||||
organization_id: input.organizationId,
|
||||
organization_slug: input.organizationId,
|
||||
},
|
||||
},
|
||||
include: {
|
||||
|
||||
@@ -1,31 +1,16 @@
|
||||
import { createTRPCRouter, protectedProcedure } from '@/server/api/trpc';
|
||||
import { db } from '@/server/db';
|
||||
import { getOrganizationById } from '@/server/services/organization.service';
|
||||
import {
|
||||
getCurrentOrganization,
|
||||
getOrganizationBySlug,
|
||||
} from '@/server/services/organization.service';
|
||||
import { clerkClient } from '@clerk/nextjs';
|
||||
import { z } from 'zod';
|
||||
|
||||
export const organizationRouter = createTRPCRouter({
|
||||
list: protectedProcedure.query(({ ctx }) => {
|
||||
return db.organization.findMany({
|
||||
where: {
|
||||
users: {
|
||||
some: {
|
||||
id: ctx.session.user.id,
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
}),
|
||||
first: protectedProcedure.query(({ ctx }) => {
|
||||
return db.organization.findFirst({
|
||||
where: {
|
||||
users: {
|
||||
some: {
|
||||
id: ctx.session.user.id,
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
list: protectedProcedure.query(() => {
|
||||
return clerkClient.organizations.getOrganizationList();
|
||||
}),
|
||||
first: protectedProcedure.query(() => getCurrentOrganization()),
|
||||
get: protectedProcedure
|
||||
.input(
|
||||
z.object({
|
||||
@@ -33,7 +18,7 @@ export const organizationRouter = createTRPCRouter({
|
||||
})
|
||||
)
|
||||
.query(({ input }) => {
|
||||
return getOrganizationById(input.id);
|
||||
return getOrganizationBySlug(input.id);
|
||||
}),
|
||||
update: protectedProcedure
|
||||
.input(
|
||||
@@ -43,13 +28,8 @@ export const organizationRouter = createTRPCRouter({
|
||||
})
|
||||
)
|
||||
.mutation(({ input }) => {
|
||||
return db.organization.update({
|
||||
where: {
|
||||
id: input.id,
|
||||
},
|
||||
data: {
|
||||
name: input.name,
|
||||
},
|
||||
return clerkClient.organizations.updateOrganization(input.id, {
|
||||
name: input.name,
|
||||
});
|
||||
}),
|
||||
});
|
||||
|
||||
@@ -15,7 +15,7 @@ export const projectRouter = createTRPCRouter({
|
||||
|
||||
return db.project.findMany({
|
||||
where: {
|
||||
organization_id: organizationId,
|
||||
organization_slug: organizationId,
|
||||
},
|
||||
});
|
||||
}),
|
||||
@@ -60,7 +60,7 @@ export const projectRouter = createTRPCRouter({
|
||||
return db.project.create({
|
||||
data: {
|
||||
id: await getId('project', input.name),
|
||||
organization_id: input.organizationId,
|
||||
organization_slug: input.organizationId,
|
||||
name: input.name,
|
||||
},
|
||||
});
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
import { createTRPCRouter, protectedProcedure } from '@/server/api/trpc';
|
||||
import { db } from '@/server/db';
|
||||
import { hashPassword, verifyPassword } from '@/server/services/hash.service';
|
||||
import { transformUser } from '@/server/services/user.service';
|
||||
import { clerkClient } from '@clerk/nextjs';
|
||||
import { z } from 'zod';
|
||||
|
||||
export const userRouter = createTRPCRouter({
|
||||
@@ -14,47 +16,17 @@ export const userRouter = createTRPCRouter({
|
||||
update: protectedProcedure
|
||||
.input(
|
||||
z.object({
|
||||
name: z.string(),
|
||||
email: z.string(),
|
||||
firstName: z.string(),
|
||||
lastName: z.string(),
|
||||
})
|
||||
)
|
||||
.mutation(({ input, ctx }) => {
|
||||
return db.user.update({
|
||||
where: {
|
||||
id: ctx.session.user.id,
|
||||
},
|
||||
data: {
|
||||
name: input.name,
|
||||
email: input.email,
|
||||
},
|
||||
});
|
||||
}),
|
||||
changePassword: protectedProcedure
|
||||
.input(
|
||||
z.object({
|
||||
password: z.string(),
|
||||
oldPassword: z.string(),
|
||||
})
|
||||
)
|
||||
.mutation(async ({ input, ctx }) => {
|
||||
const user = await db.user.findUniqueOrThrow({
|
||||
where: {
|
||||
id: ctx.session.user.id,
|
||||
},
|
||||
});
|
||||
|
||||
if (!(await verifyPassword(input.oldPassword, user.password))) {
|
||||
throw new Error('Old password is incorrect');
|
||||
}
|
||||
|
||||
return db.user.update({
|
||||
where: {
|
||||
id: ctx.session.user.id,
|
||||
},
|
||||
data: {
|
||||
password: await hashPassword(input.password),
|
||||
},
|
||||
});
|
||||
return clerkClient.users
|
||||
.updateUser(ctx.session.userId, {
|
||||
firstName: input.firstName,
|
||||
lastName: input.lastName,
|
||||
})
|
||||
.then(transformUser);
|
||||
}),
|
||||
invite: protectedProcedure
|
||||
.input(
|
||||
|
||||
@@ -1,71 +1,13 @@
|
||||
/**
|
||||
* YOU PROBABLY DON'T NEED TO EDIT THIS FILE, UNLESS:
|
||||
* 1. You want to modify request context (see Part 1).
|
||||
* 2. You want to create a new middleware or type of procedure (see Part 3).
|
||||
*
|
||||
* TL;DR - This is where all the tRPC server stuff is created and plugged in. The pieces you will
|
||||
* need to use are documented accordingly near the end.
|
||||
*/
|
||||
|
||||
import { getSession } from '@/server/auth';
|
||||
import type { auth } from '@clerk/nextjs';
|
||||
import { initTRPC, TRPCError } from '@trpc/server';
|
||||
import type { CreateNextContextOptions } from '@trpc/server/adapters/next';
|
||||
import type { Session } from 'next-auth';
|
||||
import superjson from 'superjson';
|
||||
import { ZodError } from 'zod';
|
||||
|
||||
/**
|
||||
* 1. CONTEXT
|
||||
*
|
||||
* This section defines the "contexts" that are available in the backend API.
|
||||
*
|
||||
* These allow you to access things when processing a request, like the database, the session, etc.
|
||||
*/
|
||||
|
||||
interface CreateContextOptions {
|
||||
session: Session | null;
|
||||
session: ReturnType<typeof auth> | null;
|
||||
}
|
||||
|
||||
/**
|
||||
* This helper generates the "internals" for a tRPC context. If you need to use it, you can export
|
||||
* it from here.
|
||||
*
|
||||
* Examples of things you may need it for:
|
||||
* - testing, so we don't have to mock Next.js' req/res
|
||||
* - tRPC's `createSSGHelpers`, where we don't have req/res
|
||||
*
|
||||
* @see https://create.t3.gg/en/usage/trpc#-serverapitrpcts
|
||||
*/
|
||||
export const createInnerTRPCContext = (opts: CreateContextOptions) => {
|
||||
return {
|
||||
session: opts.session,
|
||||
};
|
||||
};
|
||||
|
||||
/**
|
||||
* This is the actual context you will use in your router. It will be used to process every request
|
||||
* that goes through your tRPC endpoint.
|
||||
*
|
||||
* @see https://trpc.io/docs/context
|
||||
*/
|
||||
export const createTRPCContext = async (opts: CreateNextContextOptions) => {
|
||||
// Get the session from the server using the getServerSession wrapper function
|
||||
const session = await getSession();
|
||||
|
||||
return createInnerTRPCContext({
|
||||
session,
|
||||
});
|
||||
};
|
||||
|
||||
/**
|
||||
* 2. INITIALIZATION
|
||||
*
|
||||
* This is where the tRPC API is initialized, connecting the context and transformer. We also parse
|
||||
* ZodErrors so that you get typesafety on the frontend if your procedure fails due to validation
|
||||
* errors on the backend.
|
||||
*/
|
||||
|
||||
const t = initTRPC.context<typeof createTRPCContext>().create({
|
||||
const t = initTRPC.context<CreateContextOptions>().create({
|
||||
transformer: superjson,
|
||||
errorFormatter({ shape, error }) {
|
||||
return {
|
||||
@@ -79,48 +21,19 @@ const t = initTRPC.context<typeof createTRPCContext>().create({
|
||||
},
|
||||
});
|
||||
|
||||
/**
|
||||
* 3. ROUTER & PROCEDURE (THE IMPORTANT BIT)
|
||||
*
|
||||
* These are the pieces you use to build your tRPC API. You should import these a lot in the
|
||||
* "/src/server/api/routers" directory.
|
||||
*/
|
||||
|
||||
/**
|
||||
* This is how you create new routers and sub-routers in your tRPC API.
|
||||
*
|
||||
* @see https://trpc.io/docs/router
|
||||
*/
|
||||
export const createTRPCRouter = t.router;
|
||||
|
||||
/**
|
||||
* Public (unauthenticated) procedure
|
||||
*
|
||||
* This is the base piece you use to build new queries and mutations on your tRPC API. It does not
|
||||
* guarantee that a user querying is authorized, but you can still access user session data if they
|
||||
* are logged in.
|
||||
*/
|
||||
export const publicProcedure = t.procedure;
|
||||
|
||||
/** Reusable middleware that enforces users are logged in before running the procedure. */
|
||||
const enforceUserIsAuthed = t.middleware(({ ctx, next }) => {
|
||||
if (!ctx.session?.user) {
|
||||
if (!ctx.session?.userId) {
|
||||
throw new TRPCError({ code: 'UNAUTHORIZED' });
|
||||
}
|
||||
return next({
|
||||
ctx: {
|
||||
// infers the `session` as non-nullable
|
||||
session: { ...ctx.session, user: ctx.session.user },
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
/**
|
||||
* Protected (authenticated) procedure
|
||||
*
|
||||
* If you want a query or mutation to ONLY be accessible to logged in users, use this. It verifies
|
||||
* the session is valid and guarantees `ctx.session.user` is not null.
|
||||
*
|
||||
* @see https://trpc.io/docs/procedures
|
||||
*/
|
||||
export const protectedProcedure = t.procedure.use(enforceUserIsAuthed);
|
||||
|
||||
@@ -1,124 +1,3 @@
|
||||
import { cache } from 'react';
|
||||
import { db } from '@/server/db';
|
||||
import { verifyPassword } from '@/server/services/hash.service';
|
||||
import type { NextApiRequest, NextApiResponse } from 'next';
|
||||
import { getServerSession } from 'next-auth';
|
||||
import type { DefaultSession, NextAuthOptions } from 'next-auth';
|
||||
import Credentials from 'next-auth/providers/credentials';
|
||||
|
||||
import { createError } from './exceptions';
|
||||
|
||||
/**
|
||||
* Module augmentation for `next-auth` types. Allows us to add custom properties to the `session`
|
||||
* object and keep type safety.
|
||||
*
|
||||
* @see https://next-auth.js.org/getting-started/typescript#module-augmentation
|
||||
*/
|
||||
declare module 'next-auth' {
|
||||
interface Session extends DefaultSession {
|
||||
user: DefaultSession['user'] & {
|
||||
id: string;
|
||||
};
|
||||
}
|
||||
|
||||
// interface User {
|
||||
// // ...other properties
|
||||
// // role: UserRole;
|
||||
// }
|
||||
}
|
||||
|
||||
/**
|
||||
* Options for NextAuth.js used to configure adapters, providers, callbacks, etc.
|
||||
*
|
||||
* @see https://next-auth.js.org/configuration/options
|
||||
*/
|
||||
export const authOptions: NextAuthOptions = {
|
||||
callbacks: {
|
||||
session: ({ session, token }) => ({
|
||||
...session,
|
||||
user: {
|
||||
...session.user,
|
||||
id: token.sub,
|
||||
},
|
||||
}),
|
||||
},
|
||||
session: {
|
||||
strategy: 'jwt',
|
||||
},
|
||||
providers: [
|
||||
Credentials({
|
||||
name: 'Credentials',
|
||||
credentials: {
|
||||
email: { label: 'Email', type: 'text', placeholder: 'jsmith' },
|
||||
password: { label: 'Password', type: 'password' },
|
||||
},
|
||||
async authorize(credentials) {
|
||||
if (!credentials?.password || !credentials?.email) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const user = await db.user.findFirst({
|
||||
where: { email: credentials?.email },
|
||||
});
|
||||
|
||||
if (!user) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (!(await verifyPassword(credentials.password, user.password))) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return {
|
||||
...user,
|
||||
image: 'https://api.dicebear.com/7.x/adventurer/svg?seed=Abby',
|
||||
};
|
||||
},
|
||||
}),
|
||||
],
|
||||
};
|
||||
|
||||
export const getSession = cache(
|
||||
async () => await getServerSession(authOptions)
|
||||
);
|
||||
|
||||
export async function validateSdkRequest(
|
||||
req: NextApiRequest,
|
||||
res: NextApiResponse
|
||||
): Promise<string> {
|
||||
const clientId = req?.headers['mixan-client-id'] as string | undefined;
|
||||
const clientSecret = req.headers['mixan-client-secret'] as string | undefined;
|
||||
|
||||
if (!clientId) {
|
||||
throw createError(401, 'Misisng client id');
|
||||
}
|
||||
|
||||
const client = await db.client.findUnique({
|
||||
where: {
|
||||
id: clientId,
|
||||
},
|
||||
});
|
||||
|
||||
if (!client) {
|
||||
throw createError(401, 'Invalid client id');
|
||||
}
|
||||
|
||||
if (client.secret) {
|
||||
if (!(await verifyPassword(clientSecret || '', client.secret))) {
|
||||
throw createError(401, 'Invalid client secret');
|
||||
}
|
||||
} else if (client.cors !== '*') {
|
||||
const ok = client.cors.split(',').find((origin) => {
|
||||
if (origin === req.headers.origin) {
|
||||
return true;
|
||||
}
|
||||
});
|
||||
if (ok) {
|
||||
res.setHeader('Access-Control-Allow-Origin', String(req.headers.origin));
|
||||
} else {
|
||||
throw createError(401, 'Invalid cors settings');
|
||||
}
|
||||
}
|
||||
|
||||
return client.project_id;
|
||||
export async function getSession() {
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -3,7 +3,7 @@ import { db } from '@mixan/db';
|
||||
export function getClientsByOrganizationId(organizationId: string) {
|
||||
return db.client.findMany({
|
||||
where: {
|
||||
organization_id: organizationId,
|
||||
organization_slug: organizationId,
|
||||
},
|
||||
include: {
|
||||
project: true,
|
||||
|
||||
@@ -72,13 +72,13 @@ export async function createRecentDashboard({
|
||||
user_id: userId,
|
||||
project_id: projectId,
|
||||
dashboard_id: dashboardId,
|
||||
organization_id: organizationId,
|
||||
organization_slug: organizationId,
|
||||
},
|
||||
});
|
||||
return db.recentDashboards.create({
|
||||
data: {
|
||||
user_id: userId,
|
||||
organization_id: organizationId,
|
||||
organization_slug: organizationId,
|
||||
project_id: projectId,
|
||||
dashboard_id: dashboardId,
|
||||
},
|
||||
|
||||
@@ -1,37 +1,52 @@
|
||||
import { auth, clerkClient } from '@clerk/nextjs';
|
||||
import type { Organization } from '@clerk/nextjs/dist/types/server';
|
||||
|
||||
import { db } from '../db';
|
||||
|
||||
export type IServiceOrganization = Awaited<
|
||||
ReturnType<typeof getOrganizations>
|
||||
>[number];
|
||||
|
||||
export function getOrganizations() {
|
||||
return db.organization.findMany({
|
||||
where: {
|
||||
// users: {
|
||||
// some: {
|
||||
// id: '1',
|
||||
// },
|
||||
// }
|
||||
},
|
||||
});
|
||||
function transformOrganization(org: Organization) {
|
||||
return {
|
||||
id: org.id,
|
||||
name: org.name,
|
||||
slug: org.slug,
|
||||
};
|
||||
}
|
||||
|
||||
export function getOrganizationById(id: string) {
|
||||
return db.organization.findUniqueOrThrow({
|
||||
where: {
|
||||
id,
|
||||
},
|
||||
});
|
||||
export async function getOrganizations() {
|
||||
const orgs = await clerkClient.organizations.getOrganizationList();
|
||||
return orgs.map(transformOrganization);
|
||||
}
|
||||
|
||||
export function getOrganizationByProjectId(projectId: string) {
|
||||
return db.organization.findFirst({
|
||||
export async function getCurrentOrganization() {
|
||||
const session = auth();
|
||||
if (!session?.orgSlug) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const organization = await clerkClient.organizations.getOrganization({
|
||||
slug: session.orgSlug,
|
||||
});
|
||||
|
||||
return transformOrganization(organization);
|
||||
}
|
||||
|
||||
export function getOrganizationBySlug(slug: string) {
|
||||
return clerkClient.organizations
|
||||
.getOrganization({ slug })
|
||||
.then(transformOrganization);
|
||||
}
|
||||
|
||||
export async function getOrganizationByProjectId(projectId: string) {
|
||||
const project = await db.project.findUniqueOrThrow({
|
||||
where: {
|
||||
projects: {
|
||||
some: {
|
||||
id: projectId,
|
||||
},
|
||||
},
|
||||
id: projectId,
|
||||
},
|
||||
});
|
||||
|
||||
return clerkClient.organizations.getOrganization({
|
||||
slug: project.organization_slug,
|
||||
});
|
||||
}
|
||||
|
||||
@@ -1,8 +1,7 @@
|
||||
import { unstable_cache } from 'next/cache';
|
||||
|
||||
import { chQuery } from '@mixan/db';
|
||||
|
||||
import { db } from '../db';
|
||||
import { getCurrentOrganization } from './organization.service';
|
||||
|
||||
export type IServiceProject = Awaited<ReturnType<typeof getProjectById>>;
|
||||
|
||||
@@ -14,44 +13,31 @@ export function getProjectById(id: string) {
|
||||
});
|
||||
}
|
||||
|
||||
export function getProjectsByOrganizationId(organizationId: string) {
|
||||
return db.project.findMany({
|
||||
export async function getCurrentProjects() {
|
||||
const organization = await getCurrentOrganization();
|
||||
if (!organization?.slug) return [];
|
||||
return await db.project.findMany({
|
||||
where: {
|
||||
organization_id: organizationId,
|
||||
organization_slug: organization.slug,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export async function getProjectWithMostEvents(organizationId: string) {
|
||||
export function getProjectsByOrganizationSlug(slug: string) {
|
||||
return db.project.findMany({
|
||||
where: {
|
||||
organization_slug: slug,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export async function getProjectWithMostEvents(slug: string) {
|
||||
return db.project.findFirst({
|
||||
where: {
|
||||
organization_id: organizationId,
|
||||
organization_slug: slug,
|
||||
},
|
||||
orderBy: {
|
||||
eventsCount: 'desc',
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export function getFirstProjectByOrganizationId(organizationId: string) {
|
||||
const tag = `getFirstProjectByOrganizationId_${organizationId}`;
|
||||
return unstable_cache(
|
||||
async (organizationId: string) => {
|
||||
return db.project.findFirst({
|
||||
where: {
|
||||
organization_id: organizationId,
|
||||
},
|
||||
orderBy: {
|
||||
events: {
|
||||
_count: 'desc',
|
||||
},
|
||||
},
|
||||
});
|
||||
},
|
||||
tag.split('_'),
|
||||
{
|
||||
tags: [tag],
|
||||
revalidate: 3600 * 24,
|
||||
}
|
||||
)(organizationId);
|
||||
}
|
||||
|
||||
@@ -1,20 +1,24 @@
|
||||
import { db } from '@/server/db';
|
||||
import { auth, clerkClient } from '@clerk/nextjs';
|
||||
import type { User } from '@clerk/nextjs/dist/types/server';
|
||||
|
||||
export function getUserById(id: string) {
|
||||
return db.user.findUniqueOrThrow({
|
||||
where: {
|
||||
id,
|
||||
},
|
||||
});
|
||||
export function transformUser(user: User) {
|
||||
return {
|
||||
name: `${user.firstName} ${user.lastName}`,
|
||||
email: user.emailAddresses[0]?.emailAddress ?? '',
|
||||
id: user.id,
|
||||
lastName: user.lastName ?? '',
|
||||
firstName: user.firstName ?? '',
|
||||
};
|
||||
}
|
||||
|
||||
export type IServiceInvite = Awaited<
|
||||
ReturnType<typeof getInvitesByOrganizationId>
|
||||
>[number];
|
||||
export function getInvitesByOrganizationId(organizationId: string) {
|
||||
return db.invite.findMany({
|
||||
where: {
|
||||
organization_id: organizationId,
|
||||
},
|
||||
});
|
||||
export async function getCurrentUser() {
|
||||
const session = auth();
|
||||
if (!session.userId) {
|
||||
return null;
|
||||
}
|
||||
return getUserById(session.userId);
|
||||
}
|
||||
|
||||
export async function getUserById(id: string) {
|
||||
return clerkClient.users.getUser(id).then(transformUser);
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user