Missed Team ’24? Catch up on announcements here.

×
Create
cancel
Showing results for 
Search instead for 
Did you mean: 
Sign up Log in

how to run as specific user in script runner

이경언 February 7, 2017

I want to change user status from active to inactive.

So I search this site.https://www.adaptavist.com/doco/display/SFJ/Automatically+deactivate+inactive+JIRA+users

And My JIRA version is 7.1.9

So I run this code.

import com.atlassian.crowd.embedded.api.CrowdService
import com.atlassian.crowd.embedded.api.UserWithAttributes
import com.atlassian.crowd.embedded.impl.ImmutableUser
import com.atlassian.jira.bc.user.UserService
import com.atlassian.jira.component.ComponentAccessor
import com.atlassian.jira.user.ApplicationUser
import com.atlassian.jira.user.ApplicationUsers
import com.atlassian.jira.user.util.UserUtil
 
int numOfDays = 100 // Number of days the user was not logged in
Date dateLimit = (new Date())- numOfDays
 
UserUtil userUtil = ComponentAccessor.userUtil
CrowdService crowdService = ComponentAccessor.crowdService
UserService userService = ComponentAccessor.getComponent(UserService)
ApplicationUser updateUser
UserService.UpdateUserValidationResult updateUserValidationResult
 
long count = 0
 
userUtil.getUsers().findAll{it.isActive()}.each {
    UserWithAttributes user = crowdService.getUserWithAttributes(it.getName())
        String lastLoginMillis = user.getValue('login.lastLoginMillis')
        if (lastLoginMillis?.isNumber()) {
            Date d = new Date(Long.parseLong(lastLoginMillis))
            if (d.before(dateLimit)) {
                updateUser = ApplicationUsers.from(ImmutableUser.newUser(user).active(false).toUser())
                updateUserValidationResult = userService.validateUpdateUser(updateUser)
                if (updateUserValidationResult.isValid()) {
                    userService.updateUser(updateUserValidationResult)
                    log.info "Deactivated ${updateUser.name}"
                    count++
                } else {
                    log.error "Update of ${user.name} failed: ${updateUserValidationResult.getErrorCollection().getErrors().entrySet().join(',')}"
                }
            }
        }
}
 
"${count} users deactivated.\n"

And this code is registered service.

But error this code. here is log


Error Messages: [You do not have the permission to update users.]

 

So I have to  run as specific user in script runner. Help Me ^^

2 answers

Comments for this post are closed

Community moderators have prevented the ability to post new answers.

Post a new question

1 vote
Priyanka Lavania
Community Leader
Community Leader
Community Leaders are connectors, ambassadors, and mentors. On the online community, they serve as thought leaders, product experts, and moderators.
August 2, 2019

Hi,

We had the same situation, where any non Jira-admin IT team person should be able to deactivate a user and also remove the user from Components and Project Lead. We were able to achieve this using script post function on a transition.

We are capturing the user to be deactivated form "Employee" custom field.

The code does the following: elevation of rights (switch non admin user to admin user)

Checks if Employee is component lead, if yes change to unassigned

Checks if Employee is project lead, if yes assign to default user

Additionally send success message and also adds statistics as comment on the issue for future tracking.

JIRA version Server: 7.13.3

Here is the code: 



import com.atlassian.jira.bc.user.ApplicationUserBuilderImpl
import com.atlassian.jira.bc.user.UserService
import com.atlassian.jira.component.ComponentAccessor
import com.atlassian.jira.user.ApplicationUser;
import com.atlassian.crowd.embedded.api.User
import com.atlassian.crowd.embedded.impl.ImmutableUser
import com.atlassian.jira.user.util.UserManager
import com.onresolve.scriptrunner.runner.util.UserMessageUtil
import com.atlassian.crowd.embedded.api.UserWithAttributes
import com.atlassian.crowd.embedded.api.CrowdService
import com.atlassian.jira.user.ApplicationUsers
import com.atlassian.jira.bc.project.component.MutableProjectComponent
import com.atlassian.jira.user.DelegatingApplicationUser

CrowdService crowdService = ComponentAccessor.crowdService
UserManager userManager = ComponentAccessor.getUserManager()
UserService userService = ComponentAccessor.getComponent(UserService.class)


String adminUsername = "admin.user"

//Elevate user access to admin user
def jiraAuthenticationContext = ComponentAccessor.jiraAuthenticationContext
def adminUser = ComponentAccessor.userManager.getUserByKey(adminUsername)
def originalUser = jiraAuthenticationContext.loggedInUser
try {
//Swicth User
jiraAuthenticationContext.setLoggedInUser(adminUser)
}
finally {
// jiraAuthenticationContext.setLoggedInUser(originalUser)
}

def issueManager = ComponentAccessor.issueManager

def customFieldManager = ComponentAccessor.getCustomFieldManager()
def usern = customFieldManager.getCustomFieldObjectByName("Employee")
String username1 = issue.getCustomFieldValue(usern).name
ApplicationUser user = ComponentAccessor.getUserManager().getUserByName(username1);
String username = user.name

def commentManager = ComponentAccessor.commentManager

def projectLeadedBy = ComponentAccessor.userUtil.getProjectsLeadBy(user);
def componentsLeadedBy = ComponentAccessor.projectComponentManager.findComponentsByLead(username)

def projectManager = ComponentAccessor.getProjectManager();
def projectComponentManager = ComponentAccessor.getProjectComponentManager();

def test = true
def user1 = userManager.getUserByName(username)
def projectlead = ": "
def complead = ": "
def projcount = 0
def compcount = 0

if (jiraAuthenticationContext.getLoggedInUser() == ComponentAccessor.userManager.getUserByKey(adminUsername))
{

if (!componentsLeadedBy && !projectLeadedBy)
log.info "username doesn't lead any component or project"
else {
//remove username from project lead roles
if (projectLeadedBy.size() > 0)
for (project in projectLeadedBy) {
if (projcount != 0){
projectlead = projectlead+", "}

projectManager.updateProject(project, project.name, project.description, "user.dashboard", project.url, project.assigneeType);
projectlead = projectlead+project.name
projcount = projcount+1
}

//remove username from component lead roles
if (componentsLeadedBy.size() > 0)
for (component in componentsLeadedBy) {
if (compcount != 0){
complead = complead+", "}
MutableProjectComponent newComponent = MutableProjectComponent.copy(component)
newComponent.setLead("")
projectComponentManager.update(newComponent)
complead = complead+newComponent.name
compcount = compcount +1
}

}
def updateUser = userService.newUserBuilder(user1).active(false).build()

def updateUserValidationResult = userService.validateUpdateUser(updateUser)

if (updateUserValidationResult.isValid()) {
userService.updateUser(updateUserValidationResult)
UserMessageUtil.success ("Deactivated ${user.name}")
if(projcount !=0 && compcount!=0){
commentManager.create(issue, adminUsername, "Jira Statistics of ${user.name}: \n Project Lead on ${projcount} Project/s ${projectlead}\n Component Lead on ${compcount} Component/s ${complead} \n Deactivated ${user.name}", false)
}else if(projcount !=0 && compcount==0){
commentManager.create(issue, adminUsername, "Jira Statistics of ${user.name}: \n Project Lead on ${projcount} Project/s ${projectlead}\n Deactivated ${user.name}", false)
}else
if(projcount ==0 && compcount!=0){
commentManager.create(issue, adminUsername, "Jira Statistics of ${user.name}: \n Component Lead on ${compcount} Component/s ${complead} \n Deactivated ${user.name}", false)
}else
commentManager.create(issue, adminUsername, "Deactivated ${user.name}", false)
} else {

UserMessageUtil.error ("Update of ${user.name} failed: ${updateUserValidationResult.getErrorCollection().getErrors().entrySet().join(',')}\n")
commentManager.create (issue, adminUsername,"Update of ${user.name} failed: ${updateUserValidationResult.getErrorCollection().getErrors().entrySet().join(',')}\n",true);
}
}
else
{
//Elevation of Rights failed
UserMessageUtil.error("Elevation of rights failed. Contact Administrator")
log.error "Elevation of rights failed. Contact Administrator"
commentManager.create(issue, adminUsername, "Elevation of rights failed. Contact Administrator", false)
}



 

Hope this helps.

 

PS: We were also using a condition to check if user is active or not based on which the transition will appear.

 

Regards,

Priyanka

0 votes
Thanos Batagiannis _Adaptavist_
Rising Star
Rising Star
Rising Stars are recognized for providing high-quality answers to other users. Rising Stars receive a certificate of achievement and are on the path to becoming Community Leaders.
February 21, 2017

Hi, 

I think I miss something. In order to update users you must  have the JIRA Administrator or JIRA System Administrator global permission.

Those are the same permissions you need in order to run a script via the script console. 

The question is what kind of permissions you have ?

regards, 

TAGS
AUG Leaders

Atlassian Community Events