Skip to content

Commit

Permalink
feat: refactored user model lots of improvements as well for auth
Browse files Browse the repository at this point in the history
  • Loading branch information
Siddharth9890 committed Feb 14, 2024
1 parent 0411c83 commit 8103f37
Show file tree
Hide file tree
Showing 21 changed files with 399 additions and 595 deletions.
11 changes: 7 additions & 4 deletions db.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { Sequelize } from "sequelize";
import dotenv from "dotenv";

dotenv.config();
const connection = `postgres://${process.env.DATABASE_USER_NAME}:${process.env.DATABASE_PASSWORD}@${process.env.DATABASE_HOST}/${process.env.DATABASE_NAME}?sslmode=verify-full&options=--cluster=${process.env.COCKROACH_DB}`;
const connection = `postgres://${process.env.DATABASE_USER_NAME}:${process.env.DATABASE_PASSWORD}@${process.env.DATABASE_HOST}/${process.env.DATABASE_NAME}?sslmode=verify-full`;
const sequelize = new Sequelize(connection, {
dialectOptions: {
ssl: {
Expand All @@ -14,9 +14,12 @@ const sequelize = new Sequelize(connection, {
const makeConnectionWithDB = async () => {
try {
await sequelize.authenticate();
if (process.env.NODE_ENV === "development") {
await sequelize.sync({ force: true, logging: (sql) => console.log(sql) });
}
// if (process.env.NODE_ENV === "development") {
await sequelize.sync({
force: true,
logging: (sql) => console.log(sql),
});
// }
console.log("Connection has been established successfully.");
} catch (error) {
console.error("Unable to connect to the database:", error);
Expand Down
3 changes: 1 addition & 2 deletions index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,16 +4,15 @@ import helmet from "helmet";
import cookieParser from "cookie-parser";
const xss = require("xss-clean");
import dotenv from "dotenv";
import { limiter } from "./src/utils/rateLimiter";
import routes from "./routes";
import { makeConnectionWithDB } from "./db";
import loadData from "./insertData";
import { loadA2ZSheet } from "./script";

dotenv.config();
const app = express();
const PORT = process.env.PORT || 5000;

app.use(limiter);
app.use(helmet());
app.use(xss());

Expand Down
90 changes: 55 additions & 35 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 1 addition & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -27,14 +27,13 @@
"typescript": "^4.5.5"
},
"dependencies": {
"axios": "^1.6.5",
"cookie-parser": "^1.4.6",
"cors": "^2.8.5",
"dotenv": "^16.0.0",
"express": "^4.17.2",
"express-rate-limit": "^6.4.0",
"helmet": "^5.1.0",
"jsonwebtoken": "^8.5.1",
"nanoid": "^3.3.1",
"node-mailjet": "^4.0.0",
"nodemailer": "^6.7.2",
"pg": "^8.7.3",
Expand Down
10 changes: 5 additions & 5 deletions routes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,17 +15,17 @@ function routes(app: Express): void {

app.use(verifyJWT);

app.use("/api/v2/subject", subjectRouter);
// app.use("/api/v2/subject", subjectRouter);

app.use("/api/v2/topic", topicRouter);
// app.use("/api/v2/topic", topicRouter);

app.use("/api/v2/question", questionRouter);
// app.use("/api/v2/question", questionRouter);

app.use(verifyPermission);

app.use("/api/v2/submission", submissionRouter);
// app.use("/api/v2/submission", submissionRouter);

app.use("/api/v2/revision", revisionRouter);
// app.use("/api/v2/revision", revisionRouter);
}

export default routes;
69 changes: 69 additions & 0 deletions script.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
import axios from "axios";
import { Subject } from "./src/models/Subject";
import { TopicUnderSubject } from "./src/models/TopicUnderSubject";

export async function loadA2ZSheet() {
try {
const { data } = await axios.get(
"https://gist.githubusercontent.com/charitra1022/3c963e85a7f5715f377db330c6bf5b87/raw/552981ba037b174f59dd2b96118f41be84673590/ques_list.json"
);
// console.log(data);
// const { data: original } = await axios.get(
// "https://api.takeuforward.org/api/singletopic/single/a2z?topicName=strivers_a2z_sheet"
// );
// console.log(original);
const groupedData = data.reduce((acc: any, item: any) => {
const topicTitle = item["topic-title"];
const stepMatch = item["subtopic-title"].match(/Step (\d+\.\d+):/);

// Group by 'topic-title'
if (!acc[topicTitle]) {
acc[topicTitle] = {};
}

// Group by 'Step' part within 'topic-title'
if (stepMatch) {
const stepPart = stepMatch[1];
if (!acc[topicTitle][stepPart]) {
acc[topicTitle][stepPart] = [];
}
acc[topicTitle][stepPart].push(item);
}

return acc;
}, {});

const resultArray: {
topic: string;
subtopics: { title: string; questions: any[] }[];
}[] = Object.keys(groupedData).map((topicTitle) => {
const subtopicsArray = Object.keys(groupedData[topicTitle]).map(
(subtopicTitle) => {
return {
title: subtopicTitle,
questions: groupedData[topicTitle][subtopicTitle],
};
}
);

return {
topic: topicTitle,
subtopics: subtopicsArray,
};
});

// Log the result
console.log(resultArray[0], resultArray[1], resultArray[2]);
// Log the result
resultArray.map(async (data: any) => {
await TopicUnderSubject.create({
topic_name: data.topic,
topic_description: data.topic,
question_count: data.subtopics.length,
under_which_subject: "A2ZDSA",
});
});
} catch (error) {
console.log(error);
}
}
19 changes: 8 additions & 11 deletions src/DataAccessLayer/user.dal.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,25 +7,22 @@ export const createUserDal = async (
};

export const updateUserDal = async (
id: string,
id: number,
payload: Partial<UserInput>
): Promise<UserOutput> => {
const user = await User.findByPk(id);
if (!user) throw "User not found";

const updatedUser = user.set({
email: payload.email,
multi_factor_enabled: payload.multi_factor_enabled,
account_status: payload.account_status,
user_name: payload.user_name,
refresh_token: payload.refresh_token,
accountStatus: payload.accountStatus,
userName: payload.userName,
refreshToken: payload.refreshToken,
role: payload.role,
ip: payload.ip,
total_number_of_questions_done_by_user:
payload.total_number_of_questions_done_by_user,
secret: payload.secret,
secret_backup: payload.secret_backup,
totalNumberQuestionsSolved: payload.totalNumberQuestionsSolved,
verified: payload.verified,
verificationCode: payload.verificationCode,
});
await updatedUser.save();
return updatedUser;
Expand All @@ -40,7 +37,7 @@ export const getUserByEmailDal = async (email: string): Promise<UserOutput> => {
export const getUserByRefreshTokenDal = async (
refreshToken: string
): Promise<UserOutput> => {
const user = await User.findOne({ where: { refresh_token: refreshToken } });
const user = await User.findOne({ where: { refreshToken: refreshToken } });
if (!user) throw "User not found";
return user;
};
Expand All @@ -52,5 +49,5 @@ export const getUserByIdDal = async (id: string): Promise<UserOutput> => {
};

export const deleteUserByIdDal = async (id: string) => {
return await User.destroy({ where: { user_id: id } });
return await User.destroy({ where: { id: id } });
};
Loading

0 comments on commit 8103f37

Please sign in to comment.