I have a url and i need to enter a port number to the url.
the url is not a valid url.
here is few show cases :
https://example.com_users/param/param/param - https://example.com_users:8080/param/param/param
http://example.co_setting/param/param/param - http://example.co_settings:1000/param/param/param
http://example.co_setting- http://example.co_settings:1000
const addPort = (url,port) =>{
combined = ???????? // how to combian them
return combined
}
You could use a regular expression:
const addPort = (url, port) =>
url.replace(/^(https?:\/\/)?([^/]*)(\/.*)?$/, '$1' + '$2:' + port + '$3');
console.log(addPort('http://www.example.com/full/url/with/param', '8080'))
var urlstring = 'https://example.com_users/param/param/param';
var port = ':8080';
var allparts = urlstring.split('//');
var last = allparts[1];
var alllastparts = last.split('/');;
alllastparts[0] = alllastparts[0]+port;
alert(allparts[0]+ '//' + alllastparts.join('/'));
console.log(allparts[0]+ '//' + alllastparts.join('/'));
Related
I am trying to query Azure Table storage without using NodeJS. If I run the query on the whole table (sales) I get all the results fine, but when I want to filter on Partition Key and RowKey I get the error "Server failed to authenticate the request. Make sure the value of Authorization header is formed correctly including the signature"
Here is my code
var storageAccount = 'xxxxxxxxx';
var accountKey = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx';
var date = new Date();
var UTCString = date.toUTCString();
var dataToEncode = UTCString + "\n" + "/" + storageAccount + "/sales";
var hash = CryptoJS.HmacSHA256(dataToEncode, CryptoJS.enc.Base64.parse(accountKey));
var strSignature = CryptoJS.enc.Base64.stringify(hash);
var auth = "SharedKeyLite " + storageAccount + ":" + strSignature;
var tableName = 'sales';
var pk ="CAR1748"
var rk = "1";
var queryString = encodeURIComponent(tableName + "(PartitionKey='" + pk + "',RowKey='" + rk + "')");
var path = "https://" + storageAccount + ".table.core.windows.net/" + queryString ;
var header = { "Accept" : "application/json;odata=nometadata", "x-ms-date" : UTCString , "Authorization" : auth , "x-ms-version": "2021-06-08", "DataServiceVersion": "3.0;NetFx","MaxDataServiceVersion": "3.0;NetFx" };
try {
var response = https.get({
url: path,
headers: header
});
context.response.write(response.code);
} catch (e) {
//context.response.write(response.code);
context.response.write(response.body);
return true;
}
Based on the documentation provided here, you would need to include the query string in your data to encode.
So your code would be something like:
var storageAccount = 'xxxxxxxxx';
var accountKey = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx';
var tableName = 'sales';
var pk ="CAR1748"
var rk = "1";
var date = new Date();
var UTCString = date.toUTCString();
var queryString = encodeURIComponent(tableName + "(PartitionKey='" + pk + "',RowKey='" + rk + "')");
var dataToEncode = UTCString + "\n" + "/" + storageAccount + "/" + queryString;
var hash = CryptoJS.HmacSHA256(dataToEncode, CryptoJS.enc.Base64.parse(accountKey));
var strSignature = CryptoJS.enc.Base64.stringify(hash);
var auth = "SharedKeyLite " + storageAccount + ":" + strSignature;
var path = "https://" + storageAccount + ".table.core.windows.net/" + queryString ;
var header = { "Accept" : "application/json;odata=nometadata", "x-ms-date" : UTCString , "Authorization" : auth , "x-ms-version": "2021-06-08", "DataServiceVersion": "3.0;NetFx","MaxDataServiceVersion": "3.0;NetFx" };
try {
var response = https.get({
url: path,
headers: header
});
context.response.write(response.code);
} catch (e) {
//context.response.write(response.code);
context.response.write(response.body);
return true;
}
let NewName= params.strdocumentname + "(" + results.rows[0].arrayfilecount+ ")";
strdocumentname = params.strdocumentname = NewName;
the current output is Jayson.png(2)
desired output Jayson (2).png
How do i do that using the code above?
Use the following code:-
const path = require('path');
const extension= path.extname(params.strdocumentname);
const name= params.strdocumentname.replace(extension,"(" + results.rows[0].arrayfilecount+ ")");
const newName = name + extension;
Hope it helps
Thanks
I think your params.strdocumentname contains the extension of the file also.
Try this code;
let [fileName, extension] = params.strdocumentname.split('.');
let NewName= fileName + "(" + results.rows[0].arrayfilecount+ ")." + extension;
strdocumentname = params.strdocumentname = NewName;
see working fiddle
let mockFileName = "abc.png"
let mockArrayCount = '1'
let [fileName, extension] = mockFileName.split('.');
let NewName= fileName + "(" + mockArrayCount+ ")." + extension;
console.log(NewName)
alert(NewName)
This is what I have so far but it returns only one proxy because it rewrites over it x (however many proxies) times. I do not want to make a new file but instead rewrite proxies.txt with every proxy.
const fs = require("fs");
const formatProxies = () => {
const rawProxies = fs.readFileSync("./proxies.txt", "utf-8");
const split = rawProxies.trim().split("\n");
for (const p of split) {
const parts = p.trim().split(":");
const [ip, port, user, pass] = parts;
fs.writeFileSync(
"./proxies.txt",
user + ":" + pass + "#" + ip + ":" + port + "\r\n",
{ encoding: "utf8" }
);
}
};
formatProxies();
Does this work?
const fs = require("fs");
const formatProxies = () => {
const rawProxies = fs.readFileSync("./proxies.txt", "utf-8");
const split = rawProxies.trim().split("\n");
const lines = []
for (const p of split) {
const parts = p.trim().split(":");
const [ip, port, user, pass] = parts;
lines.push(user + ":" + pass + "#" + ip + ":" + port)
}
fs.writeFileSync(
"./proxies.txt",
lines.join("\r\n"),
{ encoding: "utf8" }
);
};
formatProxies();
Node.js has fs.appendFileSync, which writes to the end of the file instead of overwriting the whole thing.
I need to send HTTP request to AWS with signed request via Javascript. Sadly I cannot use the AWS SDK JS as its either for Node.js or browser, but I need to run it from Rhino JS environment.
seems I am doing something very wrong as I get whatever I do same result - AWS was not able to validate the provided access credentials.
:(
The code I am using is same as the one Amazons is using as example (but in Python). I am using only one external lib so I can use HMCA &SHA.
Any help is much appreciated (and needed as I am struggling for days by now...), so yeah - help!
Thanks is advance!
Cheers,
Joro
gs.include('jshashes');
var method = 'GET';
var service = 'ec2';
var host = 'ec2.amazonaws.com';
var region = 'us-east-1';
var endpoint = 'https://ec2.amazonaws.com';
var access_key = 'ACCESSKEY';
var secret_key = 'SECRET/KEY';
var request_parameters = 'AWSAccessKeyId' + access_key + 'Action=RunInstances&&ImageId=ami-b770fbd8';
function getSignatureKey(key, date, region, service){
var newKey = "AWS4" + key;
var kDate = new Hashes.SHA256().b64_hmac(newKey, date);
var kRegion = new Hashes.SHA256().b64_hmac(kDate, region);
var kService = new Hashes.SHA256().b64_hmac(kRegion, service);
var kSigning = new Hashes.SHA256().b64_hmac(kService, "aws4_request");
return kSigning;
}
var gdt = new GlideDateTime();
var datestamp = gdt.getDate().getByFormat('yyyyMMdd') + 'T' +
gdt.getTime().getByFormat('HHmmss') + 'Z';
var amzdate = gdt.getDate().getByFormat('yyyyMMdd')+"";
var canonical_uri = '/';
var canonical_querystring = request_parameters;
var canonical_headers = 'host:' + host + '\n' + 'x-amz-date:' + amzdate + '\n'
var signed_headers = 'host;x-amz-date';
var payload_hash = new Hashes.SHA256().hex("");
var canonical_request = method + '\n' + canonical_uri + '\n' + canonical_querystring + '\n' + canonical_headers + '\n' + signed_headers + '\n' + payload_hash;
var algorithm = 'AWS4-HMAC-SHA256';
var credential_scope = datestamp + '/' + region + '/' + service + '/' + 'aws4_request';
var string_to_sign = algorithm + '\n' + amzdate + '\n' + credential_scope + '\n' + new Hashes.SHA256().hex(canonical_request);
var signing_key = getSignatureKey(secret_key, datestamp, region, service);
//Python
//var signature = hmac.new(signing_key, (string_to_sign).encode('utf-8'), hashlib.sha256).hexdigest()
var signature = new Hashes.SHA256().hex_hmac(signing_key, string_to_sign);
var authorization_header = algorithm + ' ' + 'Credential=' + access_key + '/' + credential_scope + ', ' + 'SignedHeaders=' + signed_headers + ', ' + 'Signature=' + signature
var headers = {'x-amz-date':amzdate, 'Authorization':authorization_header}
var request_url = endpoint + '?' + canonical_querystring
var httpRequest = new GlideHTTPRequest(request_url);
httpRequest.setRequestHeader(headers);
var res = httpRequest.get();
gs.print(res.statusCode);
gs.print(res.allHeaders);
gs.print(res.body);
Check the URL construction. For one, the request_parameters have some missing and misplaced delimiters.
var request_parameters = 'AWSAccessKeyId=' + access_key +
'&Action=RunInstances&ImageId=ami-b770fbd8';
In addition to inspecting and testing the resulting URL, you might also try to simply the syntax to make it easier to check and update. Just as an example, the following
var credential_scope = datestamp + '/' + region + '/' + service + '/' + 'aws4_request';
var string_to_sign = algorithm + '\n' + amzdate + '\n' + credential_scope + '\n' + new Hashes.SHA256().hex(canonical_request);
could be written as follows (which seems easier to check to me):
var credential_scope = [
datestamp,
region,
service,
'aws4_request'
].join('/');
var string_to_sign = [
algorithm,
amzdate,
credential_scope,
new Hashes.SHA256().hex(canonical_request)
].join('\n');
Why does the Heroku Nodejs AWS S3 tutorial (https://devcenter.heroku.com/articles/s3-upload-node) fail when a plus '+' character is present in the signature?
Summary: Regenerate the signature until it does not contain a plus '+' character anymore:
if (signature.indexOf('+') != -1) {
setTimeout(function(){
//regenerate signature until it doesn't contain + anymore
generateSignature();
}, 400);
}
The working solution I found was suggested by #chadsaun on this forum post:
http://www.uploadify.com/forum/#/discussion/comment/10777
Full heroku example code solution:
app.get('/sign_s3', function(req, res){
var object_name = req.query.s3_object_name;
var mime_type = req.query.s3_object_type;
var amz_headers = "x-amz-acl:public-read";
var signature, expires;
function generateSignature() {
var thisTime = new Date().getTime();
expires = Math.ceil((thisTime + 10000)/1000);
var put_request = "PUT\n\n" + mime_type + "\n"
+ expires + "\n" + amz_headers
+ "\n/" + S3_BUCKET + "/"
+ object_name;
signature = crypto.createHmac('sha1', AWS_SECRET_KEY)
.update(put_request)
.digest('base64');
console.log(signature);
if (signature.indexOf('+') != -1) {
setTimeout(function(){
//regenerate signature until it doesn't contain + anymore
generateSignature();
}, 400);
} else {
var url = 'https://' + S3_BUCKET + '.s3.amazonaws.com/' + object_name;
var credentials = {
signed_request: url + "?AWSAccessKeyId=" + AWS_ACCESS_KEY
+ "&Expires=" + expires + "&Signature="
+ signature,
url: url,
};
res.write(JSON.stringify(credentials));
res.end();
}
}
generateSignature();
});
I guess you need to uri encode your signature. like this:
signature = encodeURIComponent(
crypto.createHmac('sha1', AWS_SECRET_KEY)
.update(put_request)
.digest('base64')
);
this way you don't need to check if the signature contain '+'