-
Notifications
You must be signed in to change notification settings - Fork 2
/
permissions.go
95 lines (79 loc) · 2.7 KB
/
permissions.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
package node
import (
"fmt"
"regexp"
"github.com/teamkeel/keel/codegen"
"github.com/teamkeel/keel/permissions"
"github.com/teamkeel/keel/proto"
)
var (
sqlPlaceholderRegexp = regexp.MustCompile(`\?`)
)
// writePermissions writes a JS object where the keys are function names
// and the values a list of functions that can be run to check permissions
// for a list of records.
func writePermissions(w *codegen.Writer, schema *proto.Schema) {
w.Writeln("const permissionFns = {")
w.Indent()
for _, model := range schema.Models {
for _, action := range model.Actions {
if action.Implementation != proto.ActionImplementation_ACTION_IMPLEMENTATION_CUSTOM {
continue
}
// TODO: think about how to handle error's here
sql, values, _ := permissions.ToSQL(schema, model, action)
if sql == "" {
w.Writef("%s: [],\n", action.Name)
continue
}
w.Writef("%s: [\n", action.Name)
w.Indent()
w.Writeln("async (records, ctx, db) => {")
w.Indent()
w.Write("const { rows } = await sql`")
valueIdx := 0
// Kysely uses JS interpolation rather than placeholders in the query,
// so we replace all the "?"'s with JS interpolations of the appropriate value
sql = sqlPlaceholderRegexp.ReplaceAllStringFunc(sql, func(_ string) string {
v := values[valueIdx]
valueIdx++
switch v.Type {
case permissions.ValueIdentityID:
return "${ctx.identity ? ctx.identity.id : ''}"
case permissions.ValueIdentityEmail:
return "${ctx.identity ? ctx.identity.email : ''}"
case permissions.ValueNow:
return "${ctx.now()}"
case permissions.ValueIsAuthenticated:
return "${ctx.isAuthenticated}"
case permissions.ValueRecordIDs:
// Need to use sql.join() here:
// Docs: https://kysely-org.github.io/kysely/interfaces/Sql.html#join
// Note: sql.join annoyingly throws an exception for zero length arrays
return "${(records.length > 0) ? sql.join(records.map(x => x.id)) : []}"
case permissions.ValueString:
// Note: StringValue is already wrapped in double quotes
return fmt.Sprintf(`${%s}`, v.StringValue)
case permissions.ValueNumber:
return fmt.Sprintf(`${%d}`, v.NumberValue)
case permissions.ValueHeader:
return fmt.Sprintf(`${ctx.headers["%s"] || ""}`, v.HeaderKey)
case permissions.ValueSecret:
return fmt.Sprintf(`${ctx.secrets["%s"] || ""}`, v.SecretKey)
}
return ""
})
w.Write(sql)
w.Writeln("`.execute(db);")
// Permissions pass if the same number of rows are returned.
w.Writeln("return rows.length === records.length;")
w.Dedent()
w.Writeln("},")
w.Dedent()
w.Writeln("],")
}
}
w.Dedent()
w.Writeln("}")
w.Writeln("module.exports.permissionFns = permissionFns;")
}