共计 2163 个字符,预计需要花费 6 分钟才能阅读完成。
// 中间件
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));
}
}
}
正文完
发表至: javascript
2022-11-21