operation_permission_seed.go 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. package initialize
  2. import (
  3. "errors"
  4. "fmt"
  5. "gorm.io/gorm"
  6. "wails-app/internal/dao"
  7. "wails-app/internal/global"
  8. )
  9. // EnsureOperationPermissions upgrades both new and existing databases with the
  10. // API catalogue and Casbin policies required by the entry/exit operation page.
  11. func EnsureOperationPermissions() error {
  12. db := global.GVA_DB
  13. if db == nil {
  14. return nil
  15. }
  16. apis := []dao.SysApi{
  17. {Path: "/vehicle/entry", Description: "车辆入场", ApiGroup: "进出场操作", Method: "POST"},
  18. {Path: "/vehicle/operation/context", Description: "查询车辆操作上下文", ApiGroup: "进出场操作", Method: "POST"},
  19. {Path: "/vehicle/passage", Description: "统一车辆通行", ApiGroup: "进出场操作", Method: "POST"},
  20. {Path: "/channel/events", Description: "查询通道事件", ApiGroup: "进出场操作", Method: "GET"},
  21. {Path: "/parking/gate/devices", Description: "查询道闸设备", ApiGroup: "进出场操作", Method: "GET"},
  22. {Path: "/parking/gate/open", Description: "人工开闸", ApiGroup: "进出场操作", Method: "POST"},
  23. {Path: "/parking/gate/close", Description: "人工关闸", ApiGroup: "进出场操作", Method: "POST"},
  24. }
  25. for _, api := range apis {
  26. var existing dao.SysApi
  27. err := db.Where("path = ? AND method = ?", api.Path, api.Method).First(&existing).Error
  28. if errors.Is(err, gorm.ErrRecordNotFound) {
  29. err = db.Create(&api).Error
  30. }
  31. if err != nil {
  32. return fmt.Errorf("初始化进出场API %s %s 失败: %w", api.Method, api.Path, err)
  33. }
  34. }
  35. if err := db.Exec(`CREATE TABLE IF NOT EXISTS casbin_rule (
  36. id INTEGER PRIMARY KEY AUTOINCREMENT,
  37. ptype TEXT, v0 TEXT, v1 TEXT, v2 TEXT, v3 TEXT, v4 TEXT, v5 TEXT
  38. )`).Error; err != nil {
  39. return fmt.Errorf("初始化Casbin规则表失败: %w", err)
  40. }
  41. for _, role := range []string{"618", "888", "9527"} {
  42. for _, rule := range [][2]string{
  43. {"/vehicle/entry", "POST"},
  44. {"/vehicle/operation/context", "POST"},
  45. {"/vehicle/passage", "POST"},
  46. {"/channel/events", "GET"},
  47. {"/parking/gate/devices", "GET"},
  48. {"/parking/gate/open", "POST"},
  49. {"/parking/gate/close", "POST"},
  50. } {
  51. if err := ensureCasbinRule(role, rule[0], rule[1]); err != nil {
  52. return fmt.Errorf("初始化角色%s进出场权限失败: %w", role, err)
  53. }
  54. }
  55. }
  56. return nil
  57. }