Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Session refresh functionality #98

Open
wants to merge 12 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
43 changes: 43 additions & 0 deletions apps/web/app/(pages)/ClientWrapper.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
"use client";

import { useEffect } from "react";

import { trpc } from "@good-dog/trpc/client";

/**
* This component is used to wrap the entire application with any client-side
* hooks or components that need to be run on every page.
*/
export const ClientWrapper = (
props: Readonly<{
children: React.ReactNode;
}>,
) => {
useSessionRefresh();

return <>{props.children}</>;
};

/**
* Due to limitations in the Next.js rendering engine, we can't set cookies during page load.
*
* That means we need shouldn't set any cookies in tRPC *queries*, and instead should use *mutations*
* which will never be run at render time.
*
* This component will automatically refresh the session if the session is
* marked as `refreshRequired`.
*/
const useSessionRefresh = () => {
const [user, userQuery] = trpc.user.useSuspenseQuery();
const refreshSessionMutation = trpc.refreshSession.useMutation({
onSuccess: () => {
void userQuery.refetch();
},
});

useEffect(() => {
if (user?.session.refreshRequired && !refreshSessionMutation.isPending) {
refreshSessionMutation.mutate();
}
}, [user?.session, refreshSessionMutation]);
};
10 changes: 7 additions & 3 deletions apps/web/app/(pages)/layout.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@ import Footer from "@good-dog/components/Footer";
import Nav from "@good-dog/components/Nav";
import { HydrateClient, trpc } from "@good-dog/trpc/server";

import { ClientWrapper } from "./ClientWrapper";

export const dynamic = "force-dynamic";

export default function Layout({
Expand All @@ -11,9 +13,11 @@ export default function Layout({

return (
<HydrateClient>
<Nav />
{children}
<Footer />
<ClientWrapper>
<Nav />
{children}
<Footer />
</ClientWrapper>
</HydrateClient>
);
}
10 changes: 5 additions & 5 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -15,11 +15,11 @@
"__DATABASE__________": "",
"db:up": "docker-compose -f compose.yml up -d",
"db:down": "docker-compose -f compose.yml down",
"db:push": "dotenv -e .env -- turbo run -F @good-dog/db push",
"db:generate": "turbo run -F @good-dog/db generate",
"db:migrate": "dotenv -e .env -- turbo run -F @good-dog/db migrate",
"db:migrate:create": "dotenv -e .env -- turbo run -F @good-dog/db migrate:create",
"db:migrate:reset": "dotenv -e .env -- turbo run -F @good-dog/db migrate:reset",
"db:push": "dotenv -e .env -- turbo run -F @good-dog/db push --ui tui",
"db:migrate": "dotenv -e .env -- turbo run -F @good-dog/db migrate --ui tui",
"db:migrate:create": "dotenv -e .env -- turbo run -F @good-dog/db migrate:create --ui tui",
"db:migrate:reset": "dotenv -e .env -- turbo run -F @good-dog/db migrate:reset --ui tui",
"db:studio": "dotenv -e .env -- turbo run -F @good-dog/db studio",
"db:seed": "dotenv -e .env -- turbo run -F @good-dog/db seed",
"__DEVELOPMENT_______": "",
Expand All @@ -35,7 +35,7 @@
"__MISC______________": "",
"postinstall": "turbo run generate",
"typecheck": "turbo run typecheck",
"shad:add": "turbo run ui-add",
"shad:add": "turbo run -F @good-dog/ui ui:add --ui tui",
"generate:package": "turbo generate package",
"env:setup": "cp .env.example .env"
},
Expand Down
13 changes: 13 additions & 0 deletions packages/db/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ This package contains all the database-related stuff for the project. We use the
- [Migrations](#migrations)
- [Creating/Applying Migrations](#creatingapplying-migrations)
- [Prisma Studio](#prisma-studio)
- [Fixing failed production migrations](#fixing-failed-production-migrations)

## Setup

Expand Down Expand Up @@ -59,3 +60,15 @@ bun db:studio
```

This will open a web interface where you can view and edit your database records.

### Fixing failed production migrations

1. Get the production database URL from the Vercel storage dashboard
2. Change the DATABASE_PRISMA_URL in your .env file to the production database URL
3. Run the following command to resolve the migration

```sh
bun prisma migrate resolve --rolled-back <migration name> --schema=./packages/db/prisma/schema.prisma
```

4. Change the DATABASE_PRISMA_URL in your .env file back to the development database URL
Original file line number Diff line number Diff line change
@@ -1,11 +1,7 @@
/*
Warnings:

- Added the required column `phoneNumber` to the `User` table without a default value. This is not possible if the table is not empty.

*/
-- AlterTable
ALTER TABLE "User" ADD COLUMN "phoneNumber" TEXT NOT NULL;
ALTER TABLE "User" ADD COLUMN "phoneNumber" TEXT NOT NULL DEFAULT '';
-- AlterTable remove default value
ALTER TABLE "User" ALTER COLUMN "phoneNumber" DROP DEFAULT;

-- AlterTable
ALTER TABLE "_songWriters" ADD CONSTRAINT "_songWriters_AB_pkey" PRIMARY KEY ("A", "B");
Expand Down
3 changes: 3 additions & 0 deletions packages/db/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,6 @@
import { PrismaClient } from "@prisma/client";

export const prisma = new PrismaClient();

// Re-export prisma types and enums here if needed for other packages
export { Role } from "@prisma/client";
2 changes: 2 additions & 0 deletions packages/trpc/src/internal/router.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { getAdminViewProcedure } from "../procedures/admin-view";
import {
deleteAccountProcedure,
refreshSessionProcedure,
signInProcedure,
signOutProcedure,
signUpProcedure,
Expand All @@ -26,6 +27,7 @@ export const appRouter = createTRPCRouter({
signIn: signInProcedure,
signOut: signOutProcedure,
signUp: signUpProcedure,
refreshSession: refreshSessionProcedure,
onboarding: onboardingProcedure,
deleteAccount: deleteAccountProcedure,
authenticatedUser: getAuthenticatedUserProcedure,
Expand Down
29 changes: 29 additions & 0 deletions packages/trpc/src/procedures/auth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -180,3 +180,32 @@ export const deleteAccountProcedure = authenticatedProcedureBuilder.mutation(
};
},
);

export const refreshSessionProcedure = authenticatedProcedureBuilder.mutation(
async ({ ctx }) => {
const sessionId = ctx.session.sessionId;

const updatedSession = await ctx.prisma.session.update({
where: {
sessionId: sessionId,
},
data: {
expiresAt: getNewSessionExpirationDate(),
},
select: {
sessionId: true,
expiresAt: true,
},
});

ctx.cookiesService.setSessionCookie(
updatedSession.sessionId,
updatedSession.expiresAt,
);

return {
message: "Session refreshed",
expiresAt: updatedSession.expiresAt,
};
},
);
43 changes: 40 additions & 3 deletions packages/trpc/src/procedures/user.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,35 @@
import type { Role } from "@good-dog/db";

import { baseProcedureBuilder } from "../internal/init";
import { authenticatedProcedureBuilder } from "../middleware/authentictated";

// Represents the object we send to the frontend for an authenticated user
interface UserWithSession {
userId: string;
firstName: string;
lastName: string;
email: string;
phoneNumber: string;
role: Role;
session: {
expiresAt: Date;
refreshRequired: boolean;
};
}

export const getAuthenticatedUserProcedure =
authenticatedProcedureBuilder.query(({ ctx }) => {
return ctx.session.user;
const result: UserWithSession = {
...ctx.session.user,
session: {
expiresAt: ctx.session.expiresAt,
refreshRequired:
// Refresh session if it expires in less than 29 days
ctx.session.expiresAt.getTime() - Date.now() < 60_000 * 60 * 24 * 29,
},
};

return result;
});

export const getUserProcedure = baseProcedureBuilder.query(async ({ ctx }) => {
Expand All @@ -17,7 +43,8 @@ export const getUserProcedure = baseProcedureBuilder.query(async ({ ctx }) => {
where: {
sessionId: sessionId.value,
},
include: {
select: {
expiresAt: true,
user: {
select: {
userId: true,
Expand All @@ -36,5 +63,15 @@ export const getUserProcedure = baseProcedureBuilder.query(async ({ ctx }) => {
return null;
}

return sessionOrNull.user;
const result: UserWithSession = {
...sessionOrNull.user,
session: {
expiresAt: sessionOrNull.expiresAt,
refreshRequired:
// Refresh session if it expires in less than 29 days
sessionOrNull.expiresAt.getTime() - Date.now() < 60_000 * 60 * 24 * 29,
},
};

return result;
});
2 changes: 1 addition & 1 deletion packages/ui/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@
"format": "prettier --check . --ignore-path ../../.gitignore",
"lint": "eslint",
"typecheck": "tsc --noEmit --emitDeclarationOnly false",
"ui-add": "bunx shadcn add && prettier shad --write --list-different"
"ui:add": "bunx shadcn add && prettier shad --write --list-different"
},
"prettier": "@good-dog/prettier",
"devDependencies": {
Expand Down
19 changes: 19 additions & 0 deletions tests/api/auth.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -254,4 +254,23 @@ describe("auth", () => {
);
expect(mockCookies.delete).toBeCalledWith("sessionId");
});

test("auth/refreshSession", async () => {
const session = await createSession();
mockCookies.set("sessionId", session.sessionId);
mockCookies.set.mockRestore();

const refreshSessionResponse = await $api.refreshSession();

expect(refreshSessionResponse.message).toEqual("Session refreshed");
expect(mockCookies.set).toBeCalledWith("sessionId", session.sessionId, {
httpOnly: true,
secure: true,
sameSite: "lax",
path: "/",
expires: expect.any(Date),
});

await cleanupAccount();
});
});
32 changes: 31 additions & 1 deletion tests/api/get-user.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,23 @@ describe("get user", () => {
},
},
}),
prisma.user.create({
data: {
userId: "gavin-user-id",
email: "[email protected]",
phoneNumber: "4173843849",
hashedPassword: "xxxx",
firstName: "Gavin",
lastName: "Normand",
role: "MEDIA_MAKER",
sessions: {
create: {
sessionId: "gavin-session-id",
expiresAt: new Date(Date.now() + 600_000),
},
},
},
}),
prisma.user.create({
data: {
userId: "isabelle-user-id",
Expand Down Expand Up @@ -106,7 +123,20 @@ describe("get user", () => {
expect(user).not.toBeNull();
if (user) {
expect(user.email).toEqual("[email protected]");
expect(user.phoneNumber).toEqual("1234567890");
expect(user.session.refreshRequired).toBeFalse();
}
});

test("User with session.refreshRequired", async () => {
cookies.set("sessionId", "gavin-session-id");

const user = await $api.user();

expect(user).not.toBeNull();
if (user) {
expect(user.email).toEqual("[email protected]");
expect(user.session.refreshRequired).toBeTrue();
expect(user.phoneNumber).toEqual("4173843849");
}
});
});
15 changes: 4 additions & 11 deletions turbo.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
{
"$schema": "https://turbo.build/schema.json",
"ui": "tui",
"tasks": {
"topo": {
"dependsOn": ["^topo"]
Expand Down Expand Up @@ -34,10 +33,7 @@
"clean": {
"cache": false
},
"//#clean": {
"cache": false
},
"ui-add": {
"ui:add": {
"cache": false,
"interactive": true
},
Expand All @@ -46,8 +42,7 @@
"interactive": true
},
"generate": {
"cache": false,
"interactive": false
"cache": false
},
"migrate": {
"cache": false,
Expand All @@ -62,12 +57,10 @@
"interactive": true
},
"studio": {
"cache": false,
"interactive": true
"cache": false
},
"seed": {
"cache": false,
"interactive": false
"cache": false
}
},
"globalEnv": [
Expand Down