authorization.js 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. var path = require('path');
  2. // var roles_controller = require("../controllers/roles");
  3. var path = require("path");
  4. global.service_caches = {};
  5. // 存储全局验证函数
  6. global.service_auth_fn = null;
  7. /**
  8. * 构造回调对象格式
  9. *
  10. * @param {[type]} serviceName 服务名称
  11. * @param {[type]} actionName 动作名称(方法名)
  12. * @param {[type]} serviceModule 服务模块
  13. * @param {[type]} origFunc 原始方法
  14. */
  15. function Invocation(serviceName,actionName,serviceModule,origFunc) {
  16. return function() {
  17. var origArguments = arguments;
  18. return function(req,res,next) {
  19. if(global.service_auth_fn) {
  20. global.service_auth_fn(req,res,next,serviceName,actionName,function(pass) {
  21. if(pass) {
  22. origFunc.apply(serviceModule,origArguments);
  23. } else {
  24. res.sendResult(null,401,"权限验证失败");
  25. }
  26. });
  27. } else {
  28. res.sendResult(null,401,"权限验证失败");
  29. }
  30. }
  31. }
  32. }
  33. // 获取服务对象
  34. module.exports.getService = function(serviceName) {
  35. if(global.service_caches[serviceName]) {
  36. return global.service_caches[serviceName];
  37. }
  38. var servicePath = path.join(process.cwd(),"services",serviceName);
  39. var serviceModule = require(servicePath);
  40. if(!serviceModule) {
  41. console.log("模块没有被发现");
  42. return null;
  43. }
  44. global.service_caches[serviceName] = {};
  45. console.log("*****************************************");
  46. console.log("拦截服务 => %s",serviceName);
  47. console.log("*****************************************");
  48. for(actionName in serviceModule) {
  49. if(serviceModule && serviceModule[actionName] && typeof(serviceModule[actionName]) == "function") {
  50. var origFunc = serviceModule[actionName];
  51. global.service_caches[serviceName][actionName] = Invocation(serviceName,actionName,serviceModule,origFunc);
  52. console.log("action => %s",actionName);
  53. }
  54. }
  55. // console.log(global.service_caches);
  56. console.log("*****************************************\n");
  57. return global.service_caches[serviceName];
  58. }
  59. // 设置全局验证函数
  60. module.exports.setAuthFn = function(authFn) {
  61. global.service_auth_fn = authFn;
  62. }