var context = $evaluation.getContext();
var permission = $evaluation.getPermission()
var identity = context.getIdentity();
var attributes = identity.getAttributes();

var resource = permission.getResource()

print("============= " + resource.getName() + "[" + resource.getOwner() + "," + resource.getResourceServer()  + "] =================")

var extra_claims = permission.claims
var ctx = extra_claims["context"]
if(ctx !== null){
  ctx = ctx.toArray()[0]
  if(ctx != null){
    var resource_attribute = resource.getAttribute(ctx)
    if(resource_attribute != null) $evaluation.grant();
    else $evaluation.deny();
  } else $evaluation.deny();
} else $evaluation.deny(); 

//print(resource.getAttributes())
//print('context :' + context)
//print('context attributes ' + context.getAttributes().toMap().keySet() )
//print('permission ' + permission)
//print('permission claims ' + permission.claims)
//print('permission resourceServer ' + permission.resourceServer)
//print('Identity = :' + identity)
//print('user attributes: ' + attributes.toMap().keySet());

//print('context client id is ' + context.getAttributes().getValue('kc.client.id').asString(0))

//var aud = attributes.getValue('aud')
//if (aud === null){
//  print("aud is null")
//}else{
//  aud = aud.asString(0)
//  print('aud is ' + aud)
//  print('context client id is ' + context.getAttributes().getValue('kc.client.id').asString(0))
//  var perm = attributes.getValue('kc.client.' + aud + '.roles')
//  print(perm)
//}
