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

fix(destory-session): testing destroy session for all devices using supabase #833

Open
wants to merge 3 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.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
-- CreateTable
CREATE TABLE "Session" (
"id" TEXT NOT NULL,
"expires" TIMESTAMP(3),
"userId" TEXT,
"data" JSONB NOT NULL,
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"updatedAt" TIMESTAMP(3) NOT NULL,

CONSTRAINT "Session_pkey" PRIMARY KEY ("id")
);
31 changes: 21 additions & 10 deletions app/database/schema.prisma
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
datasource db {
provider = "postgresql"
url = env("DATABASE_URL")
provider = "postgresql"
url = env("DATABASE_URL")
directUrl = env("DIRECT_URL")
}

Expand Down Expand Up @@ -159,7 +159,7 @@ model Tag {
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt

//@@unique([lower(name), organizationId]) //prisma doesnt support case insensitive unique index yet
//@@unique([lower(name), organizationId]) //prisma doesnt support case insensitive unique index yet
}

model Note {
Expand Down Expand Up @@ -274,7 +274,7 @@ model Location {

assets Asset[]

// @@unique([lower(name), organizationId]) //prisma doesnt support case insensitive unique index yet
// @@unique([lower(name), organizationId]) //prisma doesnt support case insensitive unique index yet
}

// Master data for roles
Expand All @@ -297,17 +297,17 @@ model TeamMember {
id String @id @unique @default(cuid())
name String

organization Organization @relation(fields: [organizationId], references: [id], onUpdate: Cascade)
organizationId String
organization Organization @relation(fields: [organizationId], references: [id], onUpdate: Cascade)
organizationId String
custodies Custody[]
receivedInvites Invite[]
user User? @relation(fields: [userId], references: [id], onUpdate: Cascade)
user User? @relation(fields: [userId], references: [id], onUpdate: Cascade)
userId String?

createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
deletedAt DateTime?
bookings Booking[]
bookings Booking[]
}

model Custody {
Expand Down Expand Up @@ -550,13 +550,13 @@ model Booking {
name String
status BookingStatus @default(DRAFT)

activeSchedulerReference String?
activeSchedulerReference String?

// Relationships
creator User @relation("creator", fields: [creatorId], references: [id], onDelete: Cascade, onUpdate: Cascade)
creatorId String

custodianUser User? @relation("custodian", fields: [custodianUserId], references: [id], onDelete: Cascade, onUpdate: Cascade)
custodianUser User? @relation("custodian", fields: [custodianUserId], references: [id], onDelete: Cascade, onUpdate: Cascade)
custodianUserId String?

custodianTeamMember TeamMember? @relation(fields: [custodianTeamMemberId], references: [id], onDelete: Cascade, onUpdate: Cascade)
Expand All @@ -573,3 +573,14 @@ model Booking {
from DateTime? @db.Timestamptz(3)
to DateTime? @db.Timestamptz(3)
}

model Session {
id String @id @default(cuid())

expires DateTime?
userId String?
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What do you think about User link here to prevent phantom userId?

data Json
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggestion: normalise instead of hiding in a JSONB col?

Given the schema below:

 email: z.string(),
 userId: z.string(),
 expiresAt: z.number(),
 expiresIn: z.number(),
 accessToken: z.string(),
 refreshToken: z.string(),

we could have a col for:
accessToken, refreshToken


Later in the createDatabaseSessionStorage implementation, we could use the expiresAt from the supabase auth token to populate the expires col of this table?
Then, you control this settings from supabase auth dashboard.


createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
}
38 changes: 25 additions & 13 deletions app/routes/_layout+/settings.account.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import Input from "~/components/forms/input";
import { Button } from "~/components/shared/button";
import PasswordResetForm from "~/components/user/password-reset-form";
import ProfilePicture from "~/components/user/profile-picture";
import { db } from "~/database";

import { useUserData } from "~/hooks";
import { sendResetPasswordLink } from "~/modules/auth";
Expand Down Expand Up @@ -48,22 +49,33 @@ export async function action({ context, request }: ActionFunctionArgs) {
if (formData.get("intent") === "resetPassword") {
const email = formData.get("email") as string;

const { error } = await sendResetPasswordLink(email);
const data = await db.session.findMany({
where: { userId: authSession.userId },
});

if (error) {
return json(
{
message: "Unable to send password reset link",
email: null,
},
{ status: 500 }
);
}
const updatedData = await db.session.updateMany({
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

shouldn't we delete all existing sessions for this userId and then create a new one + save it in the context before redirect?

where: { id: { in: data.map((item) => item.id) } },
data: { data: {}, userId: null, expires: null },
});

console.log(updatedData);

// const { error } = await sendResetPasswordLink(email);

// if (error) {
// return json(
// {
// message: "Unable to send password reset link",
// email: null,
// },
// { status: 500 }
// );
// }

/** Logout user after 3 seconds */
await delay(2000);
context.destroySession();
return redirect("/login");
// await delay(2000);
// context.destroySession();
return redirect("/settings/account");
}

/** Handle the use update */
Expand Down
16 changes: 13 additions & 3 deletions server/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ import { ShelfStackError } from "~/utils/error";

import { logger } from "./logger";
import { cache, protect, refreshSession } from "./middleware";
import { authSessionKey } from "./session";
import { authSessionKey, createDatabaseSessionStorage } from "./session";
import type { FlashData, SessionData } from "./session";

/** For some reason the globals like File only work on production build
Expand Down Expand Up @@ -64,9 +64,19 @@ app.use(
session({
autoCommit: true,
createSessionStorage() {
const sessionStorage = createCookieSessionStorage({
// const sessionStorage = createCookieSessionStorage({
// cookie: {
// name: "__authSession",
// httpOnly: true,
// path: "/",
// sameSite: "lax",
// secrets: [env.SESSION_SECRET],
// secure: env.NODE_ENV === "production",
// },
// });
const sessionStorage = createDatabaseSessionStorage({
cookie: {
name: "__authSession",
name: "__authenticationSession",
httpOnly: true,
path: "/",
sameSite: "lax",
Expand Down
5 changes: 5 additions & 0 deletions server/middleware.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,9 +25,14 @@ export function protect({
if (isPublic) {
return next();
}
console.log("Timer start >>>>>>>>>>>>>>>>");
console.time("session");

//@ts-expect-error fixed soon
const session = getSession<SessionData, FlashData>(c);
const auth = session.get(authSessionKey);
console.log("Timer end >>>>>>>>>>>>>>>>>>>>>>>");
console.timeEnd("session");

if (!auth) {
session.flash(
Expand Down
52 changes: 52 additions & 0 deletions server/session.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,8 @@
import type { CookieOptions } from "@remix-run/node";
import { createSessionStorage } from "@remix-run/node";
import { z } from "zod";
import { db } from "~/database";

export type AuthSession = {
accessToken: string;
refreshToken: string;
Expand All @@ -14,3 +19,50 @@ export type SessionData = {
};

export type FlashData = { errorMessage: string };

const sessionSchema = z
.object({
auth: z.object({
email: z.string(),
userId: z.string(),
expiresAt: z.number(),
expiresIn: z.number(),
accessToken: z.string(),
refreshToken: z.string(),
}),
})
.partial();

export function createDatabaseSessionStorage({
cookie,
}: {
cookie: CookieOptions & {
name?: string;
};
}) {
return createSessionStorage<SessionData, FlashData>({
cookie,
async createData(data, expires) {
const parsedData = sessionSchema.parse(data);
const createdSession = await db.session.create({
data: { data: parsedData, expires, userId: parsedData.auth?.userId },
});
return createdSession.id;
},
async readData(id) {
const data = await db.session.findFirst({ where: { id } });
return sessionSchema.parse(data?.data ?? {});
},
async updateData(id, data, expires) {
const parsedData = sessionSchema.parse(data);

await db.session.update({
where: { id },
data: { data: parsedData, expires, userId: parsedData.auth?.userId },
});
},
async deleteData(id) {
await db.session.delete({ where: { id } });
},
});
}