From 3374f7a40fa6f44f0fc30f2d7ed06aa0848e618a Mon Sep 17 00:00:00 2001 From: Mario Gonzalez Date: Wed, 11 Oct 2023 15:18:21 -0400 Subject: [PATCH] some changes and refactoring --- prisma/schema.prisma | 32 ++++++++++---------- src/models/users.ts | 45 ++++++++++++++++++----------- src/pages/api/auth/[...nextauth].ts | 8 ++--- src/pages/api/users/[id].ts | 32 +++++++++----------- src/pages/index.tsx | 2 +- 5 files changed, 62 insertions(+), 57 deletions(-) diff --git a/prisma/schema.prisma b/prisma/schema.prisma index 558d55b..679441d 100644 --- a/prisma/schema.prisma +++ b/prisma/schema.prisma @@ -19,14 +19,14 @@ datasource db { } model User { - id Int @id @default(autoincrement()) - firstName String - lastName String - dob DateTime - email String? @unique - phoneNumber String? @unique - registered Boolean @default(false) - isAdmin Boolean @default(false) // CLIENT ACCESS ONLY + id Int @id @default(autoincrement()) + firstName String + lastName String + dob DateTime + email String? @unique + phoneNumber String? @unique + registered Boolean @default(false) + isAdmin Boolean @default(false) // CLIENT ACCESS ONLY // gender String // age Int // ethnicity String @@ -34,16 +34,16 @@ model User { // maritalStatus String // languages String[] // employmentStatus String? - householdIncome Float? + householdIncome Float? // livingStatus String? - // accounts Account[] - // sessions Session[] - lessonsCompleted Int[] + // accounts Account[] + // sessions Session[] + lessonsCompleted Int[] subModuleQuizScores Json - moduleExamScores Json - progress Progress[] - intakeTests IntakeTest[] // Probably get rid of this - preferences String[] + moduleExamScores Json + progress Progress[] + intakeTests IntakeTest[] // Probably get rid of this + preferences String[] } model IntakeTest { diff --git a/src/models/users.ts b/src/models/users.ts index 2468212..c6ac0df 100644 --- a/src/models/users.ts +++ b/src/models/users.ts @@ -19,7 +19,7 @@ export default class Users { //updates the user of the given id with the given data given of type object and returns the userinformation // which is shown nowhere or returns an err - public async updateUserById(id: number, updatedData: object) { + public async updateUserById(id: number, updatedData: UserData) { try { const UserInformation: User | null = await this.usersDB.update({ where: { id: id }, @@ -73,18 +73,30 @@ export default class Users { } } - public async signUpProviderDetails(userData: UserData ) { - await this.usersDB.create({data: userData}); + public async signUpProviderDetails(userData: UserData) { + const defaultData = this.setDefaultAttributes(userData); + await this.usersDB.create({ data: defaultData }); } private setDefaultAttributes(data: UserData): UserData { return { ...data, // verified: true, // TODO: change this and add admin page - createdAt: new Date(), + registered: false, + isAdmin: false, + subModuleQuizScores: [], + moduleExamScores: [], }; } + public async deleteUser(id: number) { + await this.usersDB.delete({ + where: { + id: id, + }, + }); + } + private validateEmail(email: string) { if (!isEmail.validate(email)) { throw new Error("email must be in the proper format"); @@ -103,12 +115,12 @@ export default class Users { } public async getUser(email: string) { - const user = await this.usersDB.findUnique({ - where:{email: email} - }) - - if(user === null){ - throw new Error("user not found") + const user = await this.usersDB.findUnique({ + where: { email: email }, + }); + + if (user === null) { + throw new Error("user not found"); } const userDetails: UserReturnType = { @@ -116,7 +128,7 @@ export default class Users { id: user.id as number, firstName: user.firstName, lastName: user.lastName, - } + }; return userDetails; } @@ -124,10 +136,9 @@ export default class Users { public async isUserInDatabase(email: string): Promise { const userExists = this.usersDB.findUnique({ where: { - email: email - } - }) - - return userExists instanceof Users + email: email, + }, + }); + return userExists instanceof Users; } -} \ No newline at end of file +} diff --git a/src/pages/api/auth/[...nextauth].ts b/src/pages/api/auth/[...nextauth].ts index 7bd005c..748bbbe 100644 --- a/src/pages/api/auth/[...nextauth].ts +++ b/src/pages/api/auth/[...nextauth].ts @@ -13,14 +13,14 @@ export const authOptions: NextAuthOptions = { ], callbacks: { async signIn({ user }) { - if (user.email) { - if(await persistentUserInstance.isUserInDatabase(user.email)) { + const isUserinDB = await persistentUserInstance.isUserInDatabase(user.email) + if(isUserinDB === false) { const dummyUserData: UserData = { email: user.email, phoneNumber: "null", - firstName: user.name as string, - lastName: user.name as string, + firstName: user.name?.split(" ")[0] as string, + lastName: user.name?.split(" ")[1] as string, dob: new Date(), }; await persistentUserInstance.signUpProviderDetails(dummyUserData); diff --git a/src/pages/api/users/[id].ts b/src/pages/api/users/[id].ts index 32304a1..72b4400 100644 --- a/src/pages/api/users/[id].ts +++ b/src/pages/api/users/[id].ts @@ -3,8 +3,6 @@ import type { NextApiRequest, NextApiResponse } from "next"; import persistentUserInstance from "../../../../lib/persistentUserInstance"; import { getServerSession } from "next-auth"; import { authOptions } from "../auth/[...nextauth]"; -import Users from "@/models/users"; -import { error } from "console"; import { PrismaClient, User } from "@prisma/client"; const prisma = new PrismaClient(); @@ -19,17 +17,15 @@ export default async function handler( res: NextApiResponse ) { const session = await getServerSession(req, res, authOptions); - console.log("hello"); const supportedRequestMethods: { [key: string]: Function } = { GET: getUser, + DELETE: deleteUser, // these two below are currently seperated with differnet functions in case there is any // edits needed to be made to a patch or put to ensure // a more secure and validated request other than the built in prisma checks PUT: updateUser, PATCH: updateUserPatch, }; - console.log(req.body); - if (req.method) { return supportedRequestMethods[req.method](req, res, session); } @@ -45,7 +41,7 @@ async function updateUser(req: NextApiRequest, res: NextApiResponse) { try { id = Number(req.query.id); if (typeof id !== "number") { - throw Error("plesae input number"); + throw Error("please input number"); } } catch (error) { return res.status(403).send({ message: String(error) }); @@ -57,19 +53,7 @@ async function updateUser(req: NextApiRequest, res: NextApiResponse) { "dob", "phoneNumber", "email", - "emailVerified", - "gender", - "age", - "ethnicity", - "education", - "maritalStatus", - "password", - "verified", - "isAdmin", - "languages", - "employmentStatus", "householdIncome", - "livingStatus", ]; const missProp = []; @@ -79,6 +63,7 @@ async function updateUser(req: NextApiRequest, res: NextApiResponse) { missProp.push(prop); } } + if (missProp.length > 0) { return res .status(400) @@ -139,7 +124,7 @@ async function getUser( req: NextApiRequest, res: NextApiResponse ) { - let id = Number(req.query.id); + const id = Number(req.query.id); try { const userInfo = await persistentUserInstance.getUserById(id); @@ -151,3 +136,12 @@ async function getUser( return res.status(403).send({ message: String(error) }); } } + +async function deleteUser( + req: NextApiRequest, + res: NextApiResponse, + session: any +) { + const id = Number(req.query.id) + await persistentUserInstance.deleteUser(id) +} diff --git a/src/pages/index.tsx b/src/pages/index.tsx index ff07d0e..1613688 100644 --- a/src/pages/index.tsx +++ b/src/pages/index.tsx @@ -3,7 +3,7 @@ import { signIn } from "next-auth/react"; export default function Home() { function button(text: string) { return ( - );