作者希望在 Servant(Haskell 的 Web API 框架)之上构建一个角色权限系统,使用户可以在 API 类型定义中直接指定每个路由所需的角色。设计灵感来自 OCharle 的 Who Authorized These Ghosts 项目。核心思路是将角色定义为 sum type,通过 CheckRole 类型类实现角色检查谓词,然后引入 RequireRole 组合子。如果用户的角色不满足路由要求的权限级别,请求会自动尝试匹配下一个路由。文章逐步展示了如何通过 HasServer 实例实现这一机制。
🔑 核心要点
在 Servant API 类型定义 中直接声明每个路由所需的角色权限
角色定义为 sum type(Viewer、Editor、Admin),通过 Ord 实现层级回退
CheckRole 类型类 支持任意谓词,可建模层级式或集合式权限体系
RequireRole 组合子 在请求进入 handler 前插入角色校验步骤
权限失败时自动 尝试下一条匹配路由,实现优雅的错误处理
💡 金句
My first move was to sketch out an imaginary interface for the library. My hope is that starting from the interface the code would reveal its implementation to me.