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

Fetch userId from res.locals #59

Merged
merged 2 commits into from
Nov 11, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 11 additions & 5 deletions src/controllers/progress.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,9 @@ import { Types } from "mongoose";
import { MongoError } from "mongodb";

export const submitAnswer = async (req: Request, res: Response) => {
const { courseId, lessonId, choice, userId } = req.body;
const { courseId, lessonId, choice } = req.body;

const userId = res.locals?.populatedUser?._id;

if (!courseId || !lessonId || (!choice && choice != 0) || !userId) {
return res.status(400).send({ error: { message: "Missing params" } });
Expand Down Expand Up @@ -61,7 +63,9 @@ export const submitAnswer = async (req: Request, res: Response) => {
};

export const getLessonProgress = async (req: Request, res: Response) => {
const { courseId, lessonId, userId } = req.params;
const { courseId, lessonId } = req.params;

const userId = res.locals?.populatedUser?._id;

if (!courseId || !lessonId || !userId) {
return res.status(400).send({ error: { message: "Missing params" } });
Expand All @@ -77,7 +81,9 @@ export const getLessonProgress = async (req: Request, res: Response) => {
};

export const getCourseProgress = async (req: Request, res: Response) => {
const { userId, courseId } = req.params;
const { courseId } = req.params;

const userId = res.locals?.populatedUser;

if (!userId || !courseId) {
return res.status(400).send({ error: { message: "Missing params" } });
Expand Down Expand Up @@ -130,8 +136,8 @@ const calculateLevel = (exp: number): number => {
return level;
};

export const getUserXPAndLevel = async (req: Request, res: Response) => {
const { userId } = req.params;
export const getUserXPAndLevel = async (_req: Request, res: Response) => {
const userId = res.locals?.populatedUser?._id;

if (!userId) {
return res.status(400).send({ error: { message: "Missing userId" } });
Expand Down
22 changes: 11 additions & 11 deletions src/controllers/users.ts
Original file line number Diff line number Diff line change
Expand Up @@ -116,12 +116,12 @@ export const recoverUser = async (req: Request, res: Response) => {
return res.status(400).send({ error: { message } });
};

export const getUser = async (req: Request, res: Response) => {
export const getUser = async (_req: Request, res: Response) => {
try {
const { id } = req.params;
if (!id) return res.status(400).send({ error: { message: "Missing user's id" } });
const userId = res.locals?.populatedUser?._id;
if (!userId) return res.status(400).send({ error: { message: "Missing user's id" } });

const user = await UserModel.findOne({ _id: id });
const user = await UserModel.findOne({ _id: userId });
if (user) {
const userInfo: UserInfo = {
id: user._id,
Expand All @@ -148,10 +148,10 @@ export const getUser = async (req: Request, res: Response) => {

export const updateUser = async (req: Request, res: Response) => {
try {
const { id } = req.params;
const userId = res.locals?.populatedUser?._id;
const { email, name, picture, company, isAdmin, password, language } = req.body;

const user = await UserModel.findById(id);
const user = await UserModel.findById(userId);
if (!user) return res.status(404).send({ error: { message: "User not found" } });

if (email) user.email = email;
Expand Down Expand Up @@ -185,13 +185,13 @@ export const updateUser = async (req: Request, res: Response) => {
});
};

export const deleteUser = async (req: Request, res: Response) => {
export const deleteUser = async (_req: Request, res: Response) => {
try {
const { id } = req.params;
if (!id) return res.status(400).send({ error: { message: "Missing userId" } });
const userId = res.locals?.populatedUser?._id;
if (!userId) return res.status(400).send({ error: { message: "Missing userId" } });

const result = await UserModel.deleteOne({ _id: id });
if (result?.deletedCount > 0) return res.status(200).send({ message: `User '${id}' deleted` });
const result = await UserModel.deleteOne({ _id: userId });
if (result?.deletedCount > 0) return res.status(200).send({ message: `User '${userId}' deleted` });
} catch (e) {
console.error(`[ERROR][deleteUser] ${e}`);
}
Expand Down
2 changes: 0 additions & 2 deletions src/middlewares/auth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,6 @@ import { env } from "@/environment";
import { UserModel } from "@/models/User";

const authMiddleware = async (req: Request, res: Response, next: NextFunction) => {
// Comment here to test endpoints with authentication (app's jwt)
if (["local", "test"].includes(env.NODE_ENV)) return next();
const error = {
status: 401,
error: "You are not authorized to perform this action.",
Expand Down
12 changes: 6 additions & 6 deletions src/routes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,9 +31,9 @@ const router = (app: Express) => {
app.post("/users", createUser);
app.post("/users/verify", verifyUser);
app.post("/users/recover", recoverUser);
app.get("/users/:id", [authMiddleware], getUser);
app.put("/users/:id", [authMiddleware], updateUser);
app.delete("/users/:id", [authMiddleware], deleteUser);
app.get("/users", [authMiddleware], getUser);
app.put("/users", [authMiddleware], updateUser);
app.delete("/users", [authMiddleware], deleteUser);
app.post("/users/login", loginUser);
app.post("/users/login/google", loginUserWithGoogle);
app.post("/users/login/wallet", loginUserWithWallet);
Expand Down Expand Up @@ -61,9 +61,9 @@ const router = (app: Express) => {

// Progress
app.post("/progress", [authMiddleware], submitAnswer);
app.get("/progress/lesson/:userId/:courseId/:lessonId", [authMiddleware], getLessonProgress);
app.get("/progress/course/:userId/:courseId", [authMiddleware], getCourseProgress);
app.get("/progress/level/:userId", [authMiddleware], getUserXPAndLevel);
app.get("/progress/lesson/:courseId/:lessonId", [authMiddleware], getLessonProgress);
app.get("/progress/course/:courseId", [authMiddleware], getCourseProgress);
app.get("/progress/level", [authMiddleware], getUserXPAndLevel);
};

export default router;
79 changes: 54 additions & 25 deletions tests/courses.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@ import { join } from "path";
import { CourseModel } from "@/models/Course";
import { Module, ModuleModel } from "@/models/Module";
import { Lesson, LessonModel } from "@/models/Lesson";
import { UserModel } from "@/models/User";
import { getAuthHeaders } from "./helpers";

const PORT = 3013;
const API_URL = `http://0.0.0.0:${PORT}`;
Expand All @@ -20,6 +22,8 @@ const loadFixture = (fixture: string) => {
};

describe("Setting API Server up...", () => {
let headers: { authorization: string; code: string };

let server: Server;
beforeAll((done) => {
const app = express();
Expand All @@ -32,6 +36,19 @@ describe("Setting API Server up...", () => {

beforeAll(async () => {
await mongoDBsetup(MONGODB_DATABASE_NAME);
const email = "new.user@polkadot.education";
const password = "password";
await UserModel.createUser({
email,
password,
name: "New User",
language: "english",
company: "company",
picture: "Base64OrLink",
isAdmin: false,
signInType: "Email",
});
headers = await getAuthHeaders(email, password);
});

afterAll(async () => {
Expand Down Expand Up @@ -69,12 +86,16 @@ describe("Setting API Server up...", () => {
const courseSummary = "This is a summary of Course #1";

await axios
.post(`${API_URL}/course`, {
title: courseTitle,
language: courseLanguage,
summary: courseSummary,
modules: [module._id],
})
.post(
`${API_URL}/course`,
{
title: courseTitle,
language: courseLanguage,
summary: courseSummary,
modules: [module._id],
},
{ headers },
)
.then((r) => {
expect(r.data.title).toEqual(courseTitle);
expect(r.data.language).toEqual(courseLanguage);
Expand All @@ -93,12 +114,16 @@ describe("Setting API Server up...", () => {
const invalidModuleId = "60e4b68f2f8fb814b56fa181";

await axios
.post(`${API_URL}/course`, {
title: courseTitle,
language: courseLanguage,
summary: courseSummary,
modules: [invalidModuleId],
})
.post(
`${API_URL}/course`,
{
title: courseTitle,
language: courseLanguage,
summary: courseSummary,
modules: [invalidModuleId],
},
{ headers },
)
.then(() => {})
.catch((e) => {
expect(e.response.data.error.message).toContain("Some modules not found");
Expand Down Expand Up @@ -146,15 +171,19 @@ describe("Setting API Server up...", () => {
const updatedLanguage = "portuguese";
const updatedSummary = "Resumo do curso atualizado";

await axios.put(`${API_URL}/course/${course._id}`, {
title: updatedTitle,
language: updatedLanguage,
summary: updatedSummary,
modules: [module._id],
});
await axios.put(
`${API_URL}/course/${course._id}`,
{
title: updatedTitle,
language: updatedLanguage,
summary: updatedSummary,
modules: [module._id],
},
{ headers },
);

await axios
.get(`${API_URL}/course?courseId=${course._id}`)
.get(`${API_URL}/course?courseId=${course._id}`, { headers })
.then((r) => {
expect(r.data.title).toEqual(updatedTitle);
expect(r.data.language).toEqual(updatedLanguage);
Expand Down Expand Up @@ -192,7 +221,7 @@ describe("Setting API Server up...", () => {
});

await axios
.get(`${API_URL}/course?courseId=${newCourse._id}`)
.get(`${API_URL}/course?courseId=${newCourse._id}`, { headers })
.then((r) => {
expect(r.data.title).toEqual("Course with Module");
expect(r.data.summary).toEqual("This course contains a module");
Expand Down Expand Up @@ -258,7 +287,7 @@ describe("Setting API Server up...", () => {
});

await axios
.get(`${API_URL}/courses?language=english`)
.get(`${API_URL}/courses?language=english`, { headers })
.then((r) => {
expect(r.data.length).toBe(1);
expect(r.data[0].title).toEqual("Course in English");
Expand All @@ -268,7 +297,7 @@ describe("Setting API Server up...", () => {

it("Get courses by language with no results (GET /courses?language=french)", async () => {
await axios
.get(`${API_URL}/courses?language=french`)
.get(`${API_URL}/courses?language=french`, { headers })
.then(() => {})
.catch((e) => {
expect(e.response.status).toEqual(404);
Expand All @@ -278,7 +307,7 @@ describe("Setting API Server up...", () => {

it("Get courses by language without specifying language (GET /courses)", async () => {
await axios
.get(`${API_URL}/courses`)
.get(`${API_URL}/courses`, { headers })
.then(() => {})
.catch((e) => {
expect(e.response.status).toEqual(400);
Expand Down Expand Up @@ -314,7 +343,7 @@ describe("Setting API Server up...", () => {
const courseCountBefore = await CourseModel.countDocuments();

await axios
.delete(`${API_URL}/course`, { data: { courseId: newCourse._id } })
.delete(`${API_URL}/course`, { headers, data: { courseId: newCourse._id } })
.then((r) => {
expect(r.data.message).toEqual(`Course '${newCourse._id}' deleted`);
})
Expand Down Expand Up @@ -350,7 +379,7 @@ describe("Setting API Server up...", () => {
});

await axios
.post(`${API_URL}/course/duplicate`, { courseId: course._id })
.post(`${API_URL}/course/duplicate`, { courseId: course._id }, { headers })
.then((r) => {
expect(r.data.title).toEqual(`${course.title} (Copy)`);
expect(r.data.summary).toEqual(course.summary);
Expand Down
10 changes: 10 additions & 0 deletions tests/helpers.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
import { env } from "@/environment";
import { UserModel } from "@/models/User";

export const getAuthHeaders = async (email: string, password: string) => {
const jwt = await UserModel.login(email, password);
return {
authorization: `Bearer ${jwt}`,
code: env.AUTH_CODE,
};
};
Loading
Loading