'#' in URL, used in node.js http.request - http

I'm presented with an url with an "#" sign in it:
curl http://subdomain:token#localhost:9292/aaa/bbb
works perfectly
But I can't get it to work with node.js http.request, probably because I don't understand what the "#" is doing (and somehow can't find a clear answer on google).
Anyone care to explain?
Here's my current node.js code
var http_options = {
method : "GET"
, url : subdomain + ":" + token + "#" + Config.API.url
, path : "/aaa/bbb"
};
var req = http.request(http_options, function (response) {
// ...
});
req.on('error', function (error) {
console.log('error: ' + error);
});
which produces:
error: ECONNREFUSED

The # is dividing the user / password part from the location part.
the curl line you wrote send a HTTP Authenticate (BASIC authentication) with the request.
curl http://subdomain:token#localhost:9292/aaa/bbb
means: Get localhost:9292/aaa/bbb and do it as user: subdomain password token
I have no idea how to do that in node.js, but you'll figure it out, now that you know what it does.

Related

Karate - Authentication - cannot access url address under password

Using Karate, I have need to use basic authentication (to pass common authentication dialog window with username and password), and I have tried this: https://github.com/intuit/karate#http-basic-authentication-example).
I have created the file basic-auth.js
function fn(creds) {
var temp = creds.username + ':' + creds.password;
var Base64 = Java.type('java.util.Base64');
var encoded = Base64.getEncoder().encodeToString(temp.bytes);
return 'Basic ' + encoded;
}
I have added the call to the test feature file I run (added to Scenario section):
header Authorization = call read('basic-auth.js') { username: 'realusernamestring', password: 'realpasswordstring' }
Then I have placed the url I want to access right after:
driver urlUnderPassword
But it did not work, I still cannot access the page. I think there is something missing, something what needs to be done. Could you help me what the problem might be?
Thank you.
What you are referring to is for API tests not UI tests.
If you need the browser / driver to do basic auth it should be easy, just put it in the URL: https://intellipaat.com/community/10343/http-basic-authentication-url-with-in-password
So I am guessing something like this will work:
* driver 'http://' + username + ':' + password + '#' + urlUnderPassword

Is there a way to add a post in wordpress via googlescript?

I have a form in googlescript where I can add a user to a sheet.
Is there a way to implement some lines in that code so the script adds a post on a wordpress page?
I read that it's possible via wp_insert_post , but I have no idea how that works in my case.
EDIT:
As Spencer suggested I tried to do it via WP REST API.
The following code seems to be working .............
function httpPostTemplate() {
// URL for target web API
var url = 'http://example.de/wp-json/wp/v2/posts';
// For POST method, API parameters will be sent in the
// HTTP message payload.
// Start with an object containing name / value tuples.
var apiParams = {
// Relevant parameters would go here
'param1' : 'value1',
'param2' : 'value2' // etc.
};
// All 'application/json' content goes as a JSON string.
var payload = JSON.stringify(apiParams);
// Construct `fetch` params object
var params = {
'method': 'POST',
'contentType': 'application/json',
'payload': payload,
'muteHttpExceptions' : true
};
var response = UrlFetchApp.fetch(url, params)
// Check return code embedded in response.
var rc = response.getResponseCode();
var responseText = response.getContentText();
if (rc !== 200) {
// Log HTTP Error
Logger.log("Response (%s) %s",
rc,
responseText );
// Could throw an exception yourself, if appropriate
}
else {
// Successful POST, handle response normally
Logger.log( responseText );
}
}
But I get the error:
[16-09-28 21:24:29:475 CEST] Response (401.0)
{"code":"rest_cannot_create","message":"Sorry, you are not allowed to
create new posts.","data":{"status":401}}
Means: I have to authenticate first.
I installed the plugin: WP REST API - OAuth 1.0a Server
I setup a new user and got a client key and client user.
But from here I have no clue what to do : /
It is possible. Wordpress has a REST API. I can be found at:
http://v2.wp-api.org/
You will use the UrlFetchApp Service to access this api. Documentation can be found at:
https://developers.google.com/apps-script/reference/url-fetch/url-fetch-app
Read the docs and try to write some code. It you get stuck post the code that is confusing you here and I'll update this answer.
You should add you authentification in the header :
var headers = {
... ,
'Authorization' : 'Basic ' + Utilities.base64Encode('USERNAME:PASSWORD'),
};
And then add your header in your parameters :
var params = {
'method': 'POST',
'headers': headers,
'payload': JSON.stringify(payload),
'muteHttpExceptions': true
}
And then use UrlfetchApp.fetch
var response = UrlFetchApp.fetch("https://.../wp-json/wp/v2/posts/", params)
Logger.log(response);
You need to pass the basic auth, like this:
// Construct `fetch` params object
var params = {
'method': 'POST',
'contentType': 'application/json',
'payload': payload,
'muteHttpExceptions' : true,
"headers" : {
"Authorization" : "Basic " + Utilities.base64Encode(username + ":" + password)+"",
"cache-control": "no-cache"
}
};
thank you for giving me these important links.
<3
I installed WP REST API and the OAuth plugin.
In the documentation is written:
Once you have WP API and the OAuth server plugins activated on your
server, you’ll need to create a “client”. This is an identifier for
the application, and includes a “key” and “secret”, both needed to
link to your site.
I couldn't find out how to setup a client?
In my GoogleScriptCode according to the WP API I get the error:
{"code":"rest_cannot_create","message":"Sorry, you are not allowed to create new posts.","data":{"status":401}}
Edit: I found it - it's under User/Application
I'll try to figure it out and get back to you later.

Meteor HTTP.call() Authorization Header

I'm developing a new accounts-*** package for an API which uses an authorization header rather than an access_token parameter (as is done by most other APIs/packages I've seen). However, every version I've attempted has resulted in a 401 being returned. I've tried a few variations to no avail (Authorization in quotes/without quotes, declaring the accessToken as a new variable inside the funtion, etc.). Am I missing something obvious?
////////////////////////////////////////////////
// packages/newApi/newApi_server.js
////////////////////////////////////////////////
// Other steps for exchanging auth code for access and refresh tokens
var getIdentity = function(accessToken){
var accessTokenString = 'Bearer ' + accessToken;
try {
return HTTP.get("https://testapi.testing.com/user/info", {
headers: {
'Authorization': accessTokenString
}
}).data;
} catch(err) {
throw_.extend(new Error('You done goofed. ' + err.message));
}
};
Edit: I had tried securing my accessToken earlier in the OAuth flow which was breaking the identity fetching.
As I explained in the edit, it was a silly encoding/encryption mistake. Make sure your access tokens are properly accessible.

Router.url() returning undefined in Email.send()

I am trying to construct an email for some users. Code is running server-side. In the email I would like to have a link for the users to click on, but I am not having much luck.
I am trying to use Router.url() to set the href of an anchor. I can do console.log() and see the Router object is at least defined, but the link ends up being strange.
The code looks like this:
Meteor.methods({
sendSubmissionEmail: function(responseId) {
// Let other method calls from the same client start running,
// without waiting for the email sending to complete.
this.unblock();
var formResponse = FormResponses.findOne({_id: responseId});
var toEmails = [];
_.each(Roles.getUsersInRole('ADMIN').fetch(), function(user) {
if (user.profile && user.profile.receivesResponseEmails) {
var email = _.findWhere(user.emails, {verified: true});
if (!email) {
console.log('No verified email address was found for ' + user.username + '. Using unverified email instead.');
email = _.first(user.emails);
}
if (email) {
toEmails.push(email.address);
}
}
});
if (toEmails && toEmails.length > 0) {
console.log('Sending an email to the following Admins: ' + toEmails);
console.log('Router: ', Router);
Email.send({
from: 'noreply#strataconsulting.us',
to: toEmails,
subject: 'Form Response for Form "' + formResponse.form_title + '" Ready For Approval',
html: '<p>Form Response for Form ' + formResponse.formTitle + ' is now ready for your approval.</p>'
});
}
}
});
And the resulting email:
====== BEGIN MAIL #0 ======
MIME-Version: 1.0
From: noreply#strataconsulting.us
To: testuser4#codechimp.net
Subject: Form Response for Form "undefined" Ready For Approval
Content-Type: text/html; charset=utf-8
Content-Transfer-Encoding: quoted-printable
<p>Form Response for Form Test Form One is now ready for your approval.</p>
====== END MAIL #0 ======
First, there is a strange "3D" appearing prior to the first " of the href, then the return or Router.url() is always undefined. Just to make sure the call was right, I simulated it in Chrome's dev tools console by doing the following:
var fr = FormResponses.findOne({_id: '1234567890'});
Router.url('editResponse', fr);
As expected this spits out the full URL path to my editResponse route with the correct ID set. Is Router.url() a client-only call? If so, how do I get the URL to a route server-side? All routes are defined for both client and server.
Here:
var fr = FormResponses.findOne({_id: '1234567890'});
Router.url('editResponse', fr);
You're passing the result of the Find as a parameter. It'll look like
{ _id: ..., otherStuff: ...}
But in your code you're not passing an object, you're just passing a string:
Router.url('editResponse', formResponse.id)
That explains the "undefined".
The 3D is very odd.

send email in Meteor app with mailGun - Error invoking Method 'sendEmail'

I use Meteor v1 to buid un app, and to be able to send a email from my app, I add Email package.
This is my code on the client
Template.Home.events({
'click button': function(event, template){
event.preventDefault();
var depart = template.find('[id=exampleInputEmail1]').value;
var arrive = template.find('[id=exampleInputPassword1]').value;
var email = template.find('[id=exampleInputPassword1m]').value;
var nom = template.find('[id=exampleInputPassword1s]').value;
var telephone = template.find('[id=exampleInputPassword1n]').value;
var element = template.find('[id=exampleInputPassword1j]').value;
Meteor.call('sendEmail', 'nwabdou85#yahoo.fr', email, 'Faites moi un devis rapide svp', 'This is a test of Email.send.');
}
});
And the server one is
Meteor.startup(function() {
var username = "postmaster%40sandboxxxxxxxx.mailgun.org";
var password = "xxxxxxxxxxx";
var server = "smtp.mailgun.org";
var port = "587"
process.env.MAIL_URL = 'smtp://' + encodeURIComponent(username) + ':' + encodeURIComponent(password) + '#' + encodeURIComponent(server) + ':' + port;
});
// In your server code: define a method that the client can call
Meteor.methods({
'sendEmail': function (to, from, subject, text) {
// check([to, from, subject, text], [String]);
this.unblock();
Email.send({
to: to,
from: from,
subject: subject,
text: text
});
}
});
but it does not work !! it throw out this error on consol : Error invoking Method 'sendEmail': Internal server error [500]
Can you even have this issue and hwo do you fixe it ??
I would suggest switching your hosting to Heroku, which is free but more configurable. Try reading my recent article on the subject, should give you some hints: http://joshowens.me/modulus-vs-heroku-vs-digital-ocean/.
If that is a 500 error from mailgun then its something on their side not yours. try accessing your dashboard on mailgun and see if you can get some info from there. I spent abit of time trying to get this right and it was all to do with getting the Mail url correct.
I remember in the bulletproof meteor you should use Meteor.defer function to delay your email sending process. Usually sending email caused response timeout.
Again, this.unblock might not useful in this case. Please try to comment out it if the first way doesn't work.
encodeURIcomponent would convert something from sam#sam.com to sam%40sam.com.
Your username is already URI encoded, so doesn't need to be further encoded. In this case, you are double encoding the username, and hence was probably failing with an authentication error.

Resources