Skip to content

Commit

Permalink
Merge pull request #41 from GenerateNU/32-comp-10-preference-form
Browse files Browse the repository at this point in the history
some changes and refactoring
  • Loading branch information
TylerSchaefer4 authored Oct 19, 2023
2 parents 12781e5 + 3374f7a commit 9908b79
Show file tree
Hide file tree
Showing 5 changed files with 62 additions and 57 deletions.
32 changes: 16 additions & 16 deletions prisma/schema.prisma
Original file line number Diff line number Diff line change
Expand Up @@ -19,31 +19,31 @@ 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
// education String
// 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 {
Expand Down
45 changes: 28 additions & 17 deletions src/models/users.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 },
Expand Down Expand Up @@ -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");
Expand All @@ -103,31 +115,30 @@ 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 = {
email: user.email as string,
id: user.id as number,
firstName: user.firstName,
lastName: user.lastName,
}
};

return userDetails;
}

public async isUserInDatabase(email: string): Promise<boolean> {
const userExists = this.usersDB.findUnique({
where: {
email: email
}
})

return userExists instanceof Users
email: email,
},
});
return userExists instanceof Users;
}
}
}
8 changes: 4 additions & 4 deletions src/pages/api/auth/[...nextauth].ts
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down
32 changes: 13 additions & 19 deletions src/pages/api/users/[id].ts
Original file line number Diff line number Diff line change
Expand Up @@ -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();

Expand All @@ -19,17 +17,15 @@ export default async function handler(
res: NextApiResponse<Message>
) {
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);
}
Expand All @@ -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) });
Expand All @@ -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 = [];

Expand All @@ -79,6 +63,7 @@ async function updateUser(req: NextApiRequest, res: NextApiResponse) {
missProp.push(prop);
}
}

if (missProp.length > 0) {
return res
.status(400)
Expand Down Expand Up @@ -139,7 +124,7 @@ async function getUser(
req: NextApiRequest,
res: NextApiResponse<Message | InsensitiveUserInformation>
) {
let id = Number(req.query.id);
const id = Number(req.query.id);

try {
const userInfo = await persistentUserInstance.getUserById(id);
Expand All @@ -151,3 +136,12 @@ async function getUser(
return res.status(403).send({ message: String(error) });
}
}

async function deleteUser(
req: NextApiRequest,
res: NextApiResponse<Message | InsensitiveUserInformation>,
session: any
) {
const id = Number(req.query.id)
await persistentUserInstance.deleteUser(id)
}
2 changes: 1 addition & 1 deletion src/pages/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import { signIn } from "next-auth/react";
export default function Home() {
function button(text: string) {
return (
<button className="h-[60px] w-[20vw] lg:w-[11vw] ml-5 bg-bxBrand text-white rounded-3xl hover:bg-bxBrandLight transition ease-in duration-75">
<button className="h-[60px] w-[20vw] lg:w-[11vw] ml-5 text-white rounded-3xl transition ease-in duration-75">
{text}
</button>
);
Expand Down

0 comments on commit 9908b79

Please sign in to comment.