Skip to content

Commit

Permalink
New schemas for login (#18)
Browse files Browse the repository at this point in the history
* mirgations

* attempt to fix env

* fix type errs

* syntax err in migration

* fix syntax errs part 2

* create group schema

* fix types

* add createdAt to groupInvite

* add id to group invite

---------

Co-authored-by: DamianUduevbo <[email protected]>
  • Loading branch information
owens1127 and DamianUduevbo authored Nov 7, 2024
1 parent 58c66a4 commit f13e74c
Show file tree
Hide file tree
Showing 13 changed files with 195 additions and 75 deletions.
Binary file modified bun.lockb
Binary file not shown.
16 changes: 9 additions & 7 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -15,14 +15,15 @@
"__DATABASE__________": "",
"db:up": "docker-compose -f compose.yml up -d",
"db:down": "docker-compose -f compose.yml down",
"db:push": "turbo run -F @good-dog/db push",
"db:push": "dotenv -e .env -- turbo run -F @good-dog/db push",
"db:generate": "turbo run -F @good-dog/db generate",
"db:migrate": "turbo run -F @good-dog/db migrate",
"db:migrate:reset": "turbo run -F @good-dog/db migrate:reset",
"db:migrate:prod": "turbo run -F @good-dog/db migrate:prod",
"db:migrate:check": "turbo run -F @good-dog/db migrate:check --",
"db:studio": "turbo run -F @good-dog/db studio",
"db:seed": "turbo run -F @good-dog/db seed",
"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:migrate:prod": "dotenv -e .env -- turbo run -F @good-dog/db migrate:prod",
"db:migrate:check": "dotenv -e .env -- turbo run -F @good-dog/db migrate:check --",
"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_______": "",
"dev": "bun db:up && turbo run dev",
"dev:web": "turbo run -F @good-dog/web dev",
Expand All @@ -43,6 +44,7 @@
"devDependencies": {
"@good-dog/prettier": "workspace:*",
"@turbo/gen": "^2.1.2",
"dotenv-cli": "^7.4.2",
"turbo": "2.1.2",
"typescript": "5.4.5"
},
Expand Down
1 change: 1 addition & 0 deletions packages/db/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
"studio": "prisma studio",
"generate": "prisma generate",
"migrate": "prisma migrate dev",
"migrate:create": "prisma migrate dev --create-only",
"migrate:reset": "prisma migrate reset",
"migrate:prod": "prisma migrate deploy",
"migrate:check": "bun prisma migrate diff --exit-code --from-migrations ./prisma/migrations --to-schema-datamodel ./prisma/schema.prisma --shadow-database-url",
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
-- CreateEnum
CREATE TYPE "Role" AS ENUM ('MUSICIAN', 'MEDIA_MAKER', 'ADMIN');

-- AlterTable
ALTER TABLE "User"
RENAME COLUMN "name" TO "firstName";

-- AlterTable
ALTER TABLE "User"
ADD COLUMN "lastName" TEXT NOT NULL DEFAULT '',
ADD COLUMN "role" "Role" NOT NULL DEFAULT 'MEDIA_MAKER';

-- RemoveDefault
ALTER TABLE "User"
ALTER COLUMN "lastName" DROP DEFAULT,
ALTER COLUMN "role" DROP DEFAULT;
47 changes: 47 additions & 0 deletions packages/db/prisma/migrations/20241103222852_groups/migration.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
-- CreateTable
CREATE TABLE "Group" (
"groupId" TEXT NOT NULL,
"name" TEXT NOT NULL,
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"updatedAt" TIMESTAMP(3) NOT NULL,

CONSTRAINT "Group_pkey" PRIMARY KEY ("groupId")
);

-- CreateTable
CREATE TABLE "GroupInvite" (
"id" TEXT NOT NULL,
"groupId" TEXT NOT NULL,
"intitiatorId" TEXT NOT NULL,
"email" TEXT NOT NULL,
"firstName" TEXT NOT NULL,
"lastName" TEXT NOT NULL,
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP
);

-- CreateTable
CREATE TABLE "_GroupToUser" (
"A" TEXT NOT NULL,
"B" TEXT NOT NULL
);

-- CreateIndex
CREATE UNIQUE INDEX "GroupInvite_groupId_email_key" ON "GroupInvite"("groupId", "email");

-- CreateIndex
CREATE UNIQUE INDEX "_GroupToUser_AB_unique" ON "_GroupToUser"("A", "B");

-- CreateIndex
CREATE INDEX "_GroupToUser_B_index" ON "_GroupToUser"("B");

-- AddForeignKey
ALTER TABLE "GroupInvite" ADD CONSTRAINT "GroupInvite_groupId_fkey" FOREIGN KEY ("groupId") REFERENCES "Group"("groupId") ON DELETE CASCADE ON UPDATE CASCADE;

-- AddForeignKey
ALTER TABLE "GroupInvite" ADD CONSTRAINT "GroupInvite_intitiatorId_fkey" FOREIGN KEY ("intitiatorId") REFERENCES "User"("id") ON DELETE CASCADE ON UPDATE CASCADE;

-- AddForeignKey
ALTER TABLE "_GroupToUser" ADD CONSTRAINT "_GroupToUser_A_fkey" FOREIGN KEY ("A") REFERENCES "Group"("groupId") ON DELETE CASCADE ON UPDATE CASCADE;

-- AddForeignKey
ALTER TABLE "_GroupToUser" ADD CONSTRAINT "_GroupToUser_B_fkey" FOREIGN KEY ("B") REFERENCES "User"("id") ON DELETE CASCADE ON UPDATE CASCADE;
54 changes: 44 additions & 10 deletions packages/db/prisma/schema.prisma
Original file line number Diff line number Diff line change
Expand Up @@ -5,29 +5,63 @@
// Try Prisma Accelerate: https://pris.ly/cli/accelerate-init

generator client {
provider = "prisma-client-js"
binaryTargets = ["native", "debian-openssl-3.0.x"]
provider = "prisma-client-js"
previewFeatures = ["omitApi"]
binaryTargets = ["native", "debian-openssl-3.0.x"]
}

datasource db {
provider = "postgresql"
url = env("DATABASE_PRISMA_URL")
}

enum Role {
MUSICIAN
MEDIA_MAKER
ADMIN
}

model User {
id String @id @default(uuid())
email String @unique
name String
hashedPassword String @map("password")
userId String @id @default(uuid()) @map("id")
email String @unique
firstName String
lastName String
hashedPassword String @map("password")
role Role
groups Group[]
sessions Session[]
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
sentInvites GroupInvite[]
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
}

model Session {
id String @id @default(uuid())
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
sessionId String @id @default(uuid()) @map("id")
userId String
createdAt DateTime @default(now())
expiresAt DateTime
user User @relation(fields: [userId], references: [userId], onDelete: Cascade)
}

model Group {
groupId String @id @default(uuid())
name String
users User[]
invites GroupInvite[]
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
}

model GroupInvite {
inviteId String @default(cuid()) @map("id")
groupId String
intitiatorId String
email String
firstName String
lastName String
group Group @relation(fields: [groupId], references: [groupId], onDelete: Cascade)
intitiator User @relation(fields: [intitiatorId], references: [userId], onDelete: Cascade)
createdAt DateTime @default(now())
@@unique([groupId, email])
}
34 changes: 20 additions & 14 deletions packages/db/prisma/seed.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ async function main() {
update: {
sessions: {
update: {
where: { id: "23" },
where: { sessionId: "23" },
data: {
expiresAt: new Date(
new Date().setFullYear(new Date().getFullYear() + 10),
Expand All @@ -20,13 +20,15 @@ async function main() {
},
},
create: {
id: "7",
userId: "7",
email: "[email protected]",
name: "Alice",
firstName: "Alice",
lastName: "Smith",
role: "MEDIA_MAKER",
hashedPassword: await hashPassword("alicePassword"),
sessions: {
create: {
id: "23",
sessionId: "23",
expiresAt: new Date(
new Date().setFullYear(new Date().getFullYear() + 10),
),
Expand All @@ -42,15 +44,15 @@ async function main() {
sessions: {
updateMany: [
{
where: { id: "12" },
where: { sessionId: "12" },
data: {
expiresAt: new Date(
new Date().setFullYear(new Date().getFullYear() - 1),
),
},
},
{
where: { id: "45" },
where: { sessionId: "45" },
data: {
expiresAt: new Date(
new Date().setFullYear(new Date().getFullYear() + 10),
Expand All @@ -61,21 +63,23 @@ async function main() {
},
},
create: {
id: "9",
userId: "9",
email: "[email protected]",
name: "Bob Jones",
firstName: "Bob",
lastName: "Jones",
role: "MUSICIAN",
hashedPassword: await hashPassword("bobPassword"),
sessions: {
createMany: {
data: [
{
id: "12",
sessionId: "12",
expiresAt: new Date(
new Date().setFullYear(new Date().getFullYear() - 1),
),
},
{
id: "45",
sessionId: "45",
expiresAt: new Date(
new Date().setFullYear(new Date().getFullYear() + 10),
),
Expand All @@ -92,7 +96,7 @@ async function main() {
update: {
sessions: {
update: {
where: { id: "78" },
where: { sessionId: "78" },
data: {
expiresAt: new Date(
new Date().setFullYear(new Date().getFullYear() - 1),
Expand All @@ -102,13 +106,15 @@ async function main() {
},
},
create: {
id: "56",
userId: "56",
email: "[email protected]",
name: "Eve Smith",
firstName: "Eve",
lastName: "Brown",
role: "MEDIA_MAKER",
hashedPassword: await hashPassword("evePassword"),
sessions: {
create: {
id: "78",
sessionId: "78",
expiresAt: new Date(
new Date().setFullYear(new Date().getFullYear() - 1),
),
Expand Down
13 changes: 4 additions & 9 deletions packages/trpc/src/internal/init.ts
Original file line number Diff line number Diff line change
Expand Up @@ -60,17 +60,12 @@ export const authenticatedProcedureBuilder = baseProcedureBuilder.use(

const sessionOrNull = await ctx.prisma.session.findUnique({
where: {
id: sessionId.value,
sessionId: sessionId.value,
},
include: {
user: {
select: {
id: true,
email: true,
name: true,
sessions: true,
createdAt: true,
updatedAt: true,
omit: {
hashedPassword: true,
},
},
},
Expand Down Expand Up @@ -101,7 +96,7 @@ export const notAuthenticatedProcedureBuilder = baseProcedureBuilder.use(

const sessionOrNull = await ctx.prisma.session.findUnique({
where: {
id: sessionId.value,
sessionId: sessionId.value,
},
});

Expand Down
18 changes: 11 additions & 7 deletions packages/trpc/src/procedures/auth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,9 +15,11 @@ const getNewSessionExpirationDate = () =>
export const signUpProcedure = notAuthenticatedProcedureBuilder
.input(
z.object({
firstName: z.string(),
lastName: z.string(),
role: z.enum(["MEDIA_MAKER", "MUSICIAN"]),
email: z.string().email(),
password: z.string(),
name: z.string(),
}),
)
.mutation(async ({ ctx, input }) => {
Expand All @@ -38,7 +40,9 @@ export const signUpProcedure = notAuthenticatedProcedureBuilder

const userWithSession = await ctx.prisma.user.create({
data: {
name: input.name,
firstName: input.firstName,
lastName: input.lastName,
role: input.role,
email: input.email,
hashedPassword: hashedPassword,
sessions: {
Expand All @@ -61,7 +65,7 @@ export const signUpProcedure = notAuthenticatedProcedureBuilder
});
}

setSessionCookie(session.id, session.expiresAt);
setSessionCookie(session.sessionId, session.expiresAt);

return {
message: `Successfully signed up and logged in as ${input.email}`,
Expand Down Expand Up @@ -103,14 +107,14 @@ export const signInProcedure = notAuthenticatedProcedureBuilder
data: {
user: {
connect: {
id: user.id,
userId: user.userId,
},
},
expiresAt: getNewSessionExpirationDate(),
},
});

setSessionCookie(session.id, session.expiresAt);
setSessionCookie(session.sessionId, session.expiresAt);

return {
message: `Successfully logged in as ${input.email}`,
Expand All @@ -121,7 +125,7 @@ export const signOutProcedure = authenticatedProcedureBuilder.mutation(
async ({ ctx }) => {
await ctx.prisma.session.delete({
where: {
id: ctx.session.id,
sessionId: ctx.session.sessionId,
},
});

Expand All @@ -137,7 +141,7 @@ export const deleteAccountProcedure = authenticatedProcedureBuilder.mutation(
async ({ ctx }) => {
await ctx.prisma.user.delete({
where: {
id: ctx.session.userId,
userId: ctx.session.userId,
},
});

Expand Down
Loading

0 comments on commit f13e74c

Please sign in to comment.