From 303b3cf3038e3f57f404559d47554fb16f58cdc1 Mon Sep 17 00:00:00 2001 From: oitsjustjose Date: Fri, 15 Apr 2022 08:59:32 -0500 Subject: [PATCH] Use Bearer token --- backend/src/app/controllers/user/crud/get.ts | 28 ++++++++++++++++++++ backend/src/app/controllers/user/index.ts | 10 +++++-- backend/src/app/middleware/UserInjection.ts | 3 ++- 3 files changed, 38 insertions(+), 3 deletions(-) create mode 100644 backend/src/app/controllers/user/crud/get.ts diff --git a/backend/src/app/controllers/user/crud/get.ts b/backend/src/app/controllers/user/crud/get.ts new file mode 100644 index 0000000..09b7539 --- /dev/null +++ b/backend/src/app/controllers/user/crud/get.ts @@ -0,0 +1,28 @@ +import EmailValidator from "email-validator"; +import { Request, Response } from "express"; +import Users from "../../../models/User"; +import { LOGGER } from "../../../util/Logger"; + +export default async (req: Request, res: Response) => { + try { + if (!req.user) { + return res + .status(422) + .json({ error: "Cannot fetch the user since you are not logged in." }); + } + + // If you're an admin it's assumed you're viewing someone else's account + const userId = req.user.admin && req.body._id ? req.body._id : req.user._id; + const user = await Users.findById(userId); + if (!user) { + return res + .status(404) + .json({ error: `User with id ${userId} not found` }); + } + + return res.status(200).json(user); + } catch (ex) { + LOGGER.error(ex); + return res.status(500).json({ error: ex }); + } +}; diff --git a/backend/src/app/controllers/user/index.ts b/backend/src/app/controllers/user/index.ts index 69e0890..efc7046 100644 --- a/backend/src/app/controllers/user/index.ts +++ b/backend/src/app/controllers/user/index.ts @@ -1,11 +1,17 @@ import { RouteCollection } from ".."; -import create from "./crud/create"; -import del from "./crud/delete"; import forgot from "./auth/forgot"; import login from "./auth/login"; import validate from "./auth/validate"; +import create from "./crud/create"; +import del from "./crud/delete"; +import get from "./crud/get"; const routes: RouteCollection[] = [ + { + httpMethod: "GET", + path: "/api/v1/user", + handler: get, + }, { httpMethod: "PUT", path: "/api/v1/user", diff --git a/backend/src/app/middleware/UserInjection.ts b/backend/src/app/middleware/UserInjection.ts index 165d746..e64006c 100644 --- a/backend/src/app/middleware/UserInjection.ts +++ b/backend/src/app/middleware/UserInjection.ts @@ -7,7 +7,8 @@ import { LOGGER } from "../util/Logger"; export default () => { return async (req: Request, res: Response, next: NextFunction) => { try { - const token = req.header("auth-token"); + const token = req.header("authorization").replace("Bearer ", ""); + if (!token) { return next(); }