ScriptRunner how to addUserToGroup() on behalf of some other user

I need a post script which can add or remove users from groups. I've done something like that:
...

import com.atlassian.jira.user.util.UserUtil

def userUtil = ComponentAccessor.getUserUtil()
StringBuffer sb_debug = new StringBuffer()
def usersField = customFieldManager.getCustomFieldObjectByName("Access for users")
def users = issue.getCustomFieldValue(usersField)
for (def user: users){ //com.atlassian.jira.user.DelegatingApplicationUser
sb_debug << "Starting work with:" + user.getName() + "\n"
for (com.atlassian.crowd.embedded.api.Group group: groups){
sb_debug << "Adding " + user.getName() + " to " + group.getName() + "\n"

//Adding User
groupManager.addUserToGroup(user,group)
//userUtil.removeUserFromGroup(userUtil.getGroup("jira-users") ,userUtil.getUser(username))
//Removing User
userUtil.removeUserFromGroup(group,user)
}
}

...

 It is working, but how can I define, by which account should be user added or removed from group?
If I perform transition and run script, using account without "jira-administrators" group, script will add/delete user to/from group despite that fact, using current account. (Terrible =)

Here is a simple way to do it for issue field:

def userManager = ComponentAccessor.getComponent(UserManager)
def user = userManager.getUserByName("JiraAdmin")
def updateValidationResult = issueService.validateUpdate(user, issue.id, issueInputParameters)
if (updateValidationResult.isValid()) {
issueService.update(user, updateValidationResult)
 }

But how to do it for User ? (adding or deleting from group)
Please, help! 

Thank you! )
 

 

2 answers

As you've probably already noticed, the GroupManager and UserUtil classes don't have method signatures that take an acting user for adding users to groups or removing them from groups. The IssueService.validateUpdate method does, and there are other methods in the Atlassian API that also take an "acting user" parameter.

If you want to change the acting user, you can do something similar to what gets done by the built-in Switch User script and manipulate the session variables:

import com.onresolve.scriptrunner.runner.rest.common.ServletRequestThreadLocal
import com.atlassian.seraph.auth.DefaultAuthenticator
import com.atlassian.jira.component.ComponentAccessor

def session = ServletRequestThreadLocal.get().getSession()
def currentUser = session.getAttribute(DefaultAuthenticator.LOGGED_IN_KEY)
try {
    //Change the current user
    def userUtil = ComponentAccessor.getUserUtil()
    def targetUser = userUtil.getUser("Some username")
    session.setAttribute(DefaultAuthenticator.LOGGED_IN_KEY, targetUser)

    //Do the work you want to do as the target user
    //I just copied your code, did not actually test it
    StringBuffer sb_debug = new StringBuffer()
    def usersField = customFieldManager.getCustomFieldObjectByName("Access for users")
    def users = issue.getCustomFieldValue(usersField)
    for (def user: users){ //com.atlassian.jira.user.DelegatingApplicationUser
        sb_debug &lt;&lt; "Starting work with:" + user.getName() + "\n"
        for (com.atlassian.crowd.embedded.api.Group group: groups){
            sb_debug &lt;&lt; "Adding " + user.getName() + " to " + group.getName() + "\n"
            //Adding User
            groupManager.addUserToGroup(user,group)
            // userUtil.removeUserFromGroup(userUtil.getGroup("jira-users") ,userUtil.getUser(username))
            //Removing User
            userUtil.removeUserFromGroup(group,user)
        }
    }
}
catch (Exception e) {
    //Do some error handling here if you need to
    log.error("Error adding removing users in post function")
}
finally {
    //Set the current user back again
    session.setAttribute(DefaultAuthenticator.LOGGED_IN_KEY, currentUser)
}

>>how can I define, by which account should be user added or removed from group?

You can go to System-Audit log

then look for "group management" events. 

I've got following:

DateAuthorEvent categoryChange summaryChanged objectActions
18/Aug/16 7:46 PMJIRAgroup management

User added to group

jira-usersJIRA Internal Directory

No =))) I mean how can I define in code a user, by which adding or removing from group should be done. I want to add/remove person to/from group by selecting user. 
Right now script runner performs this by using account of user who executed script by performing issue transition. That is the problem... ) 

Wrote very sophisticated. 

  1. In script select/define user account by its name
  2. Delete/Add to group user on behalf of selected account 

Suggest an answer

Log in or Join to answer
Community showcase
Sarah Schuster
Posted Jan 29, 2018 in Jira

What are common themes you've seen across successful & failed Jira Software implementations?

Hey everyone! My name is Sarah Schuster, and I'm a Customer Success Manager in Atlassian specializing in Jira Software Cloud. Over the next few weeks I will be posting discussion topics (8 total) to ...

3,338 views 14 20
Join discussion

Atlassian User Groups

Connect with like-minded Atlassian users at free events near you!

Find a group

Connect with like-minded Atlassian users at free events near you!

Find my local user group

Unfortunately there are no AUG chapters near you at the moment.

Start an AUG

You're one step closer to meeting fellow Atlassian users at your local meet up. Learn more about AUGs

Groups near you
Atlassian Team Tour

Join us on the Team Tour

We're bringing product updates and pro tips on teamwork to ten cities around the world.

Save your spot