In the authorization expression of some function, I’d like to check that the user provider type is not anonymous. In plain javascript, that would be:

context.user.identities[0].provider_type != "anon-user"

How can I achieve the same thing in authorization expression? I don’t know how to access the first element of the array. I tried "%%user.identities.first.providerType"and "%%user.identities[0].providerType" but none of these works.

MongoDB team, any idea? Is that possible or not?

Hi Jean-Baptiste,

Please try using %%user.identities[0].provider_type

You could also make the expression call a function and within the function use context.user.identities[0].provider_type to return the value.

Regards
Manny

I couldn’t get either of these suggestions to work. Both returned "rule not matched for function \"myFunction\"".

In the end I had to add a check in the function body, which is a shame because it results in a 200 response. Works though.

// Check that this is a logged in user (not anon)
function isLocalUser() {
  if (!context.user) return false

  const identities = context.user.identities || []

  const localUserIdentities = identities.filter(
    (i) => i["provider_type"] === "local-userpass"
  )

  const isLocalUser = localUserIdentities.length === 1
  return isLocalUser
}

function myFunction() {
  if (context.functions.execute("isLocalUser") !== true) {
    return { error: "Not authorized" }
  }
  
  return { "foo": "bar }
}

Little old, but I got this working. Couldn’t find it documented anywhere.

{
  "%%user.identities": {
    "$elemMatch": {
      "provider_type": "anon-user"
    }
  }
}
1 Like