nodejs rbac 許可權驗證(匿名,普通,admin)

洪譚亮發表於2022-11-24

//中介軟體

import jwt from "jsonwebtoken";
import {resultFail} from "../common/utils";
import {SECRET} from "./auth.controller";
import {OPTION} from "./auth.controller";
import {ADMIN, NORMAL} from "../common/constants";

export let verifyAdmin = function (req, resp, next) {
  try {
    const token = req.get("authorization").slice("Bearer ".length);
    jwt.verify(token, SECRET, (error, res) => {
      if (error) {
        resp.status(401).json(resultFail(error) );
        return;
      }
      console.log(OPTION.role)
      if (OPTION.role===ADMIN){
        next();
      }else{
        return resp.status(401).json(resultFail(('No Permission')));
      }
    });
  } catch (e) {
    return resp.status(401).json(resultFail(e));
  }
};

export let verifyNormal = function (req, resp, next) {
  try {
    const token = req.get("authorization").slice("Bearer ".length);
    jwt.verify(token, SECRET, (error, res) => {
      if (error) {
        res.status(401).json(resultFail(error) );
        return;
      }
      if (OPTION.role===NORMAL){
        next();
      }else{
        res.status(401).json(resultFail(('No Permission')));
      }
    });
  } catch (e) {
    return resp.status(401).json(resultFail(e));
  }
};

控制層介面

'use strict';

import { Router } from 'express';
import DevicesController from './devices.controller';
import {verifyAdmin} from "./auth.middleware";

const router = new Router();
router.route('/').post(DevicesController.apiGetDevices);
router.route("/get-grouped-devices").post(DevicesController.apiGetGroupedDevices);
router.route("/alias").post(verifyAdmin, DevicesController.apiSetDeviceAlias);

export default router;

//登入介面

export let SECRET;
export let OPTION;
export default class AuthController {
  static async login(req, res) {
    try {
      const { name, password } = req.body;

      if (!name || typeof name !== "string") {
        res.status(400).json(resultFail("Bad name format, expected string."));
        return;
      }
      if (!password || typeof password !== "string") {
        res.status(400).json(resultFail("Bad password format, expected string."));
        return;
      }

      let userFromDB = await AuthDAO.getUser(name);
      if (!userFromDB) {
        res.status(401).json(resultFail("Make sure your name is correct."));
        return;
      }

      const user = new AuthUser(userFromDB);
      if (!(await user.comparePassword(password))) {
        res.status(401).json(resultFail("Make sure your password is correct."));
        return;
      }
        OPTION = {
          token: user.encoded(),
          userName: userFromDB.name,
          role: userFromDB.privilege
        }
        res.send(resultSuccess({
          auth_token: OPTION.token,
          ...user.toJson()
        }))

    } catch (e) {
      res.status(400).json(resultFail(e));
    }
  }

}

相關文章