Need an example of groovy-wslite POST with multiple parameters - grails

I need to make a secure POST to https://example.com/api/login with parameters Username and Password. I'm trying to use the wslite plugin with Grails, but I can't figure out the syntax. I've checked the unit tests at github, but none of them have given me what I need. Maybe I'm just failing to connect the dots.
Anyway, does anyone have an example of multiple parameters to a POST? Thanks!

Try following example to post your request.
def client = new RESTClient("https://example.com/api/login")
// for testing only!
client.httpClient.sslTrustAllCerts = true
def response = client.post() {
charset "UTF-8"
urlenc username: "test", password: "test" // here you can provide your params as a map
}

Related

How to access the body from a request Ruby on rails

I tried to do a Postman request to this endpoint http://127.0.0.1:3000/api/v1/login
with this body:
{
"username" : "Sebastiansantander",
"password" : "1233342"
}
I tried using params.permit[:username,:password]
but the problem is that I cant use them.
how can I access to that parameters in order to use them.
There is a little different syntax to achieve that params.permit(:username, password)
and then in your code params[:username]

GRAILS URL parameters short form

I know that in GRAILS/GROOVY
def content=urlrestservicestring.toURL().getBytes(requestProperties: ['User-Accepted': username])
is a short form to have all the byte content (for example for PDF donwload), but I don't know all the request properties available for URL for richer connections, for example for POST method (this is a GET call) with payload in json. Is it possible? In which way?
It looks like per requestProperties you can set request headers only which might help for simple cases.
On the other hand if you want to do something more complex, like a POST, you have to use a propper HTTP-client.
In Groovy there's an idiomatic HTTPBuilder which is very straight-forward and easy to use, or Grails own RESTBuilder
UPDATE:
Using HTTPBuilder the download could look like:
import static groovyx.net.http.HttpBuilder.configure
configure {
request.uri = "http://example.org/download"
request.contentType = 'application/json'
}.post {
request.headers.username = 'Scarpanti'
request.body = [ some:'json' ]
Download.toStream delegate, response.outputStream // from grails
// or
// Download.toStream delegate, file
}
see also ref-doc

Open new ticket in JIRA using REST api

I'd like to understand how to create a new ticket in JIRA using REST API from Jenkins. Is there any limitations or special things I should be aware of?
I'm going to write a Python script, which will parse the build log and then create a new ticket in JIRA project.
I checked the plugins, but most of them only can update the existing tickets.
Thanks
There's documentation here about the JSON schema and some example JSON which needs to go in the body of your POST request to /rest/api/2/issue
https://docs.atlassian.com/jira/REST/cloud/#api/2/issue-createIssue
Here's a basic python3 script to make a post request
import requests, json
from requests.auth import HTTPBasicAuth
base_url = "myjira.example.com" # The base_url of the Jira insance.
auth_user = "simon" # Jira Username
auth_pass = "N0tMyRe3lP4ssw0rd" # Jira Password
url = "https://{}/rest/api/2/issue".format(base_url)
# Set issue fields in python dictionary. See docs and comment below regarding available fields
fields = {
"summary": "something is wrong"
}
payload = {"fields": fields}
headers = {"Content-Type": "application/json"}
response = requests.post(
url,
auth=(auth_user, auth_pass),
headers=headers,
data=json.dumps(payload))
print("POST {}".format(url))
print("Response {}: {}".format(response.status_code, response.reason))
_json = json.loads(response.text)
Using this HTTP requests library for python http://docs.python-requests.org/en/master/
You can make a GET request to /rest/api/2/issue/{issueIdOrKey}/editmeta using the id or key of existing issue in the same project as the issue's you will be creating via the API will go to in order to get a list of all the fields you can set and which ones are required.
https://docs.atlassian.com/jira/REST/cloud/#api/2/issue-getEditIssueMeta

Access Devise Session in Backbone Marionette?

I'm working on creating a Rails app that uses Devise for user authentication and Backbone Marionette as the front end. I'm having trouble figuring out how to access the session that was created on the backend. I'd like to be able to grab say the username/email to display it in my Marionette app.
Also it might be useful to check to see if the session exists, though for the most part devise authentication in the controller seems to be working fairly well.
Any idea how I can access the current devise session in Backbone?
Thanks in advance!
Rails 3
The session cookies are stored as _app_session. They look obfuscated but they are just base64 encoded. You can use the atob function on the client to decode the session cookie and read any information you put in there. (In Rails 4 you are probably using encrypted session cookies and you will need to do something a little different)
An example cookie might look something like this:
"BAh7CEkiD3Nlc3Npb25faWQGOgZFVEkiJWNlZjFjMDhiNjYyNWEzZDI5YWM5MTJlMDY3MmQ0NTM4BjsAVEkiGXdhcmRlbi51c2VyLnVzZXIua2V5BjsAVFsISSIJVXNlcgY7AEZbBmkHSSIiJDJhJDEwJE5MYlhOWHFUMEtoZmdnNFliZHdyeE8GOwBUSSIQX2NzcmZfdG9rZW4GOwBGSSIxSSt6TnJsZm1FOTZTNWFRWGdSVWtGK2Zmd3BPVUxkQURjWHBqZ2NoZ05nMD0GOwBG"
It would decode into something like this:
atob(cookieStr);
"{I"session_id:ETI"%cef1c08b6625a3d29ac912e0672d4538;�TI"warden.user.user.key;�T[I" User;�F[iI""$2a$10$NLbXNXqT0Khfgg4YbdwrxO;�TI"_csrf_token;�FI"1I+zNrlfmE96S5aQXgRUkF+ffwpOULdADcXpjgchgNg0=;�F"
Rails 3/4
Rather than read from the session cookie I would add a separate cookie or just bootstrap your HTML code with the data you want.
Set your own cookie in your controller or devise hooks:
cookies[:my_data] = {
value: { username: "rocketman", email: "cliff.secord#gmail.com" }.to_json,
domain: "my.sweetapp.com"
}
In your client read that cookie: (use a lib like $.cookie to simplify the reading)
var cookieData, cookies = document.cookie.split('; ');
for (var i = 0, parts; (parts = cookies[i] && cookies[i].split('=')); i++) {
if (decode(parts.shift()) === "my_data") {
cookieData = JSON.parse(decode(parts.join('=')));
}
}
// Do something with cookieData;

Using REST APIs

I am new to gerrit. I am using gerrit V. 2.6 . I want to use gerrit REST APIs in my python script. But not able to figure out how to use it. I tried below code but getting errors.
curl --digest --user user:password http://server/a/changes/path/to/project~branch~change_id/rebase
getting error :
401 Authorization Required
Authorization Required
This server could not verify that you
are authorized to access the document
requested. Either you supplied the wrong
credentials (e.g., bad password), or your
browser doesn't understand how to supply
the credentials required.
Am I missing something.??
Are you using the correct username:password combination? This isn't your network password - it is the HTTP password that gerrit generates. You can find it by going to Settings->HTTP Password. If the password box is blank, click the button to have Gerrit generate a new password.
You may try using pygerrit. https://pypi.python.org/pypi/pygerrit/0.2.1
I think it has some APIs to easily access gerrit.
As #Ramraj mentioned, you can try using pygerrit or pygerrit2.
And I provide some examples that how I use gerrit REST APIs in my python script.
Here is the code.
auth = HTTPBasicAuth(username, password)
rest = GerritRestAPI(url='http://review.xxxxxx.com:8080', auth=auth)
Query changes by change number.
info = rest.get("/changes/?q=change:{}".format(change_number))
change_id = info[0]['change_id']
subject = info[0]['subject']
Query changes by commit id.
info = rest.get("/changes/?q=commit:{}".format(commit_id))
change_id = info[0]['change_id']
subject = info[0]['subject']
Revert a change.
headers = {'content-type': 'application/json'}
query = "/changes/" + str(change_number) + "/revert"
my_data = {"message": "{}".format("Revert "+str(subject))}
rest.post(query, data=json.dumps(my_data), timeout=30, headers=headers)
Review a change
headers = {'content-disposition': 'attachment', 'content-type': 'application/json'}
query = "/changes/" + str(change_number) + "/revisions/current/review"
my_data = { "labels": {"Code-Review": "+2", "Verified": "+1"} }
rest.post(query, data=json.dumps(my_data), timeout=30, headers=headers)

Resources