Scriptrunner/ Copying Project while logged-in as another user - groovy

I want to use my script, so that it will be executed by someone who is not me, but another user (ServiceUser) in the Jira Instance.
This is my functioning code, but I do not know how to make someone else execute it.
import com.atlassian.jira.project.Project
import com.atlassian.jira.project.ProjectManager
import com.atlassian.jira.project.AssigneeTypes
import com.atlassian.jira.component.ComponentAccessor
import com.atlassian.jira.user.ApplicationUser
import com.atlassian.jira.component.ComponentAccessor
import com.onresolve.scriptrunner.canned.jira.admin.CopyProject
import org.apache.log4j.Logger
import com.atlassian.jira.bc.projectroles.ProjectRoleService
import com.atlassian.jira.component.ComponentAccessor
import com.atlassian.jira.security.roles.ProjectRole
import com.atlassian.jira.util.SimpleErrorCollection
import com.atlassian.jira.security.roles.ProjectRoleManager
import com.atlassian.jira.project.ProjectManager
import com.atlassian.jira.project.Project
import com.atlassian.jira.security.roles.ProjectRoleActor
import com.atlassian.jira.bc.project.ProjectCreationData
import com.atlassian.jira.bc.project.ProjectService
import com.atlassian.jira.component.ComponentAccessor
import com.atlassian.jira.project.AssigneeTypes
import com.atlassian.jira.project.type.ProjectTypeKey
// the key for the new project
def projectKey = "EXA987"
def projectName = "EXA987"
def log = Logger.getLogger("com.onresolve.jira.groovy.MyScript")
Thread executorThread = new Thread(new Runnable() {
void run() {
def copyProject = new CopyProject()
def inputs = [
(CopyProject.FIELD_SOURCE_PROJECT) : "SWTEMP",
(CopyProject.FIELD_TARGET_PROJECT) : projectKey,
(CopyProject.FIELD_TARGET_PROJECT_NAME) : projectName,
(CopyProject.FIELD_COPY_VERSIONS) : false,
(CopyProject.FIELD_COPY_COMPONENTS) : false,
(CopyProject.FIELD_COPY_ISSUES) : false,
(CopyProject.FIELD_COPY_DASH_AND_FILTERS) : false,
]
def errorCollection = copyProject.doValidate(inputs, false)
if(errorCollection.hasAnyErrors()) {
log.warn("Couldn't create project: $errorCollection")
}
else {
def util = ComponentAccessor.getUserUtil()
def adminsGroup = util.getGroupObject("jira-administrators")
assert adminsGroup // must have jira-administrators group defined
def admins = util.getAllUsersInGroups([adminsGroup])
assert admins // must have at least one admin
ComponentAccessor.getJiraAuthenticationContext().setLoggedInUser(util.getUserByName(admins.first().name))
copyProject.doScript(inputs)
}
}
})
executorThread.start()
I stumbled upon other codes, using things like
def oldLoggedInUser = jiraAuthenticationContext.getLoggedInUser()
jiraAuthenticationContext.setLoggedInUser(serviceUser)
jiraAuthenticationContext.setLoggedInUser(oldLoggedInUser)
but it was not succesful for me.

I have used following solution to change user during script execution:
def authContext = ComponentAccessor.getJiraAuthenticationContext();
def currentUser = authContext.getLoggedInUser();
def superuser=ComponentAccessor.getUserManager().getUserByKey("ANOTHER_USER_ACCOUNT")
authContext.setLoggedInUser(superuser);
// < do the needed work>
authContext.setLoggedInUser(currentUser);
I had first issues as my used another account had not needed Jira access rights (and I got funny "user must be logged in" errors)

Related

Scriptrunner Create issue and assign to existing epic

While creating a new issue using scriptrunner, I would like to assign it an existing epic. it seems the issue.setCustomFieldValue(epicLinkCustomField) is not working. any help would be greatly appreciated. everything else works fine, im able to set name, summary, tittle, prio, description, assign reporter, projectkey, issue context, and issue type.
The code I have is below.
import com.atlassian.jira.component.ComponentAccessor
import com.atlassian.jira.issue.context.IssueContext
import com.atlassian.jira.issue.context.IssueContextImpl
import com.atlassian.jira.issue.fields.config.manager.PrioritySchemeManager
import com.atlassian.jira.component.ComponentAccessor
import com.atlassian.jira.issue.IssueManager
import com.atlassian.jira.issue.Issue
import com.atlassian.jira.issue.CustomFieldManager
import com.atlassian.jira.issue.MutableIssue
import java.text.SimpleDateFormat
def date = new Date()
def sdf = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss")
// the project key under which the issue will get created
final projectKey = 'SEC'
// stores status
final statusKey = 'AN QUE'
// the issue type for the new issue
final issueTypeName = 'Task'
// user with that user key will be the reporter of the issue
final reporterKey = 'MV108788'
// the summary of the new issue
final summary = 'test' + date
// the priority of the new issue
final priorityName = 'Low'
// sets description
final description = 'this is a decription'
//epic
final epicIssueKey = 'test'
def issueService = ComponentAccessor.issueService
def constantsManager = ComponentAccessor.constantsManager
def loggedInUser = ComponentAccessor.jiraAuthenticationContext.loggedInUser
def prioritySchemeManager = ComponentAccessor.getComponent(PrioritySchemeManager)
//finds epic
def epicLinkCustomField = ComponentAccessor.customFieldManager.getCustomFieldObjects().findByName(epicIssueKey)
//finds status key
def status = ComponentAccessor.constantsManager.getStatusByName(statusKey)
//finds project key
def project = ComponentAccessor.projectManager.getProjectObjByKey(projectKey)
assert project : "Could not find project with key $projectKey"
//finds issue types
def issueType = constantsManager.allIssueTypeObjects.findByName(issueTypeName)
assert issueType : "Could not find issue type with name $issueTypeName"
// if we cannot find user with the specified key or this is null, then set as a reporter the logged in user
def reporter = ComponentAccessor.userManager.getUserByKey(reporterKey) ?: loggedInUser
// if we cannot find the priority with the given name or if this is null, then set the default priority
def issueContext = new IssueContextImpl(project, issueType) as IssueContext
// finds priority
def priorityId = constantsManager.priorities.findByName(priorityName)?.id ?: prioritySchemeManager.getDefaultOption(issueContext)
//sets all issue settings
def issueInputParameters = issueService.newIssueInputParameters().with {
setStatusId(statusId) //not working
setProjectId(project.id)
setDescription(description)
setIssueTypeId(issueType.id)
setReporterId(reporter.name)
setSummary(summary)
setPriorityId(priorityId)
issue.setCustomFieldValue(epicLinkCustomField)
}
def validationResult = issueService.validateCreate(loggedInUser, issueInputParameters)
assert validationResult.valid : validationResult.errorCollection
def result = issueService.create(loggedInUser, validationResult)
assert result.valid : result.errorCollection

impossible to execute due to infinite loop

the problem itself is that the last 4 lines cannot be executed because there is an infinite loop in the function above, without which it is impossible, who can offer a solution?
from aiogram import Bot, types
from aiogram.dispatcher import Dispatcher
from aiogram.utils import executor
from requests import Request, Session
import requests
import json
import pprint
import time
bot = Bot(token='')
dp = Dispatcher(bot)
site = "https://pro-api.coinmarketcap.com/v2/cryptocurrency/quotes/latest"
parameters = {
'slug':'bitcoin',
'convert':'USD'
}
headers = {
'Accepts':'application/json',
'X-CMC_PRO_API_KEY':''
}
def main():
bitcoin_history = []
while True:
session = Session()
session.headers.update(headers)
response = session.get(site, params=parameters)
price = (json.loads(response.text)['data']['1']['quote']['USD']['price'])
bitcoin_history.append(price)
print(bitcoin_history)
if len(bitcoin_history) == 5:
bitcoin_history = []
time.sleep(30)
main()
#dp.message_handler(commands=["btcusd"])
async def echo_send(message : types.Message):
await message.answer("$" + str())
executor.start_polling(dp, skip_updates=True)

How to encode the password in Gatling?

I have a requirement in my project to encode the password being sent in the login request. What is the best way to do it?
You can store the credentials in a file as key-value pair. Read the file in vector and then decode the value. The value can be stored in a session and can be used in your Gatling request as below:
import scala.concurrent.duration._
import io.gatling.core.Predef._
import io.gatling.core.structure.ChainBuilder
import io.gatling.http.Predef._
import io.gatling.jdbc.Predef._
import io.gatling.jsonpath._
import Headers._
import scala.collection._
import java.time.format.DateTimeFormatter
import java.time.LocalDateTime
import java.time.LocalDate
import io.gatling.core.feeder._
import java.util.Base64
import java.nio.charset.StandardCharsets
import scala.util.matching.Regex
object TestClass {
//Now you can use below code to read the credential file,
val recordsByEnv: Map[String, Seq[Record[Any]]] =
csv("/User/sandy/data/userdetails.csv").readRecords.groupBy { record =>
record("env").toString
}
val passwordByEnv: Map[String, Seq[Any]] = recordsByEnv.mapValues { records =>
records.map { record =>
record("password")
}
}
val password_v = (passwordByEnv.get("env_name").toString)
val password_encoded = password_v.substring(12, (password_v.length - 2))
val credentials = new String(Base64.getDecoder.decode(password_encoded))
//Store the decoded value in session variable
.exec(session => session.set("password", credentials))
.exec(
http("Authorization")
.post("https://XXXX.xxxxxx.com")
.header("Content-Type", "application/x-www-form-urlencoded")
.formParam("password", "${password}")
.formParam("username", "USERNAME")
)
//Below is user details file look like below
//env_name,encoded_password
}

python3 unit testing, patching return of instance method not working

I am trying to do the following:
#patch('uuid.uuid4', autospec=True)
def test_generate_adid(self, patched_uuid, app_api):
patched_uuid.return_value = "9e51ab81-6d65-4b81-af3b-8f7f49d69ba7"
adid = app_api.generate_adid()
assert adid == "9e51ab81-6d65-4b81-af3b-8f7f49d69ba7"
Where app_api is a fixture of the class under test.
However, in my app_api class, uuid4() is not getting patched and keeps returning a uuid other than the one I am trying to force. Here is what the generate_adid() instance method looks like:
from uuid import uuid4
def generate_adid(self):
adid = str(uuid4())
return adid
The failing unit test error:
AssertionError: assert '90b29e86-e3b0-40aa-8971-f868f90cb009' == '9e51ab81-6d65-4b81-af3b-8f7f49d69ba7'
I have consulted this post: How to mock uuid generation in a test case? but still am having no luck.
What am I doing wrong? Thanks to all of those who reply in advance.
EDIT: Here is the full code:
from requests import Session
from random import uniform
from hashlib import md5
from hmac import new
from uuid import uuid4
from json import dumps
class AppApi:
def __init__(self, account):
self.account = account
self.session = Session()
def generate_adid(self):
adid = str(uuid4())
return adid
Test Case:
from src import AppApi
from pytest import fixture
from unittest.mock import patch
from json import loads
ACCOUNT = {
"email": "user#email.com",
"username": "user",
"password": "s3cr3t"
}
#fixture
def app_api():
app_api = AppApi(ACCOUNT)
yield app_api
class TestAppApi:
#patch('uuid.uuid4')
def test_generate_adid(self, patched_uuid, app_api):
patched_uuid.return_value = "9e51ab81-6d65-4b81-af3b-8f7f49d69ba7"
adid = app_api.generate_adid()
assert adid == "9e51ab81-6d65-4b81-af3b-8f7f49d69ba7"
In your example you're patching the uuid4() function in the uuid module rather than the function uuid4() in the module which you're trying to test. Take a look at Python unnit.test docs where to patch
Using your example above you need to patch the uuid4() imported into the src module. You need to use #patch("src.uuid4")
from src import AppApi
from pytest import fixture
from unittest.mock import patch
from json import loads
ACCOUNT = {
"email": "user#email.com",
"username": "user",
"password": "s3cr3t"
}
#fixture
def app_api():
app_api = AppApi(ACCOUNT)
yield app_api
class TestAppApi:
#patch('src.uuid4')
def test_generate_adid(self, patched_uuid, app_api):
patched_uuid.return_value = "9e51ab81-6d65-4b81-af3b-8f7f49d69ba7"
adid = app_api.generate_adid()
assert adid == "9e51ab81-6d65-4b81-af3b-8f7f49d69ba7"
Hope this helps!

Connection request failed while connecting to sharepoint online

I am trying to connect sharepoint online i used the following code but the response it is showing is request failed . I tried the following code
#Grab(group='org.codehaus.groovy.modules.http-builder', module='http-builder', version='0.5.0-RC2' )
import groovyx.net.http.*;
import static groovyx.net.http.ContentType.*;
import static groovyx.net.http.Method.*;
import groovyx.net.http.HTTPBuilder;
import static groovyx.net.http.Method.GET;
import static groovyx.net.http.ContentType.TEXT;
import groovyx.net.http.RESTClient
import groovy.util.slurpersupport.GPathResult
import static groovyx.net.http.ContentType.URLENC
import groovyx.net.http.URIBuilder
def authSite = new HTTPBuilder( 'https://xyzsharepoint.com' );
authSite.auth.basic 'username', 'password';
authSite.request(GET) { req->
response.success = { resp->
println'request was successful'
assert resp.status<400
}
response.failure = { resp ->
println'request failed'
assert resp.status>=400
}
}
Suggest me where I went wrong.

Resources