grails oauth from groovy script - grails

I'm trying to run a groovy script that calls the Linkedin API. The question is, how do I authenticate using the grails oauth plugin from within the groovy script ?
This is my config :
oauth {
linkedin {
requestTokenUrl="https://api.linkedin.com/uas/oauth/requestToken"
accessTokenUrl="https://api.linkedin.com/uas/oauth/accessToken"
authUrl="https://www.linkedin.com/uas/oauth/authenticate"
consumer.key="xxxxxxxxx"
consumer.secret="xxxxxxxxxx"
}
}
This is my script, which I start with "grails run-script scriptname.groovy" :
import org.grails.plugins.oauth.OauthService
def oauthService = new OauthService()
oauthService.reset()
def URL = "http://api.linkedin.com/v1/people-search?country-code=us&postal-code=98102&distance=100&start=0&count=5"
def recs_response = oauthService.accessResource( URL, "linkedin", [key:"xxxxxxx", secret:"xxxxxxxxx"], 'GET')
println "it worked"
If I print the response I get "The token used in the OAuth request is not valid"
Thanks.

Take a look at http://code.google.com/p/oauth-signpost/wiki/TwitterAndSignpost
I downloaded the OAuthTwitterExample and put the commons-codec-1.3.jar and signpost-core-1.1-SNAPSHOT.jar that were included in the zip in my working directory
for flickr OAuth I used the following in oauth.groovy
import oauth.signpost.OAuth;
import oauth.signpost.OAuthConsumer;
import oauth.signpost.OAuthProvider;
import oauth.signpost.basic.DefaultOAuthConsumer;
import oauth.signpost.basic.DefaultOAuthProvider;
import oauth.signpost.signature.SignatureMethod;
def consumer = new DefaultOAuthConsumer('<API KEY>','<Signature>',
SignatureMethod.HMAC_SHA1)
def provider = new
DefaultOAuthProvider(consumer,"http://www.flickr.com/services/oauth/request_token",
"http://www.flickr.com/services/oauth/access_token",
"http://www.flickr.com/services/oauth/authorize");
String url =provider.retrieveRequestToken( OAuth.OUT_OF_BAND);
println "navigate to the following URL"
println url
enter this on commandline in the working directory
groovy -cp commons-codec-1.3.jar:signpost-core-1.1-SNAPSHOT.jar oauth.groovy
hope this helps

Related

Use OAuth with PyGithub to request private repo access

I am having trouble finding a way to request "repo" scope when authorizing a user in OAuth using the PyGithub library.
My team is building a "repository analyzer" website that provides insights on code in a chosen repository. We are using the PyGithub implementation of the Git API. We are using OAuth to authorize users and it works great for public repositories. However, I am unable to succesfully specify a scope. I tried "Github.oauth_scopes" below which is obviously wrong. Any tips are greatly appreciated!
In the screenshot can see that OAuth is only requesting public data, we need to prompt access to private repositories too which means using the "repo" scope: GitApiScopeDoc
from github import *
g = Github()
#request repo scope
Github.oauth_scopes = "repo"
#authorization using oauth
clientID = "enterclientidhere"
secret = "entersecrethere"
oauth = g.get_oauth_application(clientID, secret)
url = oauth.get_login_url()
#print the url, then we follow the url to github which requests a users identity
print(url)
screenshot
from github import *
g = Github()
#request repo scope
Github.scopes = "repo"
#authorization using oauth
clientID = "enterclientidhere"
secret = "entersecrethere"
oauth = g.get_oauth_application(clientID, secret)
url = oauth.get_login_url()
#print the url, then we follow the url to github which requests a users identity
print(url)
The code above should work. You sh

Adding Google Service Account Credentials by a groovy script

I want to add Google Service Account credentials using a groovy file initializer on init.groovy.d. So far I could define UserName-Password credentials and String credentials. However, the Google API key requires a special credential type: GoogleRobotPrivateKeyCredentials. I could not manage to add that type of credential.
How can I define Google Service Account credentials of type GoogleRobotPrivateKeyCredentials through a groovy script?
It seems there is an answer on that link: https://github.com/jenkinsci/google-oauth-plugin/issues/5
I have changed that slightly, as that answer did not work on the latest Jenkins installation:
import com.cloudbees.plugins.credentials.Credentials
import com.cloudbees.plugins.credentials.CredentialsStore
import com.cloudbees.plugins.credentials.SystemCredentialsProvider
import com.cloudbees.plugins.credentials.domains.Domain
import com.google.jenkins.plugins.credentials.oauth.GoogleRobotPrivateKeyCredentials
import com.google.jenkins.plugins.credentials.oauth.JsonServiceAccountConfig
import hudson.model.FileParameterValue.FileItemImpl
import org.apache.commons.fileupload.FileItem
def jsonFile = new File("/myfilepath/key.json")
def fileItem = new FileItemImpl(jsonFile)
def config = new JsonServiceAccountConfig()
config.setJsonKeyFileUpload(fileItem)
Credentials credentials = new GoogleRobotPrivateKeyCredentials("gpc", config, null)
SystemCredentialsProvider instance = SystemCredentialsProvider.getInstance()
CredentialsStore store = instance.getStore()
store.addCredentials(Domain.global(), credentials)

cannot authorize using Rest-Assured

400 error cannot understand where is mistake in code
I used Rest-assured documentation
https://www.toolsqa.com/rest-assured/post-request-using-rest-assured/
Please help with this question
package forth;
import org.apache.log4j.BasicConfigurator;
import org.testng.annotations.Test;
import org.testng.Assert;
import io.restassured.RestAssured;
import io.restassured.specification.RequestSpecification;
import io.restassured.response.Response;
import org.json.simple.JSONObject;
public class zero {
#Test
public void RegistrationSuccessful()
{
BasicConfigurator.configure();
RestAssured.baseURI ="url";
RequestSpecification request = RestAssured.given();
JSONObject requestParams = new JSONObject();
requestParams.put("useremail", "my login");
requestParams.put("api_token", "my token");
request.header("Content-Type", "application/json");
request.body(requestParams.toJSONString());
Response response = request.post("/rest/auth/1/session");
int statusCode = response.getStatusCode();
Assert.assertEquals(statusCode, "201");
String successCode = response.jsonPath().get("SuccessCode");
Assert.assertEquals( "Correct Success code was returned", successCode, "OPERATION_SUCCESS");
}
}
First of all, always try opening the end point url in new tab of browser, if it doesn't give any error then, it is an indication that we can use it. If browser displays something like "This site can't be reached", then it is not a valid end point or server is not up and running for respective end point.
In case of toolsqa website, in starting few pages endpoints are not working. I sent a message to Virender to look into this issue, but unfortunately no response.
I suggest you to learn rest assured from makeseleniumeasy website as per my personal experience.
Its very important to check if the api requires form params or body params.
form-params are intended to be used with content-type "application/x-www-form-urlencoded" (a form)
body-params are intended to use for parameters which are also going to be located in the body with other content-types (application/json)

Twilio - Quick question (Unable to update record)

hope you are doing it right these days.
To summarize my problem, I think this is not working becuase I am using a free Twilio account instead of a paid one. But that's just my beginner theory. Now, the issue:
I have tried an official Twilio tutorial (https://www.twilio.com/blog/automating-ngrok-python-twilio-applications-pyngrok, I shared the link in case someone finds it interesting or needs it), which allows us to automate SMS webhook (sms_url) configuration by using Client (twilio) and pyngrok (ngrok).
def start_ngrok():
from twilio.rest import Client
from pyngrok import ngrok
url = ngrok.connect(5000)
print(' * Tunnel URL:', url)
client = Client()
client.incoming_phone_numbers.list(
phone_number=os.environ.get('TWILIO_PHONE_NUMBER'))[0].update(
sms_url=url + '/bot')
I can't explain all the things that I tried in the last 4 days, with no success. I keep getting the same error:
client.incoming_phone_numbers.list(phone_number=os.environ.get('TWILIO_PHONE_NUMBER'))[0].update(sms_url=url + '/bot')
IndexError: list index out of range
Something is not working with the list, it comes empty, although environment variables are working properly. I will work with just one phone_number, so there no need for list, indeed, so I started to change that line to avoid different errors and ended up with this:
def start_ngrok():
from twilio.rest import Client
from pyngrok import ngrok
url = ngrok.connect(5000)
print(' * Tunnel URL:', url)
client = Client()
client.incoming_phone_numbers("my_number").update(sms_url=str(url) + '/bot')
Then I got the final error that I can't solve by my self:
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/twilio/rest/api/v2010/account/incoming_phone_number/__init__.py", line 442, in update
payload = self._version.update(method='POST', uri=self._uri, data=data, )
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/twilio/base/version.py", line 106, in update
raise self.exception(method, uri, response, 'Unable to update record')
twilio.base.exceptions.TwilioRestException:
HTTP Error Your request was:
POST /Accounts/my_account_SID/IncomingPhoneNumbers/+my_number.json
Twilio returned the following information:
Unable to update record: The requested resource /2010-04-01/Accounts/my_account_SID/IncomingPhoneNumbers/+my_number.json was not found
More information may be available here:
https://www.twilio.com/docs/errors/20404
I tried all different phone numbers combinations/formats: nothing works.
Thanks for your time reading all this!
Looks like something changed since the blog was written or there was a mistake.
Try the below:
The only difference is adding .public_url to the url object. Also allowed a GET to /bot for testing.
from dotenv import load_dotenv
from flask import Flask, request
from twilio.twiml.messaging_response import MessagingResponse
load_dotenv()
app = Flask(__name__)
#app.route('/bot', methods=['POST','GET'])
def bot():
user = request.values.get('From', '')
resp = MessagingResponse()
resp.message(f'Hello, {user}, thank you for your message!')
return str(resp)
def start_ngrok():
from twilio.rest import Client
from pyngrok import ngrok
url = ngrok.connect(5000)
print('This is',url)
print(' * Tunnel URL:', url)
client = Client()
client.incoming_phone_numbers.list(
phone_number=os.environ.get('TWILIO_PHONE_NUMBER'))[0].update(
sms_url=url.public_url + '/bot')
if __name__ == '__main__':
if os.environ.get('WERKZEUG_RUN_MAIN') != 'true':
start_ngrok()
app.run(debug=True)

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

Resources