Add basic credentials authentication

This commit is contained in:
Meier Lukas
2023-07-28 18:51:44 +02:00
parent d507f0807f
commit d7f6bdf417
11 changed files with 794 additions and 12 deletions

View File

@@ -6,11 +6,14 @@
* 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 { initTRPC } from '@trpc/server';
import { TRPCError, initTRPC } 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';
import { getServerAuthSession } from '../auth';
/**
* 1. CONTEXT
*
@@ -19,7 +22,9 @@ import { ZodError } from 'zod';
* These allow you to access things when processing a request, like the database, the session, etc.
*/
type CreateContextOptions = Record<never, unknown>;
interface CreateContextOptions {
session: Session | null;
}
/**
* This helper generates the "internals" for a tRPC context. If you need to use it, you can export
@@ -31,7 +36,9 @@ type CreateContextOptions = Record<never, unknown>;
*
* @see https://create.t3.gg/en/usage/trpc#-serverapitrpcts
*/
const createInnerTRPCContext = (opts: CreateContextOptions) => ({});
const createInnerTRPCContext = (opts: CreateContextOptions) => ({
session: opts.session,
});
/**
* This is the actual context you will use in your router. It will be used to process every request
@@ -43,8 +50,11 @@ export const createTRPCContext = async (opts: CreateNextContextOptions) => {
const { req, res } = opts;
// Get the session from the server using the getServerSession wrapper function
const session = await getServerAuthSession({ req, res });
return createInnerTRPCContext({});
return createInnerTRPCContext({
session,
});
};
/**
@@ -90,3 +100,26 @@ export const createTRPCRouter = t.router;
* 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) {
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);

197
src/server/auth.ts Normal file
View File

@@ -0,0 +1,197 @@
import { PrismaAdapter } from '@next-auth/prisma-adapter';
import bcrypt from 'bcrypt';
import Cookies from 'cookies';
import { type GetServerSidePropsContext, type NextApiRequest, type NextApiResponse } from 'next';
import { type DefaultSession, type NextAuthOptions, getServerSession } from 'next-auth';
import { decode, encode } from 'next-auth/jwt';
import Credentials from 'next-auth/providers/credentials';
import { prisma } from '~/server/db';
import { fromDate, generateSessionToken } from '~/utils/session';
import { signInSchema } from '~/validations/user';
/**
* 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;
isAdmin: boolean;
// ...other properties
// role: UserRole;
};
}
interface User {
isAdmin: boolean;
// ...other properties
// role: UserRole;
}
}
declare module 'next-auth/jwt' {
interface JWT {
id: string;
isAdmin: boolean;
}
}
const adapter = PrismaAdapter(prisma);
const sessionMaxAgeInSeconds = 30 * 24 * 60 * 60; // 30 days
/**
* Options for NextAuth.js used to configure adapters, providers, callbacks, etc.
*
* @see https://next-auth.js.org/configuration/options
*/
export const constructAuthOptions = (
req: NextApiRequest,
res: NextApiResponse
): NextAuthOptions => ({
callbacks: {
async session({ session, user }) {
if (session.user) {
// eslint-disable-next-line no-param-reassign
session.user.id = user.id;
// eslint-disable-next-line no-param-reassign
session.user.name = user.name as string;
const userFromDatabase = await prisma.user.findUniqueOrThrow({
where: {
id: user.id,
},
include: {
roles: true,
},
});
session.user.isAdmin = userFromDatabase.isAdmin;
}
return session;
},
async signIn({ user }) {
// Check if this sign in callback is being called in the credentials authentication flow.
// If so, use the next-auth adapter to create a session entry in the database
// (SignIn is called after authorize so we can safely assume the user is valid and already authenticated).
if (!isCredentialsRequest(req)) return true;
if (!user) return true;
const sessionToken = generateSessionToken();
const sessionExpiry = fromDate(sessionMaxAgeInSeconds);
await adapter.createSession({
sessionToken: sessionToken,
userId: user.id,
expires: sessionExpiry,
});
const cookies = new Cookies(req, res);
cookies.set('next-auth.session-token', sessionToken, {
expires: sessionExpiry,
});
return true;
},
},
session: {
strategy: 'database',
maxAge: sessionMaxAgeInSeconds,
},
adapter: PrismaAdapter(prisma),
providers: [
Credentials({
name: 'credentials',
credentials: {
name: {
label: 'Username',
type: 'text',
},
password: { label: 'Password', type: 'password' },
},
async authorize(credentials) {
const data = await signInSchema.parseAsync(credentials);
const user = await prisma.user.findFirst({
include: {
roles: true,
},
where: {
name: data.name,
},
});
if (!user || !user.password) {
return null;
}
console.log(`user ${user.id} is trying to log in. checking password...`);
const isValidPassword = await bcrypt.compare(data.password, user.password);
if (!isValidPassword) {
console.log(`password for user ${user.id} was incorrect`);
return null;
}
console.log(`user ${user.id} successfully authorized`);
return {
id: user.id,
name: user.name,
isAdmin: false,
};
},
}),
],
jwt: {
async encode(params) {
if (!isCredentialsRequest(req)) {
return encode(params);
}
const cookies = new Cookies(req, res);
const cookie = cookies.get('next-auth.session-token');
return cookie ?? '';
},
async decode(params) {
if (!isCredentialsRequest(req)) {
return decode(params);
}
return null;
},
},
});
const isCredentialsRequest = (req: NextApiRequest): boolean => {
const nextAuthQueryParams = req.query.nextauth as ['callback', 'credentials'];
return (
nextAuthQueryParams.includes('callback') &&
nextAuthQueryParams.includes('credentials') &&
req.method === 'POST'
);
};
/**
* Wrapper for `getServerSession` so that you don't need to import the `authOptions` in every file.
*
* @see https://next-auth.js.org/configuration/nextjs
*/
export const getServerAuthSession = (ctx: {
req: GetServerSidePropsContext['req'];
res: GetServerSidePropsContext['res'];
}) => {
return getServerSession(
ctx.req,
ctx.res,
constructAuthOptions(
ctx.req as unknown as NextApiRequest,
ctx.res as unknown as NextApiResponse
)
);
};

14
src/server/db.ts Normal file
View File

@@ -0,0 +1,14 @@
import { PrismaClient } from '@prisma/client';
import { env } from '~/env';
const globalForPrisma = globalThis as unknown as {
prisma: PrismaClient | undefined;
};
export const prisma =
globalForPrisma.prisma ??
new PrismaClient({
log: env.NODE_ENV === 'development' ? ['query', 'error', 'warn'] : ['error'],
});
if (env.NODE_ENV !== 'production') globalForPrisma.prisma = prisma;