how to check whether a user is able to update or insert a document in marklogic database?

Viewed 148

how to check whether a user is able to update or insert any document in marklogic database or not ?

For example , there are 4 user and some have permission to update and some have permission to read document in marklogic database

try{
    let $uri := abc.xml
    let $doc : <a/>
    if (condition)
    then check whether the current user is able to update or insert the doc in marklogic or not , if it is not then throw fn:error()
    else 
    xdmp:document-insert($uri,$doc) (:it will throw error, when user have no permission to insert the doc:)
    }
catch($e)
{$e}
1 Answers

The permissions that a user needs in order to insert and update a document will depend upon the user's explicit roles and permissions, as well as default permissions and any explicit permissions set on the document.

https://docs.marklogic.com/guide/admin/security#chapter

enter image description here

https://docs.marklogic.com/xdmp:document-insert

Required Privileges If a new document is inserted, the unprotected-uri privilege (only if the URI is not protected), the any-uri privilege, or an appropriate URI privilege is also needed. If adding an unprotected collection to a document, the unprotected-collections privilege is needed; if adding a protected collection, the user must have either permissions to update the collection or the any-collection privilege.

If you are updating a document, then you must have the necessary permissions specified for that document (which can include default permissions).

Use xdmp:document-get-permissions to return which roles have which permission on that specific URI and then intersect that with roles attached to the user of interest, and you will know whether the user can access or update the document or not.

So, to check whether a user has the ability to insert or update a URI, you would want to get that users roles and then see if the permissions from the default permissions or the document permissions have that role and the insert or update capability:

xquery version "1.0-ml";
import module namespace sec="http://marklogic.com/xdmp/security" at "/MarkLogic/security.xqy";
let $name := "user-foo"
let $uri := "/bar.xml"
let $user-roles := xdmp:invoke-function(
  function(){ sec:user-get-roles($name) }, 
  <options xmlns="xdmp:eval">
    <database>{xdmp:security-database()}</database>
  </options>)
let $permissions := (xdmp:default-permissions(), xdmp:document-get-permissions($uri))
return
 exists($permissions[sec:capability=('insert', 'update') and sec:role-id/xdmp:role-name(.) = $user-roles])
Related