@apso/cli 0.47.6 → 0.49.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +28 -1
- package/dist/commands/dev.d.ts +2 -0
- package/dist/commands/dev.js +20 -3
- package/dist/commands/generate.js +55 -13
- package/dist/commands/mcp/serve.js +24 -41
- package/dist/commands/schema/diff.js +3 -4
- package/dist/commands/schema/pull.js +13 -11
- package/dist/commands/schema/push.js +6 -5
- package/dist/commands/schema/validate.d.ts +10 -0
- package/dist/commands/schema/validate.js +54 -0
- package/dist/commands/test/access.d.ts +11 -0
- package/dist/commands/test/access.js +65 -0
- package/dist/lib/access/cases.d.ts +120 -0
- package/dist/lib/access/cases.js +1163 -0
- package/dist/lib/access/index.d.ts +4 -0
- package/dist/lib/access/index.js +7 -0
- package/dist/lib/access/report.d.ts +75 -0
- package/dist/lib/access/report.js +118 -0
- package/dist/lib/access/rules.json +207 -0
- package/dist/lib/access/run.d.ts +38 -0
- package/dist/lib/access/run.js +111 -0
- package/dist/lib/access/tokens.d.ts +46 -0
- package/dist/lib/access/tokens.js +139 -0
- package/dist/lib/api/services.d.ts +10 -7
- package/dist/lib/api/services.js +19 -32
- package/dist/lib/apsorc-parser.d.ts +1 -1
- package/dist/lib/apsorc-parser.js +2 -0
- package/dist/lib/ddl/change.js +2 -0
- package/dist/lib/ddl/index.d.ts +11 -1
- package/dist/lib/ddl/index.js +30 -16
- package/dist/lib/ddl/sync.d.ts +25 -0
- package/dist/lib/ddl/sync.js +78 -0
- package/dist/lib/deploy/server-push.js +3 -1
- package/dist/lib/generators/go.d.ts +25 -7
- package/dist/lib/generators/go.js +365 -128
- package/dist/lib/generators/python.d.ts +9 -3
- package/dist/lib/generators/python.js +282 -47
- package/dist/lib/generators/typescript.d.ts +3 -5
- package/dist/lib/generators/typescript.js +78 -64
- package/dist/lib/guards.d.ts +111 -13
- package/dist/lib/guards.js +287 -23
- package/dist/lib/templates/entities/entity-col-array.eta +1 -1
- package/dist/lib/templates/go/dto/dto-col-array.eta +2 -2
- package/dist/lib/templates/go/dto/dto-col-date.eta +1 -1
- package/dist/lib/templates/go/dto/dto-col-decimal.eta +1 -1
- package/dist/lib/templates/go/dto/dto-col-enum.eta +1 -1
- package/dist/lib/templates/go/dto/dto-col-float.eta +1 -1
- package/dist/lib/templates/go/dto/dto-col-integer.eta +3 -3
- package/dist/lib/templates/go/dto/dto-col-numeric.eta +1 -1
- package/dist/lib/templates/go/dto/dto-col-string.eta +1 -1
- package/dist/lib/templates/go/dto/dto-col-text.eta +1 -1
- package/dist/lib/templates/go/dto/dto-col-timestamp.eta +1 -1
- package/dist/lib/templates/go/dto/dto-col-timestamptz.eta +1 -1
- package/dist/lib/templates/go/dto/dto-col-uuid.eta +1 -1
- package/dist/lib/templates/go/dto/dto-col-varchar.eta +1 -1
- package/dist/lib/templates/go/dto/dto.eta +17 -18
- package/dist/lib/templates/go/handlers/handler.eta +10 -8
- package/dist/lib/templates/go/handlers/scope.eta +3 -2
- package/dist/lib/templates/go/index-module.eta +10 -5
- package/dist/lib/templates/go/mcp.eta +307 -0
- package/dist/lib/templates/go/middleware/auth.eta +587 -166
- package/dist/lib/templates/go/middleware/permission.eta +174 -0
- package/dist/lib/templates/go/models/model.eta +22 -19
- package/dist/lib/templates/go/models/schema.eta +72 -0
- package/dist/lib/templates/go/services/service.eta +84 -35
- package/dist/lib/templates/go/utils/query.eta +68 -7
- package/dist/lib/templates/guards/guards.module.eta +37 -29
- package/dist/lib/templates/guards/index.eta +4 -0
- package/dist/lib/templates/guards/jwt-auth.guard.eta +114 -29
- package/dist/lib/templates/guards/key.guard.eta +280 -0
- package/dist/lib/templates/guards/permission.guard.eta +168 -0
- package/dist/lib/templates/guards/relations.interceptor.eta +124 -0
- package/dist/lib/templates/guards/scope.guard.eta +189 -41
- package/dist/lib/templates/python/auth.eta +354 -95
- package/dist/lib/templates/python/index-module.eta +7 -7
- package/dist/lib/templates/python/mcp.eta +284 -0
- package/dist/lib/templates/python/models/init.eta +24 -0
- package/dist/lib/templates/python/models/model.eta +30 -61
- package/dist/lib/templates/python/permissions.eta +121 -0
- package/dist/lib/templates/python/routers/router.eta +39 -1
- package/dist/lib/templates/python/schemas/schema-col-array.eta +1 -1
- package/dist/lib/templates/python/schemas/schema.eta +27 -14
- package/dist/lib/templates/python/services/service.eta +38 -15
- package/dist/lib/templates/python/utils/query.eta +52 -25
- package/dist/lib/templates/rest/controller-rest.eta +43 -23
- package/dist/lib/templates/rest/index-module-rest.eta +0 -4
- package/dist/lib/templates/rest/service-rest.eta +3 -44
- package/dist/lib/types/auth.d.ts +84 -80
- package/dist/lib/types/auth.js +77 -60
- package/dist/lib/types/entity.d.ts +17 -9
- package/dist/lib/types/entity.js +3 -0
- package/dist/lib/types/index.d.ts +2 -2
- package/dist/lib/types/index.js +6 -5
- package/dist/lib/utils/crud-deps.d.ts +77 -6
- package/dist/lib/utils/crud-deps.js +197 -14
- package/dist/lib/utils/field.d.ts +12 -0
- package/dist/lib/utils/field.js +18 -2
- package/dist/lib/utils/schema-convert.d.ts +20 -43
- package/dist/lib/utils/schema-convert.js +28 -78
- package/dist/lib/utils/template.d.ts +11 -0
- package/dist/lib/utils/template.js +36 -1
- package/dist/lib/verify/index.d.ts +6 -1
- package/dist/lib/verify/index.js +30 -13
- package/npm-shrinkwrap.json +2 -2
- package/oclif.manifest.json +36 -1
- package/package.json +1 -1
- package/dist/lib/templates/go/models/model-col-array.eta +0 -1
- package/dist/lib/templates/go/models/model-col-boolean.eta +0 -1
- package/dist/lib/templates/go/models/model-col-date.eta +0 -1
- package/dist/lib/templates/go/models/model-col-decimal.eta +0 -1
- package/dist/lib/templates/go/models/model-col-enum.eta +0 -2
- package/dist/lib/templates/go/models/model-col-float.eta +0 -1
- package/dist/lib/templates/go/models/model-col-integer.eta +0 -1
- package/dist/lib/templates/go/models/model-col-json.eta +0 -1
- package/dist/lib/templates/go/models/model-col-jsonb.eta +0 -1
- package/dist/lib/templates/go/models/model-col-numeric.eta +0 -1
- package/dist/lib/templates/go/models/model-col-string.eta +0 -1
- package/dist/lib/templates/go/models/model-col-text.eta +0 -1
- package/dist/lib/templates/go/models/model-col-timestamp.eta +0 -1
- package/dist/lib/templates/go/models/model-col-timestamptz.eta +0 -1
- package/dist/lib/templates/go/models/model-col-uuid.eta +0 -1
- package/dist/lib/templates/go/models/model-col-varchar.eta +0 -1
- package/dist/lib/templates/guards/api-key-auth.guard.eta +0 -145
- package/dist/lib/templates/guards/auth.guard.eta +0 -233
- package/dist/lib/templates/python/models/model-col-array.eta +0 -4
- package/dist/lib/templates/python/models/model-col-boolean.eta +0 -6
- package/dist/lib/templates/python/models/model-col-date.eta +0 -4
- package/dist/lib/templates/python/models/model-col-datetime.eta +0 -5
- package/dist/lib/templates/python/models/model-col-decimal.eta +0 -4
- package/dist/lib/templates/python/models/model-col-enum.eta +0 -16
- package/dist/lib/templates/python/models/model-col-float.eta +0 -6
- package/dist/lib/templates/python/models/model-col-integer.eta +0 -6
- package/dist/lib/templates/python/models/model-col-json.eta +0 -4
- package/dist/lib/templates/python/models/model-col-jsonb.eta +0 -4
- package/dist/lib/templates/python/models/model-col-numeric.eta +0 -4
- package/dist/lib/templates/python/models/model-col-string.eta +0 -6
- package/dist/lib/templates/python/models/model-col-text.eta +0 -6
- package/dist/lib/templates/python/models/model-col-timestamp.eta +0 -11
- package/dist/lib/templates/python/models/model-col-timestamptz.eta +0 -11
- package/dist/lib/templates/python/models/model-col-uuid.eta +0 -5
- package/dist/lib/templates/python/models/model-col-varchar.eta +0 -6
|
@@ -0,0 +1,174 @@
|
|
|
1
|
+
<%~ includeFile('../header.eta', it) %>
|
|
2
|
+
|
|
3
|
+
package middleware
|
|
4
|
+
|
|
5
|
+
// PermissionMiddleware checks the role permissions from .apsorc on every route
|
|
6
|
+
// of the /api group, after AuthMiddleware.
|
|
7
|
+
//
|
|
8
|
+
// A signed-in user may perform a guarded operation when any of these holds:
|
|
9
|
+
// - one of its roles is in the .apsorc default list
|
|
10
|
+
// - its token carries the permission (for example Auth0 RBAC "permissions")
|
|
11
|
+
<% if (it.grants) { %>
|
|
12
|
+
// - a <%= it.grants.entity %> row grants the permission to one of its roles<% if (it.grants.tenantField) { %> in its
|
|
13
|
+
// tenant (or in every tenant, when <%= it.grants.tenantField %> is null)<% } %>
|
|
14
|
+
|
|
15
|
+
<% } %>
|
|
16
|
+
//
|
|
17
|
+
// Grants only add access; they never take away a default. An operation that
|
|
18
|
+
// is not listed is open to any authenticated caller. A service caller (valid
|
|
19
|
+
// API key) is not limited by role. Every interface that calls this API (REST,
|
|
20
|
+
// SDK, MCP) goes through this check.
|
|
21
|
+
|
|
22
|
+
import (
|
|
23
|
+
"net/http"
|
|
24
|
+
"regexp"
|
|
25
|
+
"strings"
|
|
26
|
+
|
|
27
|
+
"github.com/gin-gonic/gin"
|
|
28
|
+
"gorm.io/gorm"
|
|
29
|
+
)
|
|
30
|
+
|
|
31
|
+
// permissionRule is a guarded operation: its permission name and the roles
|
|
32
|
+
// that have it by default.
|
|
33
|
+
type permissionRule struct {
|
|
34
|
+
permission string
|
|
35
|
+
roles []string
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
// entityPermissions holds the guarded operations by route.
|
|
39
|
+
var entityPermissions = map[string]map[string]permissionRule{
|
|
40
|
+
<% it.routes.forEach((route) => { %>
|
|
41
|
+
<%~ JSON.stringify(route.path) %>: {
|
|
42
|
+
<% route.rules.forEach((r) => { %>
|
|
43
|
+
<%~ JSON.stringify(r.op) %>: {<%~ JSON.stringify(r.permission) %>, []string{<%~ r.roles.map((x) => JSON.stringify(x)).join(', ') %>}},
|
|
44
|
+
<% }) %>
|
|
45
|
+
},
|
|
46
|
+
<% }) %>
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
// joinPermissions holds the read rules a join must satisfy, by relation name,
|
|
50
|
+
// so a caller who cannot read an entity cannot read it through a join either.
|
|
51
|
+
var joinPermissions = map[string][]permissionRule{
|
|
52
|
+
<% it.joins.forEach((join) => { %>
|
|
53
|
+
<%~ JSON.stringify(join.name) %>: {
|
|
54
|
+
<% join.rules.forEach((r) => { %>
|
|
55
|
+
{<%~ JSON.stringify(r.permission) %>, []string{<%~ r.roles.map((x) => JSON.stringify(x)).join(', ') %>}},
|
|
56
|
+
<% }) %>
|
|
57
|
+
},
|
|
58
|
+
<% }) %>
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
var permissionOperations = map[string]string{
|
|
62
|
+
http.MethodGet: "read",
|
|
63
|
+
http.MethodHead: "read",
|
|
64
|
+
http.MethodPost: "create",
|
|
65
|
+
http.MethodPut: "update",
|
|
66
|
+
http.MethodPatch: "update",
|
|
67
|
+
http.MethodDelete: "delete",
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
// A relation embedded in a PostgREST select: rel(...), alias:rel!inner(...).
|
|
71
|
+
var embedPattern = regexp.MustCompile(`([A-Za-z_]\w*)(?:![A-Za-z]+)?\(`)
|
|
72
|
+
|
|
73
|
+
// joinedRelations lists every relation the query asks to load, under either
|
|
74
|
+
// query dialect. ?join=Invoices loads the same relation as ?join=invoices, so
|
|
75
|
+
// the first letter is lowered to the .apsorc name.
|
|
76
|
+
func joinedRelations(c *gin.Context) []string {
|
|
77
|
+
q := c.Request.URL.Query()
|
|
78
|
+
raw := []string{}
|
|
79
|
+
for _, j := range q["join"] {
|
|
80
|
+
raw = append(raw, strings.Split(strings.SplitN(j, "||", 2)[0], ".")...)
|
|
81
|
+
}
|
|
82
|
+
for _, s := range q["select"] {
|
|
83
|
+
for _, m := range embedPattern.FindAllStringSubmatch(s, -1) {
|
|
84
|
+
raw = append(raw, m[1])
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
names := []string{}
|
|
88
|
+
for _, n := range raw {
|
|
89
|
+
if n = strings.TrimSpace(n); n != "" {
|
|
90
|
+
names = append(names, strings.ToLower(n[:1])+n[1:])
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
return names
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
// grantedPermissions returns the caller's permissions from its token<% if (it.grants) { %> and
|
|
97
|
+
// its roles' <%= it.grants.entity %> rows. A failed query grants nothing<% } %>.
|
|
98
|
+
func grantedPermissions(db *gorm.DB, a *AuthContext) map[string]bool {
|
|
99
|
+
granted := map[string]bool{}
|
|
100
|
+
for _, p := range a.Permissions {
|
|
101
|
+
granted[p] = true
|
|
102
|
+
}
|
|
103
|
+
<% if (it.grants) { %>
|
|
104
|
+
if len(a.Roles) > 0 {
|
|
105
|
+
// ponytail: one query per guarded request; cache per role and tenant
|
|
106
|
+
// with a short TTL if this shows up in latency.
|
|
107
|
+
q := db.Table(<%~ JSON.stringify(it.grants.table) %>).Where(`"role" IN ?`, a.Roles)
|
|
108
|
+
<% if (it.grants.tenantField) { %>
|
|
109
|
+
if a.WorkspaceID == "" {
|
|
110
|
+
q = q.Where(`"<%= it.grants.tenantField %>" IS NULL`)
|
|
111
|
+
} else {
|
|
112
|
+
q = q.Where(`("<%= it.grants.tenantField %>" IS NULL OR CAST("<%= it.grants.tenantField %>" AS text) = ?)`, a.WorkspaceID)
|
|
113
|
+
}
|
|
114
|
+
<% } %>
|
|
115
|
+
var rows []string
|
|
116
|
+
if err := q.Pluck("permission", &rows).Error; err == nil {
|
|
117
|
+
for _, p := range rows {
|
|
118
|
+
granted[p] = true
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
<% } %>
|
|
123
|
+
return granted
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
// PermissionMiddleware answers 403 unless the caller may perform the
|
|
127
|
+
// operation. basePath is the path of the group the routes are registered on.
|
|
128
|
+
func PermissionMiddleware(db *gorm.DB, basePath string) gin.HandlerFunc {
|
|
129
|
+
return func(c *gin.Context) {
|
|
130
|
+
a, ok := GetAuthContext(c)
|
|
131
|
+
if !ok {
|
|
132
|
+
c.AbortWithStatusJSON(http.StatusForbidden, gin.H{"error": "Forbidden"})
|
|
133
|
+
return
|
|
134
|
+
}
|
|
135
|
+
if a.ServiceID != "" {
|
|
136
|
+
c.Next()
|
|
137
|
+
return
|
|
138
|
+
}
|
|
139
|
+
// Loaded once per request, and only when a default role does not decide.
|
|
140
|
+
var granted map[string]bool
|
|
141
|
+
allowed := func(r permissionRule) bool {
|
|
142
|
+
for _, have := range a.Roles {
|
|
143
|
+
for _, want := range r.roles {
|
|
144
|
+
if have == want {
|
|
145
|
+
return true
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
if granted == nil {
|
|
150
|
+
granted = grantedPermissions(db, a)
|
|
151
|
+
}
|
|
152
|
+
return granted[r.permission]
|
|
153
|
+
}
|
|
154
|
+
deny := func(r permissionRule) {
|
|
155
|
+
c.AbortWithStatusJSON(http.StatusForbidden, gin.H{"error": "Missing permission " + r.permission})
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
rest := strings.TrimPrefix(strings.TrimPrefix(c.FullPath(), basePath), "/")
|
|
159
|
+
entity := strings.SplitN(rest, "/", 2)[0]
|
|
160
|
+
if r, ok := entityPermissions[entity][permissionOperations[c.Request.Method]]; ok && !allowed(r) {
|
|
161
|
+
deny(r)
|
|
162
|
+
return
|
|
163
|
+
}
|
|
164
|
+
for _, relation := range joinedRelations(c) {
|
|
165
|
+
for _, r := range joinPermissions[relation] {
|
|
166
|
+
if !allowed(r) {
|
|
167
|
+
deny(r)
|
|
168
|
+
return
|
|
169
|
+
}
|
|
170
|
+
}
|
|
171
|
+
}
|
|
172
|
+
c.Next()
|
|
173
|
+
}
|
|
174
|
+
}
|
|
@@ -1,47 +1,50 @@
|
|
|
1
1
|
<%~ includeFile('../../header.eta', it) %>
|
|
2
2
|
|
|
3
3
|
package models
|
|
4
|
+
<% if (it.importTime || it.importEnums || it.importPq) { %>
|
|
4
5
|
|
|
5
6
|
import (
|
|
7
|
+
<% if (it.importTime) { %>
|
|
6
8
|
"time"
|
|
9
|
+
<% } %>
|
|
7
10
|
<% if (it.importEnums) { %>
|
|
8
11
|
"app/autogen/models/enums"
|
|
9
12
|
<% } %>
|
|
13
|
+
<% if (it.importPq) { %>
|
|
14
|
+
"github.com/lib/pq"
|
|
15
|
+
<% } %>
|
|
10
16
|
)
|
|
17
|
+
<% } %>
|
|
11
18
|
|
|
12
|
-
// <%= it.name %> represents the <%= it.tableName %> table
|
|
19
|
+
// <%= it.name %> represents the <%= it.tableName %> table. Each gorm tag
|
|
20
|
+
// matches the column the migrations from `apso migrate` create.
|
|
13
21
|
type <%= it.name %> struct {
|
|
14
22
|
<% if (it.createPrimaryKey) { %>
|
|
15
23
|
<% if (it.primaryKeyType === 'uuid') { %>
|
|
16
|
-
ID
|
|
24
|
+
ID string `gorm:"column:id;type:uuid;primaryKey;default:uuid_generate_v4()" json:"id"`
|
|
17
25
|
<% } else { %>
|
|
18
|
-
ID
|
|
26
|
+
ID uint `gorm:"column:id;type:integer;primaryKey;autoIncrement" json:"id"`
|
|
19
27
|
<% } %>
|
|
20
28
|
<% } %>
|
|
21
29
|
<% it.columns.forEach((column) => { %>
|
|
22
|
-
|
|
30
|
+
<%= column.pascalName %> <%~ column.modelGoType %> `gorm:"<%~ column.gormTag %>" json:"<%= column.name %>,omitempty"`
|
|
23
31
|
<% }) %>
|
|
24
32
|
<% if (it.createdAt) { %>
|
|
25
|
-
CreatedAt time.Time
|
|
33
|
+
CreatedAt time.Time `gorm:"column:created_at;type:timestamp;not null;default:now();autoCreateTime" json:"createdAt"`
|
|
26
34
|
<% } %>
|
|
27
35
|
<% if (it.updatedAt) { %>
|
|
28
|
-
UpdatedAt time.Time
|
|
36
|
+
UpdatedAt time.Time `gorm:"column:updated_at;type:timestamp;not null;default:now();autoUpdateTime" json:"updatedAt"`
|
|
29
37
|
<% } %>
|
|
30
38
|
<% it.associations.forEach((assoc) => { %>
|
|
31
|
-
<% if (assoc.
|
|
32
|
-
<%= assoc.
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
<%= assoc.
|
|
39
|
+
<% if (assoc.owns) { %>
|
|
40
|
+
<%= assoc.fkField %> <%= assoc.fkGoType %> `gorm:"<%~ assoc.fkTag %>" json:"<%= assoc.camelReferenceName %>Id"`
|
|
41
|
+
<%= assoc.fieldName %> *<%= assoc.name %> `gorm:"foreignKey:<%= assoc.fkField %><% if (assoc.onDeleteCascade) { %>;constraint:OnDelete:CASCADE<% } %>" json:"<%= assoc.jsonName %>,omitempty"`
|
|
42
|
+
<% } else if (assoc.type === 'OneToMany') { %>
|
|
43
|
+
<%= assoc.fieldName %> []<%= assoc.name %> `gorm:"foreignKey:<%= assoc.foreignKey %>" json:"<%= assoc.jsonName %>,omitempty"`
|
|
36
44
|
<% } else if (assoc.type === 'OneToOne') { %>
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
<%= assoc.
|
|
40
|
-
<% } else { %>
|
|
41
|
-
<%= assoc.referenceName || assoc.name %> *<%= assoc.name %> `json:"<%= assoc.camelReferenceName || assoc.camelName %>,omitempty"`
|
|
42
|
-
<% } %>
|
|
43
|
-
<% } else if (assoc.type === 'ManyToMany') { %>
|
|
44
|
-
<%= assoc.pluralName %> []<%= assoc.name %> `gorm:"many2many:<%= assoc.joinTable %>;" json:"<%= assoc.camelPluralName %>,omitempty"`
|
|
45
|
+
<%= assoc.fieldName %> *<%= assoc.name %> `gorm:"foreignKey:<%= assoc.foreignKey %>;constraint:OnDelete:CASCADE" json:"<%= assoc.jsonName %>,omitempty"`
|
|
46
|
+
<% } else if (assoc.type === 'ManyToMany' && assoc.join) { %>
|
|
47
|
+
<%= assoc.fieldName %> []<%= assoc.name %> `gorm:"many2many:<%= assoc.join.name %>;joinForeignKey:<%= assoc.join.ownCol %>;joinReferences:<%= assoc.join.otherCol %>" json:"<%= assoc.jsonName %>,omitempty"`
|
|
45
48
|
<% } %>
|
|
46
49
|
<% }) %>
|
|
47
50
|
}
|
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
<%~ includeFile('../../header.eta', it) %>
|
|
2
|
+
|
|
3
|
+
package models
|
|
4
|
+
|
|
5
|
+
import (
|
|
6
|
+
"gorm.io/gorm"
|
|
7
|
+
"gorm.io/gorm/schema"
|
|
8
|
+
)
|
|
9
|
+
|
|
10
|
+
// Migrate brings the database to the .apsorc schema exactly as the migrations
|
|
11
|
+
// from `apso migrate` build it: it creates the tables, columns, indexes and
|
|
12
|
+
// constraints that are missing, and never alters or drops anything. Call it
|
|
13
|
+
// instead of db.AutoMigrate when DATABASE_SYNC=true; AutoMigrate can't create
|
|
14
|
+
// the enum types, unique constraints and names those migrations use.
|
|
15
|
+
//
|
|
16
|
+
// It refuses, and prints the SQL to rename them, when the database still has
|
|
17
|
+
// the snake_case columns older generated models made, rather than adding
|
|
18
|
+
// empty columns beside them.
|
|
19
|
+
func Migrate(db *gorm.DB) error {
|
|
20
|
+
UseNames(db)
|
|
21
|
+
sqlDB, err := db.DB()
|
|
22
|
+
if err != nil {
|
|
23
|
+
return err
|
|
24
|
+
}
|
|
25
|
+
tx, err := sqlDB.Begin()
|
|
26
|
+
if err != nil {
|
|
27
|
+
return err
|
|
28
|
+
}
|
|
29
|
+
defer tx.Rollback()
|
|
30
|
+
for _, statement := range schemaStatements {
|
|
31
|
+
if _, err := tx.Exec(statement); err != nil {
|
|
32
|
+
return err
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
return tx.Commit()
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
var schemaStatements = []string{
|
|
39
|
+
<% it.statements.forEach((s) => { %>
|
|
40
|
+
<%~ s %>,
|
|
41
|
+
<% }) %>
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
// joinColumns maps a join table column, as gorm titles it, to its name in the
|
|
45
|
+
// database (gorm would otherwise snake_case "PostId" to "post_id").
|
|
46
|
+
var joinColumns = map[string]string{
|
|
47
|
+
<% it.joinColumns.forEach(([k, v]) => { %>
|
|
48
|
+
<%~ k %>: <%~ v %>,
|
|
49
|
+
<% }) %>
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
type namer struct{ schema.Namer }
|
|
53
|
+
|
|
54
|
+
func (n namer) ColumnName(table, column string) string {
|
|
55
|
+
if c, ok := joinColumns[column]; ok {
|
|
56
|
+
return c
|
|
57
|
+
}
|
|
58
|
+
return n.Namer.ColumnName(table, column)
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
// JoinTableName keeps the join table names from the many2many tags as written.
|
|
62
|
+
func (n namer) JoinTableName(name string) string {
|
|
63
|
+
return name
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
// UseNames makes gorm use the join table column names the migrations create.
|
|
67
|
+
// RegisterAllRoutes and Migrate call it before any model is read.
|
|
68
|
+
func UseNames(db *gorm.DB) {
|
|
69
|
+
if _, ok := db.NamingStrategy.(namer); !ok {
|
|
70
|
+
db.NamingStrategy = namer{db.NamingStrategy}
|
|
71
|
+
}
|
|
72
|
+
}
|
|
@@ -4,14 +4,20 @@ package services
|
|
|
4
4
|
|
|
5
5
|
import (
|
|
6
6
|
"context"
|
|
7
|
+
<% if (it.columns.some(c => c.gormTag.includes('serializer:json'))) { %>
|
|
8
|
+
"encoding/json"
|
|
9
|
+
<% } %>
|
|
7
10
|
"errors"
|
|
8
11
|
|
|
9
12
|
"app/autogen/dto"
|
|
10
|
-
<% if (it.scope) { %>
|
|
13
|
+
<% if (it.scope || it.references.length) { %>
|
|
11
14
|
"app/autogen/middleware"
|
|
12
15
|
<% } %>
|
|
13
16
|
"app/autogen/models"
|
|
14
17
|
"app/autogen/utils"
|
|
18
|
+
<% if (it.columns.some(c => c.type === 'array')) { %>
|
|
19
|
+
"github.com/lib/pq"
|
|
20
|
+
<% } %>
|
|
15
21
|
"gorm.io/gorm"
|
|
16
22
|
)
|
|
17
23
|
|
|
@@ -20,7 +26,7 @@ import (
|
|
|
20
26
|
var AllowedFields<%= it.entityName %> = map[string]bool{
|
|
21
27
|
"id": true,
|
|
22
28
|
<% it.columns.forEach((column) => { %>
|
|
23
|
-
"<%= column.
|
|
29
|
+
"<%= column.name %>": true,
|
|
24
30
|
<% }) %>
|
|
25
31
|
<% if (it.createdAt) { %>
|
|
26
32
|
"created_at": true,
|
|
@@ -28,8 +34,8 @@ var AllowedFields<%= it.entityName %> = map[string]bool{
|
|
|
28
34
|
<% if (it.updatedAt) { %>
|
|
29
35
|
"updated_at": true,
|
|
30
36
|
<% } %>
|
|
31
|
-
<% it.associations.filter(a => a.
|
|
32
|
-
"<%= assoc.
|
|
37
|
+
<% it.associations.filter(a => a.owns).forEach((assoc) => { %>
|
|
38
|
+
"<%= assoc.fkColumn %>": true,
|
|
33
39
|
<% }) %>
|
|
34
40
|
}
|
|
35
41
|
|
|
@@ -42,19 +48,19 @@ func New<%= it.entityName %>Service(db *gorm.DB) *<%= it.entityName %>Service {
|
|
|
42
48
|
}
|
|
43
49
|
<% if (it.scope) { %>
|
|
44
50
|
|
|
45
|
-
// scoped limits q to the caller's tenant
|
|
46
|
-
//
|
|
47
|
-
//
|
|
51
|
+
// scoped limits q to the caller's tenant per .apsorc scopeBy, on every
|
|
52
|
+
// operation (op names it), and returns the scope column values. Both are
|
|
53
|
+
// unchanged for a service caller or a bypass role.
|
|
48
54
|
func (s *<%= it.entityName %>Service) scoped(ctx context.Context, q *gorm.DB, op string) (*gorm.DB, map[string]string, error) {
|
|
49
|
-
|
|
50
|
-
case <%~ it.scope.enforceOn.map((o) => JSON.stringify(o)).join(', ') %>:
|
|
51
|
-
default:
|
|
52
|
-
return q, nil, nil
|
|
53
|
-
}
|
|
55
|
+
_ = op
|
|
54
56
|
a, ok := middleware.FromContext(ctx)
|
|
55
57
|
if !ok {
|
|
56
58
|
return nil, nil, ErrForbidden
|
|
57
59
|
}
|
|
60
|
+
// A service caller (valid API key) is not tenant-scoped.
|
|
61
|
+
if a.ServiceID != "" {
|
|
62
|
+
return q, nil, nil
|
|
63
|
+
}
|
|
58
64
|
<% if (it.scope.bypassRoles.length > 0) { %>
|
|
59
65
|
if hasAnyRole(a.Roles, <%~ it.scope.bypassRoles.map((r) => JSON.stringify(r)).join(', ') %>) {
|
|
60
66
|
return q, nil, nil
|
|
@@ -71,7 +77,7 @@ func (s *<%= it.entityName %>Service) scoped(ctx context.Context, q *gorm.DB, op
|
|
|
71
77
|
return nil, nil, ErrForbidden
|
|
72
78
|
}
|
|
73
79
|
// Compared as text: token claims are strings, the column may be a number or uuid.
|
|
74
|
-
q = q.Where(
|
|
80
|
+
q = q.Where(`CAST("`+table+`"."`+col+`" AS TEXT) = ?`, v)
|
|
75
81
|
}
|
|
76
82
|
return q, values, nil
|
|
77
83
|
}
|
|
@@ -83,8 +89,8 @@ func (s *<%= it.entityName %>Service) FindAll(ctx context.Context, opts utils.Qu
|
|
|
83
89
|
var items []models.<%= it.entityName %>
|
|
84
90
|
|
|
85
91
|
query := s.db.WithContext(ctx).Model(&models.<%= it.entityName %>{})
|
|
86
|
-
<% it.associations.filter(a => a.eager).forEach((assoc) => { %>
|
|
87
|
-
query = query.Preload("<%= assoc.
|
|
92
|
+
<% it.associations.filter(a => a.eager && !a.hidden).forEach((assoc) => { %>
|
|
93
|
+
query = query.Preload("<%= assoc.fieldName %>")
|
|
88
94
|
<% }) %>
|
|
89
95
|
<% if (it.scope) { %>
|
|
90
96
|
query, _, scopeErr := s.scoped(ctx, query, "find")
|
|
@@ -124,8 +130,8 @@ func (s *<%= it.entityName %>Service) FindAllBare(ctx context.Context, opts util
|
|
|
124
130
|
var items []models.<%= it.entityName %>
|
|
125
131
|
|
|
126
132
|
query := s.db.WithContext(ctx).Model(&models.<%= it.entityName %>{})
|
|
127
|
-
<% it.associations.filter(a => a.eager).forEach((assoc) => { %>
|
|
128
|
-
query = query.Preload("<%= assoc.
|
|
133
|
+
<% it.associations.filter(a => a.eager && !a.hidden).forEach((assoc) => { %>
|
|
134
|
+
query = query.Preload("<%= assoc.fieldName %>")
|
|
129
135
|
<% }) %>
|
|
130
136
|
<% if (it.scope) { %>
|
|
131
137
|
query, _, scopeErr := s.scoped(ctx, query, "find")
|
|
@@ -155,8 +161,8 @@ func (s *<%= it.entityName %>Service) FindOne(ctx context.Context, id string) (*
|
|
|
155
161
|
var item models.<%= it.entityName %>
|
|
156
162
|
|
|
157
163
|
query := s.db.WithContext(ctx)
|
|
158
|
-
<% it.associations.filter(a => a.eager).forEach((assoc) => { %>
|
|
159
|
-
query = query.Preload("<%= assoc.
|
|
164
|
+
<% it.associations.filter(a => a.eager && !a.hidden).forEach((assoc) => { %>
|
|
165
|
+
query = query.Preload("<%= assoc.fieldName %>")
|
|
160
166
|
<% }) %>
|
|
161
167
|
<% if (it.scope) { %>
|
|
162
168
|
query, _, scopeErr := s.scoped(ctx, query, "get")
|
|
@@ -184,17 +190,13 @@ func (s *<%= it.entityName %>Service) FindOne(ctx context.Context, id string) (*
|
|
|
184
190
|
func (s *<%= it.entityName %>Service) Create(ctx context.Context, input *dto.<%= it.entityName %>Create) (*dto.<%= it.entityName %>Response, error) {
|
|
185
191
|
item := models.<%= it.entityName %>{
|
|
186
192
|
<% it.columns.filter(c => !c.generated && !c.primary).forEach((column) => { %>
|
|
187
|
-
<% if (column.required) { %>
|
|
188
193
|
<%= column.pascalName %>: input.<%= column.pascalName %>,
|
|
189
|
-
<% } else { %>
|
|
190
|
-
<%= column.pascalName %>: input.<%= column.pascalName %>,
|
|
191
|
-
<% } %>
|
|
192
194
|
<% }) %>
|
|
193
|
-
<% it.associations.filter(a => a.
|
|
194
|
-
<%= assoc.
|
|
195
|
+
<% it.associations.filter(a => a.owns).forEach((assoc) => { %>
|
|
196
|
+
<%= assoc.fkField %>: input.<%= assoc.fkField %>,
|
|
195
197
|
<% }) %>
|
|
196
198
|
}
|
|
197
|
-
<% if (it.scope
|
|
199
|
+
<% if (it.scope) { %>
|
|
198
200
|
|
|
199
201
|
// The caller's tenant, never one from the body (.apsorc scopeBy).
|
|
200
202
|
_, scopeVals, scopeErr := s.scoped(ctx, s.db, "create")
|
|
@@ -208,6 +210,17 @@ func (s *<%= it.entityName %>Service) Create(ctx context.Context, input *dto.<%=
|
|
|
208
210
|
}
|
|
209
211
|
}
|
|
210
212
|
<% }) %>
|
|
213
|
+
<% } %>
|
|
214
|
+
<% if (it.references.length) { %>
|
|
215
|
+
|
|
216
|
+
// Foreign keys to tenant-scoped entities must name rows the caller can read.
|
|
217
|
+
if err := middleware.CheckReferences(ctx, s.db, map[string][]interface{}{
|
|
218
|
+
<% it.references.forEach((r) => { %>
|
|
219
|
+
<%~ JSON.stringify(r.target) %>: {item.<%= r.goField %>},
|
|
220
|
+
<% }) %>
|
|
221
|
+
}); err != nil {
|
|
222
|
+
return nil, err
|
|
223
|
+
}
|
|
211
224
|
<% } %>
|
|
212
225
|
|
|
213
226
|
if err := s.db.WithContext(ctx).Create(&item).Error; err != nil {
|
|
@@ -243,12 +256,24 @@ func (s *<%= it.entityName %>Service) Update(ctx context.Context, id string, inp
|
|
|
243
256
|
updates := make(map[string]interface{})
|
|
244
257
|
<% it.columns.filter(c => !c.generated && !c.primary).forEach((column) => { %>
|
|
245
258
|
if input.<%= column.pascalName %> != nil {
|
|
246
|
-
|
|
259
|
+
<% if (column.gormTag.includes('serializer:json')) { %>
|
|
260
|
+
// A map in an update map skips the model's JSON serializer.
|
|
261
|
+
encoded, err := json.Marshal(input.<%= column.pascalName %>)
|
|
262
|
+
if err != nil {
|
|
263
|
+
return nil, err
|
|
264
|
+
}
|
|
265
|
+
updates["<%= column.name %>"] = string(encoded)
|
|
266
|
+
<% } else if (column.type === 'array') { %>
|
|
267
|
+
// A plain slice would be sent as a record; the pq type sends an array.
|
|
268
|
+
updates["<%= column.name %>"] = <%= column.arrayGoType %>(*input.<%= column.pascalName %>)
|
|
269
|
+
<% } else { %>
|
|
270
|
+
updates["<%= column.name %>"] = *input.<%= column.pascalName %>
|
|
271
|
+
<% } %>
|
|
247
272
|
}
|
|
248
273
|
<% }) %>
|
|
249
|
-
<% it.associations.filter(a => a.
|
|
250
|
-
if input.<%= assoc.
|
|
251
|
-
updates["<%= assoc.
|
|
274
|
+
<% it.associations.filter(a => a.owns).forEach((assoc) => { %>
|
|
275
|
+
if input.<%= assoc.fkField %> != nil {
|
|
276
|
+
updates["<%= assoc.fkColumn %>"] = *input.<%= assoc.fkField %>
|
|
252
277
|
}
|
|
253
278
|
<% }) %>
|
|
254
279
|
<% if (it.scope) { %>
|
|
@@ -257,6 +282,15 @@ func (s *<%= it.entityName %>Service) Update(ctx context.Context, id string, inp
|
|
|
257
282
|
delete(updates, col)
|
|
258
283
|
}
|
|
259
284
|
<% } %>
|
|
285
|
+
<% if (it.references.length) { %>
|
|
286
|
+
if err := middleware.CheckReferences(ctx, s.db, map[string][]interface{}{
|
|
287
|
+
<% it.references.forEach((r) => { %>
|
|
288
|
+
<%~ JSON.stringify(r.target) %>: {updates[<%~ JSON.stringify(r.column) %>]},
|
|
289
|
+
<% }) %>
|
|
290
|
+
}); err != nil {
|
|
291
|
+
return nil, err
|
|
292
|
+
}
|
|
293
|
+
<% } %>
|
|
260
294
|
|
|
261
295
|
if len(updates) > 0 {
|
|
262
296
|
if err := s.db.WithContext(ctx).Model(&item).Updates(updates).Error; err != nil {
|
|
@@ -266,8 +300,8 @@ func (s *<%= it.entityName %>Service) Update(ctx context.Context, id string, inp
|
|
|
266
300
|
|
|
267
301
|
// Reload with associations
|
|
268
302
|
query := s.db.WithContext(ctx)
|
|
269
|
-
<% it.associations.filter(a => a.eager).forEach((assoc) => { %>
|
|
270
|
-
query = query.Preload("<%= assoc.
|
|
303
|
+
<% it.associations.filter(a => a.eager && !a.hidden).forEach((assoc) => { %>
|
|
304
|
+
query = query.Preload("<%= assoc.fieldName %>")
|
|
271
305
|
<% }) %>
|
|
272
306
|
<% if (it.primaryKeyType === 'uuid') { %>
|
|
273
307
|
if err := query.Where("id = ?", id).First(&item).Error; err != nil {
|
|
@@ -306,7 +340,7 @@ func (s *<%= it.entityName %>Service) Delete(ctx context.Context, id string) err
|
|
|
306
340
|
|
|
307
341
|
// toResponse converts a model to a response DTO
|
|
308
342
|
func (s *<%= it.entityName %>Service) toResponse(item *models.<%= it.entityName %>) dto.<%= it.entityName %>Response {
|
|
309
|
-
|
|
343
|
+
response := dto.<%= it.entityName %>Response{
|
|
310
344
|
ID: item.ID,
|
|
311
345
|
<% it.columns.forEach((column) => { %>
|
|
312
346
|
<%= column.pascalName %>: item.<%= column.pascalName %>,
|
|
@@ -317,8 +351,23 @@ func (s *<%= it.entityName %>Service) toResponse(item *models.<%= it.entityName
|
|
|
317
351
|
<% if (it.updatedAt) { %>
|
|
318
352
|
UpdatedAt: item.UpdatedAt,
|
|
319
353
|
<% } %>
|
|
320
|
-
<% it.associations.filter(a => a.
|
|
321
|
-
<%= assoc.
|
|
354
|
+
<% it.associations.filter(a => a.owns).forEach((assoc) => { %>
|
|
355
|
+
<%= assoc.fkField %>: item.<%= assoc.fkField %>,
|
|
322
356
|
<% }) %>
|
|
323
357
|
}
|
|
358
|
+
// Relations loaded by ?join= or eager loading. A relation onto an auth
|
|
359
|
+
// entity is left out: those rows are for service callers only.
|
|
360
|
+
<% it.associations.filter(a => !a.hidden).forEach((assoc) => { %>
|
|
361
|
+
<% if (assoc.type === 'ManyToOne' || assoc.type === 'OneToOne') { %>
|
|
362
|
+
if item.<%= assoc.fieldName %> != nil {
|
|
363
|
+
related := (&<%= assoc.name %>Service{}).toResponse(item.<%= assoc.fieldName %>)
|
|
364
|
+
response.<%= assoc.fieldName %> = &related
|
|
365
|
+
}
|
|
366
|
+
<% } else if (assoc.type === 'OneToMany' || (assoc.type === 'ManyToMany' && assoc.join)) { %>
|
|
367
|
+
for i := range item.<%= assoc.fieldName %> {
|
|
368
|
+
response.<%= assoc.fieldName %> = append(response.<%= assoc.fieldName %>, (&<%= assoc.name %>Service{}).toResponse(&item.<%= assoc.fieldName %>[i]))
|
|
369
|
+
}
|
|
370
|
+
<% } %>
|
|
371
|
+
<% }) %>
|
|
372
|
+
return response
|
|
324
373
|
}
|