config.go 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. package permlib
  2. import (
  3. "errors"
  4. "net/http"
  5. "time"
  6. )
  7. type FieldWriteMode int
  8. const (
  9. FieldWriteSilent FieldWriteMode = iota
  10. FieldWriteReject
  11. )
  12. // AuthCallbacks 鉴权回调,调用方必须提供,permlib 不内置任何响应格式
  13. type AuthCallbacks struct {
  14. // OnError 鉴权失败时调用
  15. // httpStatus: 建议的 HTTP 状态码(401/403/500)
  16. // code: 业务错误码
  17. // msg: 错误信息
  18. OnError func(w http.ResponseWriter, r *http.Request, httpStatus int, code int, msg string)
  19. // OnSuccess 鉴权成功时调用
  20. // user: 当前用户信息(含 Perms)
  21. // hasDataPerm: 当前请求是否有对应的 data:* 数据权限
  22. // next: 业务 handler,hasDataPerm 为 true 时调用,否则返回空数据
  23. OnSuccess func(w http.ResponseWriter, r *http.Request, next http.HandlerFunc, user *UserInfo, hasDataPerm bool)
  24. }
  25. type Config struct {
  26. ProductCode string
  27. AppKey string
  28. AppSecret string
  29. PermServerAddr string
  30. FieldWriteMode FieldWriteMode
  31. CacheTTL time.Duration
  32. Callbacks AuthCallbacks
  33. }
  34. func (c *Config) validate() error {
  35. if c.Callbacks.OnError == nil {
  36. return errors.New("Config.Callbacks.OnError is required")
  37. }
  38. if c.Callbacks.OnSuccess == nil {
  39. return errors.New("Config.Callbacks.OnSuccess is required")
  40. }
  41. return nil
  42. }
  43. func (c *Config) defaults() {
  44. if c.CacheTTL == 0 {
  45. c.CacheTTL = 5 * time.Minute
  46. }
  47. }