NetSuite RestLet call from SuiteLet Client - netsuite

I am trying to call a RestLet webservice/URL from another SuiteScript. As i understand I need to use the http/https module to do so. But I am not able to find some example or steps to do so.
Planning to use this code in SS2.0-
var response = http.post({
url: 'https://rest.na1.netsuite.com/app/site/hosting/restlet.nl?script=601&deploy=1',
body: myDataObj, // json object
headers: headerObj // json obj
});
The below code works for me.
var nameValue = "arin";
var myDataObj = {
"name" : nameValue
};
var myRequest = {};
myRequest.headers = {};
myRequest.headers["Authorization"] = 'NLAuth nlauth_account=TSTDRV158xxxx,nlauth_email=XXXX,nlauth_signature=XXXX,nlauth_role=3';
myRequest.headers["Content-Type"] = 'application/json';
myRequest.headers["Accept"] = '*/*';
myRequest.url = 'https://rest.na1.netsuite.com/app/site/hosting/restlet.nl?script=601&deploy=1'; // RESTlet
// URL
myRequest.method = "POST";
myRequest.body = JSON.stringify(myDataObj);
// myRequest.body = myDataObj;
var myResponse = https.post(myRequest);
And reading the response data for JSON return ...
log.debug("Resonse", myResponse.body);
log.debug("Resonse", myResponse.code);
var data = myResponse.body;
var retObj = JSON.parse(data);
log.debug("Resonse Ret city - ", retObj.city);

Here's a basic example of how to do it:
var myRequest = {};
myRequest.headers = {};
myRequest.headers["Authorization"] = 'NLAuth nlauth_account=TSTDRVXXXXX, nlauth_email=xxx#xxx.com, nlauth_signature=XXXXXXX, nlauth_role=3';
myRequest.headers["contentType"] = 'application/json';
myRequest.url = 'https://XXXXXXXXX'; //RESTlet URL
myRequest.body = myDataObj;
var myResponse = https.post(myRequest);
Be careful exposing this on clientside scripts. You don't want to expose your credentials.

Related

How to retrieve rest let data from suitelet and print in execution logs

How to retrieve rest let data from suitelet and print in execution logs. I have wrote a restlet script i'm able to see the output in postman. I need those output in suitelet script.
below is the suitelet script which i have tried.
function callRestletData(request,response)
{
try
{
url = 'https://tstdrxxxxxx.restlets.api.netsuite.com/app/site/hosting/restlet.nl?script=xxx&deploy=1';
//orderId = 741;
var hearders = {};
hearders['Authorization'] = 'NLAuth nlauth_account=TSTDRVxxxx, nlauth_email=abc#abc.com, nlauth_signature=xxxxxx, nlauth_role=3';
hearders['contentType'] = 'application/json';
//var myResponse = https.post(myRequest);
var myResopnse = nlapiRequestURL(url,null,hearders,null,'GET');
//var responseText = myResopnse.getBody();
var data = JSON.stringify(myResopnse);
nlapiLogExecution('DEBUG','Response Is:',data);
}
catch(error)
{
nlapiLogExecution('ERROR','In Catch Block',error.message);
}
}

How to configure the user_token of Damn Vulnerable Web Application within CSRF field while Script based authentication using ZAP?

I had been following the documentation of Script Based Authentication for Damn Vulnerable Web Application using ZAP. I have navigated to http://localhost/dvwa/login.php through Manual Explore which opens up the DVWA application on my localhost as follows:
and adds the URL to the Default Context.
I've also created the dvwa script with the following configuration:
and modified the dvwa script:
Now when I try Configure Context Authentication, dvwa script does gets loaded but the CSRF field doesn't shows up.
Additionally, POST Data doesn't even shows up but Extra POST Data is shown.
Am I missing something in the steps? Can someone help me out?
The modified script within the documentation of Script Based Authentication section for Damn Vulnerable Web Application using ZAP
seems incomplete.
The complete script is available at Setting up ZAP to Test Damn Vulnerable Web App (DVWA) which is as follows:
function authenticate(helper, paramsValues, credentials) {
var loginUrl = paramsValues.get("Login URL");
var csrfTokenName = paramsValues.get("CSRF Field");
var csrfTokenValue = extractInputFieldValue(getPageContent(helper, loginUrl), csrfTokenName);
var postData = paramsValues.get("POST Data");
postData = postData.replace('{%username%}', encodeURIComponent(credentials.getParam("Username")));
postData = postData.replace('{%password%}', encodeURIComponent(credentials.getParam("Password")));
postData = postData.replace('{%' + csrfTokenName + '%}', encodeURIComponent(csrfTokenValue));
var msg = sendAndReceive(helper, loginUrl, postData);
return msg;
}
function getRequiredParamsNames() {
return [ "Login URL", "CSRF Field", "POST Data" ];
}
function getOptionalParamsNames() {
return [];
}
function getCredentialsParamsNames() {
return [ "Username", "Password" ];
}
function getPageContent(helper, url) {
var msg = sendAndReceive(helper, url);
return msg.getResponseBody().toString();
}
function sendAndReceive(helper, url, postData) {
var msg = helper.prepareMessage();
var method = "GET";
if (postData) {
method = "POST";
msg.setRequestBody(postData);
}
var requestUri = new org.apache.commons.httpclient.URI(url, true);
var requestHeader = new org.parosproxy.paros.network.HttpRequestHeader(method, requestUri, "HTTP/1.0");
msg.setRequestHeader(requestHeader);
helper.sendAndReceive(msg);
return msg;
}
function extractInputFieldValue(page, fieldName) {
// Rhino:
var src = new net.htmlparser.jericho.Source(page);
// Nashorn:
// var Source = Java.type("net.htmlparser.jericho.Source");
// var src = new Source(page);
var it = src.getAllElements('input').iterator();
while (it.hasNext()) {
var element = it.next();
if (element.getAttributeValue('name') == fieldName) {
return element.getAttributeValue('value');
}
}
return '';
}
Using this script, CSRF Field and POST Data field shows up just perfect.

oAuth2 web request works in browser but not in app

I have the following code sample with which I'm trying to authenticate an Azure active directory user within a Xamarin forms app
The URL (I've removed the actual client ID) works fine in a browser but fails when trying to send the http request
The error message says 'the response type must include client_id'
string URL = "https://login.microsoftonline.com/common/oauth2/v2.0/authorize?"
+ "client_id=xxxx-xxxxx-xxxxx-xxxxx-xxx"
+ "&response_type=code"
+ "&redirect_uri=https://login.microsoftonline.com/common/oauth2/nativeclient"
+ "&response_mode=query"
+ "&scope=openid%20offline_access%20https%3A%2F%2Fgraph.microsoft.com%2Fmail.read"
+ "&state=12345";
var webRequest = System.Net.WebRequest.Create(URL) as HttpWebRequest;
System.Console.WriteLine(URL);
if (webRequest != null)
{
webRequest.Method = "POST";
webRequest.ServicePoint.Expect100Continue = false;
webRequest.Timeout = 20000;
webRequest.ContentType = "text/html";
//POST the data.
using (requestWriter = new StreamWriter(webRequest.GetRequestStream()))
{
requestWriter.Write(postData);
}
}
HttpWebResponse resp = (HttpWebResponse)webRequest.GetResponse();
Stream resStream = resp.GetResponseStream();
StreamReader reader = new StreamReader(resStream);
ret = reader.ReadToEnd();
You put parameters in the URL, so you need to use GET method, instead of POST (like your browser does when you paste the URL in its address bar).
So, replace:
webRequest.Method = "POST";
by:
webRequest.Method = "GET";
and remove:
//POST the data.
using (requestWriter = new StreamWriter(webRequest.GetRequestStream()))
{
requestWriter.Write(postData);
}

Call Restlet from external suitelet with authentications

Can We call Restlet From External Suitelet with NLAuth or any auth.Kindly post some sample please.
Here's the simplest way to do a GET to a RESTlet:
var headers = {};
headers["Authorization"] = 'NLAuth nlauth_account=TSTDRVXXXXX, nlauth_email=xxx#xxx.com, nlauth_signature=XXXXXXX, nlauth_role=3';
headers["contentType"] = 'application/json';
var url = 'https://rest.na1.netsuite.com/app/site/hosting/restlet.nl?script=xxxx&deploy=xxx';
var response = nlapiRequestURL(url, null, headers);

I'm trying to send emails using sendgrid in nodejs.But am getting "TypeError: object is not a function" error

Here is my code snippet
var sendgrid = require('sendgrid')('xxxxxx', 'xxxxxx');
var email = new sendgrid.Email();
email.addTo('xyz#gmail.com');
email.setFrom('xyz#gmail.com');
email.setSubject('welcome to send grid');
email.setHtml('<html><body>HELLO evryone ...,</body></html>');
sendgrid.send(email, function(err, json) {
if(!err)
{
console.log("mail sent successssss");
res.send({"status":0,"msg":"failure","result":"Mail sent successfully"});
}
else
{
console.log("error while sending mail")
res.send({"status":1,"msg":"failure","result":"Error while sending mail."});
}
});
Installed sendgrid throgh npm also.am getting "TypeError: object is not a function" error.MAy i know why.??
Version:--
sendgrid#3.0.8 node_modules\sendgrid
└── sendgrid-rest#2.2.1
It looks like you're using sendgrid#3.0.8 but trying to call on the sendgrid#2.* api.
v2 implementation: https://sendgrid.com/docs/Integrate/Code_Examples/v2_Mail/nodejs.html
v3 implementation:
https://sendgrid.com/docs/Integrate/Code_Examples/v3_Mail/nodejs.html
Give the v3 a go.
As for the type error:
v2
var sendgrid = require("sendgrid")("SENDGRID_APIKEY");
you're invoking a function
however you have v3 installed
require('sendgrid').SendGrid(process.env.SENDGRID_API_KEY)
and it's now an object
REQUESTED UPDATE:
I don't know too much about the keys given, but since they have tons of different supported libraries, it's completely possible that some of them use both while others use only one. If you really only have a USER_API_KEY nad PASSWORD_API_KEY, just use the user_api_key
Here is their source for the nodejs implementation module SendGrid:
function SendGrid (apiKey, host, globalHeaders) {
var Client = require('sendgrid-rest').Client
var globalRequest = JSON.parse(JSON.stringify(require('sendgrid-rest').emptyRequest));
globalRequest.host = host || "api.sendgrid.com";
globalRequest.headers['Authorization'] = 'Bearer '.concat(apiKey)
globalRequest.headers['User-Agent'] = 'sendgrid/' + package_json.version + ';nodejs'
globalRequest.headers['Accept'] = 'application/json'
if (globalHeaders) {
for (var obj in globalHeaders) {
for (var key in globalHeaders[obj] ) {
globalRequest.headers[key] = globalHeaders[obj][key]
}
}
}
The apiKey is attached to the header as an auth, and it looks like that's all you need.
Try following their install steps, without your own implementation,
1) (OPTIONAL) Update the development environment with your SENDGRID_API_KEY, for example:
echo "export SENDGRID_API_KEY='YOUR_API_KEY'" > sendgrid.env
echo "sendgrid.env" >> .gitignore
source ./sendgrid.env
========
2) Make this class and if you did the above use process.env.SENDGRID_API_KEY else put your USER_API_KEY
var helper = require('sendgrid').mail
from_email = new helper.Email("test#example.com")
to_email = new helper.Email("test#example.com")
subject = "Hello World from the SendGrid Node.js Library!"
content = new helper.Content("text/plain", "Hello, Email!")
mail = new helper.Mail(from_email, subject, to_email, content)
//process.env.SENDGRID_API_KEY if above is done
//else just use USER_API_KEY as is
var sg = require('sendgrid').SendGrid(process.env.SENDGRID_API_KEY)
var requestBody = mail.toJSON()
var request = sg.emptyRequest()
request.method = 'POST'
request.path = '/v3/mail/send'
request.body = requestBody
sg.API(request, function (response) {
console.log(response.statusCode)
console.log(response.body)
console.log(response.headers)
})

Resources