Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
variableToSet: string = ResourceConstants.SNIPPETS.IsDynamicGroupAuthorizedVariable,
defaultValue: Expression = raw(`$util.defaultIfNull($${variableToSet}, false)`)
): Expression {
if (!rules || rules.length === 0) {
return comment(`No Dynamic Group Authorization Rules`);
}
let groupAuthorizationExpressions = [];
for (const rule of rules) {
const groupsAttribute = rule.groupsField || DEFAULT_GROUPS_FIELD;
const groupClaimAttribute = rule.groupClaim || DEFAULT_GROUP_CLAIM;
groupAuthorizationExpressions = groupAuthorizationExpressions.concat(
comment(`Authorization rule: { allow: ${rule.allow}, groupsField: "${groupsAttribute}", groupClaim: "${groupClaimAttribute}" }`),
set(ref('allowedGroups'), ref(`util.defaultIfNull($${variableToCheck}.${groupsAttribute}, [])`)),
this.setUserGroups(rule.groupClaim),
forEach(ref('userGroup'), ref('userGroups'), [
iff(raw('$util.isList($allowedGroups)'), iff(raw(`$allowedGroups.contains($userGroup)`), set(ref(variableToSet), raw('true')))),
iff(raw(`$util.isString($allowedGroups)`), iff(raw(`$allowedGroups == $userGroup`), set(ref(variableToSet), raw('true')))),
])
);
}
// check for group claim here
return block('Dynamic Group Authorization Checks', [set(ref(variableToSet), defaultValue), ...groupAuthorizationExpressions]);
}
// tslint:disable-next-line
set(ref('identityValue'), raw(`$util.defaultIfNull($ctx.identity.claims.get("${rawUsername}"), $util.defaultIfNull($ctx.identity.claims.get("${identityAttribute}"), "${NONE_VALUE}"))`)) :
set(ref('identityValue'), raw(`$util.defaultIfNull($ctx.identity.claims.get("${identityAttribute}"), "${NONE_VALUE}")`)),
iff(
raw(`$util.isList($${allowedOwnersVariable})`),
forEach(ref('allowedOwner'), ref(allowedOwnersVariable), [
iff(
raw(`$allowedOwner == $identityValue`),
set(ref(variableToSet), raw('true'))),
])
),
iff(
raw(`$util.isString($${allowedOwnersVariable})`),
iff(
raw(`$${allowedOwnersVariable} == $identityValue`),
set(ref(variableToSet), raw('true'))),
)
)
ruleNumber++
}
return block('Owner Authorization Checks', [
set(ref(variableToSet), defaultValue),
...ownerAuthorizationExpressions
])
}
}
return new Resolver({
ApiId: Fn.GetAtt(ResourceConstants.RESOURCES.GraphQLAPILogicalID, 'ApiId'),
DataSourceName: ModelResourceIDs.ModelTableResourceID(relatedType.name.value),
FieldName: field,
TypeName: type,
RequestMappingTemplate: print(
compoundExpression([
...setup,
DynamoDBMappingTemplate.query(queryArguments)
])
),
ResponseMappingTemplate: print(
compoundExpression([
iff(raw('!$result'), set(ref('result'), ref('ctx.result'))),
raw('$util.toJson($result)')
])
)
}).dependsOn([ResourceConstants.RESOURCES.GraphQLSchemaLogicalID, ModelResourceIDs.ModelTableResourceID(relatedType.name.value)])
}
ResourceFactory.prototype.makeDeleteResolver = function (type, nameOverride) {
var fieldName = nameOverride ? nameOverride : graphql_transformer_common_1.graphqlName('delete' + graphql_transformer_common_1.toUpper(type));
return new appSync_1.default.Resolver({
ApiId: cloudform_1.Fn.GetAtt(graphql_transformer_common_1.ResourceConstants.RESOURCES.GraphQLAPILogicalID, 'ApiId'),
DataSourceName: cloudform_1.Fn.GetAtt(graphql_transformer_common_1.ModelResourceIDs.ModelTableDataSourceID(type), 'Name'),
FieldName: fieldName,
TypeName: 'Mutation',
RequestMappingTemplate: graphql_mapping_template_1.print(graphql_mapping_template_1.compoundExpression([
graphql_mapping_template_1.ifElse(graphql_mapping_template_1.ref(graphql_transformer_common_1.ResourceConstants.SNIPPETS.AuthCondition), graphql_mapping_template_1.compoundExpression([
graphql_mapping_template_1.set(graphql_mapping_template_1.ref('condition'), graphql_mapping_template_1.ref(graphql_transformer_common_1.ResourceConstants.SNIPPETS.AuthCondition)),
graphql_mapping_template_1.qref('$condition.put("expression", "$condition.expression AND attribute_exists(#id)")'),
graphql_mapping_template_1.qref('$condition.expressionNames.put("#id", "id")')
]), graphql_mapping_template_1.set(graphql_mapping_template_1.ref('condition'), graphql_mapping_template_1.obj({
expression: graphql_mapping_template_1.str("attribute_exists(#id)"),
expressionNames: graphql_mapping_template_1.obj({
"#id": graphql_mapping_template_1.str("id")
})
}))),
graphql_mapping_template_1.DynamoDBMappingTemplate.deleteItem({
key: graphql_mapping_template_1.obj({
id: graphql_mapping_template_1.ref('util.dynamodb.toDynamoDBJson($ctx.args.input.id)')
}),
condition: graphql_mapping_template_1.ref('util.toJson($condition)')
})
])),
ResponseMappingTemplate: graphql_mapping_template_1.print(graphql_mapping_template_1.ref('util.toJson($context.result)'))
const fieldName = nameOverride ? nameOverride : graphqlName('search' + plurality(toUpper(type)));
return new AppSync.Resolver({
ApiId: Fn.GetAtt(ResourceConstants.RESOURCES.GraphQLAPILogicalID, 'ApiId'),
DataSourceName: Fn.GetAtt(ResourceConstants.RESOURCES.ElasticsearchDataSourceLogicalID, 'Name'),
FieldName: fieldName,
TypeName: queryTypeName,
RequestMappingTemplate: print(
compoundExpression([
set(ref('indexPath'), str(`/${type.toLowerCase()}/doc/_search`)),
set(ref('nonKeywordFields'), list(nonKeywordFields)),
ifElse(
ref('util.isNullOrEmpty($context.args.sort)'),
compoundExpression([set(ref('sortDirection'), str('desc')), set(ref('sortField'), str(primaryKey))]),
compoundExpression([
set(ref('sortDirection'), raw('$util.defaultIfNull($context.args.sort.direction, "desc")')),
set(ref('sortField'), raw(`$util.defaultIfNull($context.args.sort.field, "${primaryKey}")`)),
])
),
ElasticsearchMappingTemplate.searchItem({
path: str('$indexPath'),
size: ifElse(ref('context.args.limit'), ref('context.args.limit'), int(10), true),
search_after: list([str('$context.args.nextToken')]),
query: ifElse(
ref('context.args.filter'),
ref('util.transform.toElasticsearchQueryDSL($ctx.args.filter)'),
obj({
match_all: obj({}),
})
),
sort: list([
raw(
'{ #if($nonKeywordFields.contains($sortField))\
return new AppSync.Resolver({
ApiId: Fn.GetAtt(ResourceConstants.RESOURCES.GraphQLAPILogicalID, 'ApiId'),
DataSourceName: Fn.GetAtt(ModelResourceIDs.ModelTableDataSourceID(type), 'Name'),
FieldName: fieldName,
TypeName: queryTypeName,
RequestMappingTemplate: print(
compoundExpression([
set(ref('limit'), ref(`util.defaultIfNull($context.args.limit, ${defaultPageLimit})`)),
set(
ref(requestVariable),
obj({
version: isSyncEnabled ? str('2018-05-29') : str('2017-02-28'),
limit: ref('limit'),
})
),
iff(ref('context.args.nextToken'), set(ref(`${requestVariable}.nextToken`), str('$context.args.nextToken'))),
iff(
ref('context.args.filter'),
set(ref(`${requestVariable}.filter`), ref('util.parseJson("$util.transform.toDynamoDBFilterExpression($ctx.args.filter)")'))
),
ifElse(
raw(`!$util.isNull($${ResourceConstants.SNIPPETS.ModelQueryExpression})
&& !$util.isNullOrEmpty($${ResourceConstants.SNIPPETS.ModelQueryExpression}.expression)`),
compoundExpression([
qref(`$${requestVariable}.put("operation", "Query")`),
qref(`$${requestVariable}.put("query", $${ResourceConstants.SNIPPETS.ModelQueryExpression})`),
ifElse(
raw(`!$util.isNull($ctx.args.sortDirection) && $ctx.args.sortDirection == "DESC"`),
set(ref(`${requestVariable}.scanIndexForward`), bool(false)),
set(ref(`${requestVariable}.scanIndexForward`), bool(true))
),
]),
type
)}Input.${this.typePrimaryKeyMap.get(type)}`;
}
const reqFileName = `${mutationTypeName}.${fieldName}.req.vtl`;
const resFileName = `${mutationTypeName}.${fieldName}.res.vtl`;
const reqTemplate = print(
compoundExpression([
set(ref('cols'), list([])),
set(ref('vals'), list([])),
forEach(ref('entry'), ref(`ctx.args.create${toUpper(type)}Input.keySet()`), [
set(ref('discard'), ref(`cols.add($entry)`)),
set(ref('discard'), ref(`vals.add("'$ctx.args.create${toUpper(type)}Input[$entry]'")`)),
]),
set(ref('valStr'), ref('vals.toString().replace("[","(").replace("]",")")')),
set(ref('colStr'), ref('cols.toString().replace("[","(").replace("]",")")')),
RelationalDBMappingTemplate.rdsQuery({
statements: list([str(createSql), str(selectSql)]),
}),
])
);
const resTemplate = print(ref('utils.toJson($utils.parseJson($utils.rds.toJsonString($ctx.result))[1][0])'));
fs.writeFileSync(`${this.resolverFilePath}/${reqFileName}`, reqTemplate, 'utf8');
fs.writeFileSync(`${this.resolverFilePath}/${resFileName}`, resTemplate, 'utf8');
let resolver = new AppSync.Resolver({
ApiId: Fn.Ref(ResourceConstants.PARAMETERS.AppSyncApiId),
DataSourceName: Fn.GetAtt(ResourceConstants.RESOURCES.RelationalDatabaseDataSource, 'Name'),
TypeName: mutationTypeName,
public collectAuthCondition(): Expression {
return block('Collect Auth Condition', [
set(
ref(ResourceConstants.SNIPPETS.AuthCondition),
raw(
`$util.defaultIfNull($authCondition, ${print(
obj({
expression: str(''),
expressionNames: obj({}),
expressionValues: obj({}),
})
)})`
)
),
set(ref('totalAuthExpression'), str('')),
comment('Add dynamic group auth conditions if they exist'),
iff(
ref('groupAuthExpressions'),
forEach(ref('authExpr'), ref('groupAuthExpressions'), [
const queryObj = DynamoDBMappingTemplate.query(queryArguments);
return new Resolver({
ApiId: Fn.GetAtt(ResourceConstants.RESOURCES.GraphQLAPILogicalID, 'ApiId'),
DataSourceName: Fn.GetAtt(ModelResourceIDs.ModelTableDataSourceID(relatedType.name.value), 'Name'),
FieldName: field,
TypeName: type,
RequestMappingTemplate: print(
compoundExpression([
...setup,
queryObj
])
),
ResponseMappingTemplate: print(
compoundExpression([
iff(raw('!$result'), set(ref('result'), ref('ctx.result'))),
raw('$util.toJson($result)')
])
)
}).dependsOn(ResourceConstants.RESOURCES.GraphQLSchemaLogicalID)
}
public dynamicGroupAuthorizationExpressionForReadOperations(
rules: AuthRule[],
variableToCheck: string = 'ctx.result',
variableToSet: string = ResourceConstants.SNIPPETS.IsDynamicGroupAuthorizedVariable,
defaultValue: Expression = raw(`$util.defaultIfNull($${variableToSet}, false)`)
): Expression {
if (!rules || rules.length === 0) {
return comment(`No Dynamic Group Authorization Rules`)
}
let groupAuthorizationExpressions = [];
for (const rule of rules) {
const groupsAttribute = rule.groupsField || DEFAULT_GROUPS_FIELD
groupAuthorizationExpressions = groupAuthorizationExpressions.concat(
comment(`Authorization rule: { allow: ${rule.allow}, groupsField: "${groupsAttribute}" }`),
set(ref('allowedGroups'), ref(`util.defaultIfNull($${variableToCheck}.${groupsAttribute}, [])`)),
forEach(ref('userGroup'), ref('userGroups'), [
iff(
raw('$util.isList($allowedGroups)'),
iff(
raw(`$allowedGroups.contains($userGroup)`),
set(ref(variableToSet), raw('true'))),
),
iff(
raw(`$util.isString($allowedGroups)`),
iff(
raw(`$allowedGroups == $userGroup`),
set(ref(variableToSet), raw('true'))),
)
])
)
}