Octocake-Dev / octocake

https://octocake.netlify.app
MIT License
1 stars 0 forks source link

Add isAdmin middleware #243

Open imadatyatalah opened 3 years ago

imadatyatalah commented 3 years ago

Is your feature request related to a problem? Please describe. We should be able to check if the current user is admin.

Describe the solution you'd like Your suggestions.

Describe alternatives you've considered Your suggestions.

imadatyatalah commented 3 years ago

I have made this solution and it works just fine in dev mode.

// server/src/routes/auth/github.ts

router.get(
  "/callback",
  passport.authenticate("github", { failureRedirect: "/login" }),
  async (req: CustomRequest, res: Response, next: NextFunction) => {
    try {
      // fetch the current user
      const user = await prisma.user.findUnique({
        where: { githubId: Number(req.user.id) },
      });

      // added user `role`
      const token = jwt.sign(
        { id: Number(req.user.id), role: user.role },
        config.jwt_key,
        {
          expiresIn: 60 * 60 * 24 * 1000,
        }
      );

      res.cookie("oc_token", token, {
        secure: true,
        httpOnly: true,
        maxAge: 60 * 60 * 24 * 1000,
        sameSite: "lax",
      });

      req.logIn(req.user, (err) => {
        if (err) return next(err);
        res.redirect(config.client_base_url);
      });
    } catch (err) {
      res.send(err);
    }
  }
);
// server/src/middlewares/isAdmin.ts

import { NextFunction, Request, Response } from "express";

import jwt from "jsonwebtoken";

import { config } from "../config/credentials";

const isAdmin = (req: Request, res: Response, next: NextFunction) => {
  const token = req.cookies.oc_token as string;

  jwt.verify(token, config.jwt_key, (err, data) => {
    if (err) {
      res.status(403).send({ success: false, message: "Not Authenticated" });
    } else if (data.role === "ADMIN") {
      req.user = data;

      next();
    } else {
      res.status(403).send({ success: false, message: "Not Admin" });
    }
  });
};

export default isAdmin;