Assigning roles in the sync function

#1

Is it possible to assign roles to users inside the sync function in the same way you can assign user access to channels?

I’m trying to make it possible from some users to be able to read & write to certain docs in a channel, where others can only read. I thought roles sounded like a suitable solution.

#2

There is a good example in the documentation, you can use requireRole("role:editor") to force creation of documents only by editors. Here is the link to the docs http://developer.couchbase.com/documentation/mobile/1.2/develop/guides/sync-gateway/sync-function-api-guide/validation/index.html

Regards,
Vlad

#3

Thanks, but my question was about how to assign roles, the requireRole method does not do this. I think I’ve figured it out though.

The answer is to call the role() method, in the same way as you’d call the access() method, except that it doesn’t seem to take an array as the first argument. I’ve looked in the docs here and here and can’t find any mention of it. Why isn’t role() documented? Is it not supposed to be used? Feels like its quite important.

Also, regarding the “docs” - there’s conflicting descriptions of how to use requireRole. In some places it says requireRole(["admin", "old-timer"]); and others it’s requireRole("role:editor");. From my experiments it seems that you can supply an array or a singleton, but you should not prefix the role name with "role:".

I know I’ve asked many times for documentation to be updated, and it never is. So I won’t ask any more. How about putting into github though so we can submit PRs?

#4

The documentation is definitely messy. From the link you posted :

The access() function can also operate on roles. If a user name string begins with role: then the remainder of the string is interpreted as a role name. There’s no ambiguity here, because “:” is an illegal character in a user or role name.

So it seems access(“role:whatever”) is what you are looking for. Haven’t tried it myself, in my projects, I am adding roles as part of the user creation, via the admin rest API

Regards,
Vlad

#5

Thanks agin, but from what I can gather, access("role:whatever", channels) assigns users with the role whatever channel access to channels. But it does not assign roles to users. Which is what my question is about. I believe that calling the undocumented role() method is the only way to do this in the sync function.

#6

The role method is documented here:
http://developer.couchbase.com/documentation/mobile/1.2/develop/guides/sync-gateway/sync-function-api-guide/routing/index.html