日期:2014-05-16 浏览次数:20379 次
(function() { var log = panda.log("proxy.security"); proxy.security = { priority: 80 }; // 对 page.* 的调用进行权限控制 proxy.security.page = { priority: 100, expr: /^page./, func: function(name, method, args) { // 获取方法的第二个参数,即 req var req = args[1]; // 读取 session 中的role。返回值是 java.lang.String // 加上空字符串转为 JavaScript 中的 String var role = req.session.getAttribute("user.role") + ""; // 如果角色是 "admin",则显示相应页面 // 否则,显示登录页面 if (role === "admin") { return this[method].apply(this, args); } else { log.info("Redirect to login page."); return panda.render("login"); } } } // 利用类似的方法对 api.* 的调用进行权限控制,略 proxy.security.api = { ... } }());
validator = {}; // 校验异常信息 validator.USER_INVALID = "Invalid user data."; validator.USER_NAME_EMPTY = "Name cannot be empty."; validator.USER_NAME_TOO_LONG = "Name cannot be longer than 50."; validator.USER_NAME_FORMAT = "Name format is not conrrect."; validator.USER_DESC_EMPTY = "Description cannot be empty."; validator.USER_DESC_TOO_LONG = "Description cannot be longer than 50."; // 检查 user 对象的方法 validator.validateUser = function(user) { // 参数类型错误,可能是恶意攻击 if (typeof user.name !== "string" || typeof user.desc !== "string") { return { success: false, error: validator.USER_INVALID }; } // name 为空 if (!user.name) { return { success: false, error: validator.USER_NAME_EMPTY }; } // name 过长 if (user.name.length > 50) { return { success: false, error: validator.USER_NAME_TOO_LONG }; } // name 格式检查 if (!/^[A-z][A-z0-9._]*$/.test(user.name)) { return { success: false, error: validator.USER_NAME_FORMAT }; } // desc 为空 if (!user.desc) { return { success: false, error: validator.USER_DESC_EMPTY }; } // desc 过长 if (user.desc.length > 50) { return { success: false, error: validator.USER_DESC_TOO_LONG }; } // 提取 name 和 desc;因为对象中可能还有其他不需要的属性 var data = { name: user.name, desc: user.desc } return { success: true, data: data }; }
(function() { var log = panda.log("proxy.validation"); proxy.validation = { priority: 60 }; // 创建或更新 user 时,检查 user 数据 proxy.validation.saveUser = { priority: 100, expr: /^dbo.users.(add|update)$/, func: function(name, method, args) { var validated = validator.validateUser(args[0]); if (!validated.success) { log.info(validated.error); throw validated.error; } args[0] = validated.data; return this[method].apply(this, args); } }; // 创建 user 时,检查用户是否已经存在 proxy.validation.addUser = { priority: 80, expr: