wip: clerk auth

This commit is contained in:
Carl-Gerhard Lindesvärd
2024-02-07 11:59:40 +01:00
parent bd62127451
commit a9cbff2306
46 changed files with 611 additions and 816 deletions

View File

@@ -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),

View File

@@ -44,7 +44,7 @@ export const dashboardRouter = createTRPCRouter({
return db.dashboard.findMany({
where: {
project: {
organization_id: input.organizationId,
organization_slug: input.organizationId,
},
},
include: {

View File

@@ -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,
});
}),
});

View File

@@ -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,
},
});

View File

@@ -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(

View File

@@ -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);

View File

@@ -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;
}

View File

@@ -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,

View File

@@ -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,
},

View File

@@ -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,
});
}

View File

@@ -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);
}

View File

@@ -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);
}