Skip to content

Instantly share code, notes, and snippets.

@jechlin-adaptavist
Created April 30, 2021 06:12
Show Gist options
  • Save jechlin-adaptavist/8541cdc3be8b6546484f407879580d33 to your computer and use it in GitHub Desktop.
Save jechlin-adaptavist/8541cdc3be8b6546484f407879580d33 to your computer and use it in GitHub Desktop.
Creating users via a workflow function
package examples.champs
import com.atlassian.jira.bc.user.UserService
import com.atlassian.jira.component.ComponentAccessor
def userService = ComponentAccessor.getComponent(UserService)
def createValidationResult = UserCreationUtil.validateUserCreation(issue)
if (!createValidationResult.isValid()) {
throw new Exception('fail')
}
userService.createUser(createValidationResult)
package examples.champs
import com.atlassian.jira.bc.user.UserService
import com.atlassian.jira.component.ComponentAccessor
import com.atlassian.jira.issue.Issue
import com.opensymphony.workflow.InvalidInputException
class UserCreationUtil {
static UserService.CreateUserValidationResult validateUserCreation(Issue issue) {
def customFieldManager = ComponentAccessor.customFieldManager
// the username of the new user - needs to be lowercase and unique - required
def userNameCf = customFieldManager.getCustomFieldObjectByName('Username')
final String userName = issue.getCustomFieldValue(userNameCf)
// The password for the new user - if empty a random password will be generated
final String password = ""
// The email address for the new user - required
def emailAddressCf = customFieldManager.getCustomFieldObjectByName('Email Address')
final String emailAddress = issue.getCustomFieldValue(emailAddressCf)
// The display name for the new user - required
def displayNameCf = customFieldManager.getCustomFieldObjectByName('Display Name')
final String displayName = issue.getCustomFieldValue(displayNameCf)
if (!userName) {
throw new InvalidInputException(userNameCf.id, 'Must not be empty')
}
// notifications are sent by default, set to false to not send a notification
final boolean sendNotification = true
def loggedInUser = ComponentAccessor.jiraAuthenticationContext.loggedInUser
def userService = ComponentAccessor.getComponent(UserService)
def newCreateRequest = UserService.CreateUserRequest.withUserDetails(loggedInUser, userName, password, emailAddress, displayName)
.sendNotification(sendNotification)
userService.validateCreateUser(newCreateRequest)
}
}
package examples.champs
import com.opensymphony.workflow.InvalidInputException
def createValidationResult = UserCreationUtil.validateUserCreation(issue)
if (!createValidationResult.isValid()) {
def errorCollection = createValidationResult.errorCollection
throw new InvalidInputException(errorCollection)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment