fetchAndQuery is a generic function that wraps a database fetch and query. A query has potential side effects in the database (update, delete, etc). The fetch is used to know which rbac object the action should be asserted on **before** the query runs. The returns from the fetch are only used to ass
( logger slog.Logger, authorizer rbac.Authorizer, action policy.Action, fetchFunc Fetch, queryFunc Query, )
| 1072 | // **before** the query runs. The returns from the fetch are only used to |
| 1073 | // assert rbac. The final return of this function comes from the Query function. |
| 1074 | func fetchAndQuery[ |
| 1075 | ObjectType rbac.Objecter, |
| 1076 | ArgumentType any, |
| 1077 | Fetch func(ctx context.Context, arg ArgumentType) (ObjectType, error), |
| 1078 | Query func(ctx context.Context, arg ArgumentType) (ObjectType, error), |
| 1079 | ]( |
| 1080 | logger slog.Logger, |
| 1081 | authorizer rbac.Authorizer, |
| 1082 | action policy.Action, |
| 1083 | fetchFunc Fetch, |
| 1084 | queryFunc Query, |
| 1085 | ) Query { |
| 1086 | return func(ctx context.Context, arg ArgumentType) (empty ObjectType, err error) { |
| 1087 | // Fetch the rbac subject |
| 1088 | act, ok := ActorFromContext(ctx) |
| 1089 | if !ok { |
| 1090 | return empty, ErrNoActor |
| 1091 | } |
| 1092 | |
| 1093 | // Fetch the database object |
| 1094 | object, err := fetchFunc(ctx, arg) |
| 1095 | if err != nil { |
| 1096 | return empty, xerrors.Errorf("fetch object: %w", err) |
| 1097 | } |
| 1098 | |
| 1099 | // Authorize the action |
| 1100 | err = authorizer.Authorize(ctx, act, action, object.RBACObject()) |
| 1101 | if err != nil { |
| 1102 | return empty, logNotAuthorizedError(ctx, logger, err) |
| 1103 | } |
| 1104 | |
| 1105 | return queryFunc(ctx, arg) |
| 1106 | } |
| 1107 | } |
| 1108 | |
| 1109 | // fetchWithPostFilter is like fetch, but works with lists of objects. |
| 1110 | // SQL filters are much more optimal. |
no test coverage detected