Ionic 3, encodeURI with firebase - javascript

I need to send a http request to firebase that has this shape
https://db.firebaseio.com/0.json?&orderBy="name"&startAt=query&endAt=query+"\uf8ff"&limitToLast=1&print=pretty&auth=auth_token
My problem is that when I call this request I've a 400 error in console because it replace %22 to question marks and other symbols for \uf8ff and I think firebase doesn't recognize that.
let name = '"name"';
let cod = '"\uf8ff"';
let url = ('https://db.firebaseio.com/0.json?&orderBy=' + encodeURIComponent(name) + '&startAt=' + encodeURIComponent(birraName) + '&endAt=' + encodeURIComponent(birraName) + '+' + encodeURIComponent(cod) + '&limitToLast=1&print=pretty&auth=' + encodeURIComponent(this.idToken));
let response = this.http.get(url).map(res => res.json());
return response;
And then in console
400 Bad Request
Do you have any thougths?

You're missing quotes in your target string to mark string values. If you're searching for nodes starting with Marco, it should be https://db.firebaseio.com/0.json?&orderBy="name"&startAt="Marco"&endAt="Marco\uf8ff"&limitToLast=1&print=pretty&auth=auth_token. Note the double quotes around "Marco" and "Marco\uf8ff".
To build these in your JavaScript:
var url = 'https://db.firebaseio.com/0.json';
url = url + '?orderBy="' + encodeURIComponent(name) + '"';
url = url + "&startAt="' + encodeURIComponent(birraName) + '"';
url = url + "&endAt="' + encodeURIComponent(birraName) + '\uf8ff"';
url = url + '&limitToLast=1&print=pretty';
url = url + '&auth="' + encodeURIComponent(this.idToken))+'"";
Template literals might also be useful to keep this readable:
let url = (`https://db.firebaseio.com/0.json?orderBy=${encodeURIComponent(name)}&startAt=${encodeURIComponent(birraName)}&endAt=${encodeURIComponent(birraName)}${encodeURIComponent(cod)}&limitToLast=1&print=pretty&auth=${encodeURIComponent(this.idToken))}`;

Related

Regex to replace only some / characters inside strings

How to get regex with replace method? In my case I've got string which uses char / between.
input:
var string = "cn/" + companyName + "/st/" + state + "/ic/" + incCi + "/pr/" + priority + "/es/" + emplSystem + "/mc/" + mainCategory + "/sc/" + subCategory + "/ty/" + type;
output:
"cn/Nemesis Group/st/2/ic/null/pr/1 - High/es/null/mc/Add/Button/sc/Core/Label/ty/str"
variable mainCategory and subCategory returns string 'Add/Button' and 'Core/Label'
How to replace 'Add/Button' to 'Add%2FButton' and 'Core/Label' to 'Core%2FLabel' without changing any other char?
string.replace("\/", "%2F")
will change all char / to %2F
You can use encodeURIComponent() and decodeURIComponent() to transform this String
Example:
const companyName = "Company",
state = "State",
incCi = "IncCi",
priority = "Priority",
emplSystem = "EmplSystem",
mainCategory = 'Add/Button',
subCategory = 'Core/Label',
type = "Type";
var string = "cn/" + companyName + "/st/" + state + "/ic/" + incCi + "/pr/" + priority + "/es/" + emplSystem +
"/mc/" + encodeURIComponent(mainCategory) +
"/sc/" + encodeURIComponent(subCategory) + "/ty/" + type;
console.log(string)
It sounds to me like you are looking to encode the url. You can use encodeURI in JS to encode a url.
let encodedURL = encodeURI(url);
You can read more about it here.
If you want to encode the string altogether without ignoring any domain related parts, you can us encodeURIComponent()
let encodedURL = encodeURIComponent(url);
You can read more about their differences here.
EDIT:
If you are not encoding a url and you just want to repalce / with %2F only in mainCategory and subCategory then you need to run the regex on the string itself before joining them.
var string = "cn/" + companyName +
"/st/" + state +
"/ic/" + incCi +
"/pr/" + priority +
"/es/" + emplSystem +
"/mc/" + mainCategory.replace("\/", "%2F") +
"/sc/" + subCategory.replace("\/", "%2F") +
"/ty/" + type;

How to send encode string as a parameter into url string in angular and open in new tab

How to send encode string as a parameter into URL string in angular and open in new tab. I am trying to send multiple parameter separated by '-' and converted into base64 encode through url but it is throwing me into not found. I am using angular 8. using router.navigate , it is working fine but I want to open url in new tab.
here is my code in TS.
goToAssessmentPage(event, assignmentId, courseId, studentId, instituteId, sectionId , assignment_submission_id) {
event.preventDefault()
const string:string = btoa(courseId + '-' + assignmentId + '-' + studentId + '-' + instituteId + '-' + sectionId + '-' + assignment_submission_id)
const url: string = string + '/grader-assessment';
window.open(url, '_blank');
}
app.routing.ts
{
path: ':params/grader-assessment',
component: GraderAssessmentPageComponent
},
Well you'll more than likely need the whole url tree in that url string for window.open to work.
From the docs (https://angular.io/api/router/Router#createurltree)
// create /team/33/user/11
router.createUrlTree(['/team', 33, 'user', 11]);
And on top of that (https://angular.io/api/router/Router#serializeurl)
serializeUrl(url: UrlTree): string
So in your case it would be something like:
const string:string = btoa(courseId + '-' + assignmentId + '-' + studentId + '-' + instituteId + '-' + sectionId + '-' + assignment_submission_id)
const fullUrl:string = this.router.serializeUrl(router.createUrlTree([string, '/grader-assessment']));
// Then you navigate to this full url
window.open(fullUrl, '_blank');

Azure Account Shared Access Signiture

I am trying to construct an Account level Shared Access Signiture so my client can access all containers in a storage account. I am following these docs Account SAS. It seems straight forward enough but I keep getting the following error message:
"Signature did not match. String to sign used was accountname\nrl\nb\nsc\n\n2016-10-09\n\n\n2015-04-05\n".
My parameters are identical so I suspect it has something to do with how I am hashing the String to Sign. Below is how I construct the token.
var crypto = require('crypto');
var accountName = 'accountname';
var accountKey = 'tH37FTlG3TUT86caMrt2y5kOzof8nFqqA6spzg6r7HPRojE1zDiLJD/xE4oLFDh4RNqAmymvlV7fm8W4SF8cJg==';
var signedPermissions = "sp=rl";
var signedServcies = "ss=b";
var signedResourceType = "srt=sc";
var signedExpiry = "se=2016-10-09";
var signedVersion = "sv=2015-04-05";
var stringToSign = accountName + "\n" + signedPermissions + "\n" + signedServcies + "\n" + signedResourceType + "\n" + signedExpiry + "\n" + signedVersion + "\n";
var hmacsha256 = crypto.createHmac('sha256', accountKey).update(stringToSign).digest('base64');
var token = signedPermissions + "&" + signedServcies + "&" + signedResourceType + "&" + signedExpiry + "&" + signedVersion + "&sig=" + hmacsha256;
I have tried using crypto-js as well but to no avail. The final URL used to access a blob in a container is...
"https://accountname.blob.core.windows.net/containername/blobName?srt=sc&se=2016-10-09&api-version=2015-04-05&sp=rl&ss=b&sv=2015-04-05&sig=IFD2wyfRAsHGU5IFg3RbwSJW6tRE0m0%2FxgAYvJ%2FmnEk%3D"
I have been trying for days and really would appreciate knowing what I'm doing wrong. Thanks.
Benzene, for stringToSign, the value should NOT has the parameter name?
var signedPermissions = "rl";
var signedServcies = "b";
var signedResourceType = "sc";
var signedExpiry = "2016-10-09";
var signedVersion = "2015-04-05";
Please try the following (code shamelessly taken from Azure Storage Node.js library):
var hmacsha256 = crypto.createHmac('sha256', new Buffer(accountKey, 'base64')).update(stringToSign, 'utf-8').digest('base64');

oauth 1.0 -invalid signature GetRequestToken for Google

I could not find any active Oauth 1.0 support by Google as it has already been deprecated.
But as I want to access Gmail data,I am bound to use Oauth 1.0
So I have been trying since 2 days to get the RequestToken for my Google Application and I am getting the invalid signature error.
My base-string matches with the debug-string returned by google.
I have tried using both HMAC-SHA1 and RSA-SHA1 and my keys are correct.
(I have even tried using both token and secret as anonymous which Google recommends for non-registered applications.)
Could it be something due to wrong nonce or due to some percent-encoding issue.
The same method worked fine for Twitter.
I am also pasting my code below and would be glad if someone could help or point me to the right forum.
$('#GMAIL_BUTTON').click(function () {
//oauth1 approach similar to twitter
var requestUrl = "https://www.google.com/accounts/OAuthGetRequestToken";
var scope = "https://mail.google.com/";
var clientID = "anonymous";
var clientSecret = "anonymous";
var rsakey = "MIICblahblahblah";
var timestamp = Math.round(new Date().getTime() / 1000.0);
var nonce = Math.random();
var sigBaseStringParams = "oauth_consumer_key=" + clientID;
sigBaseStringParams += "&" + "oauth_nonce=" + nonce;
sigBaseStringParams += "&" + "oauth_signature_method=HMAC-SHA1";
sigBaseStringParams += "&" + "oauth_timestamp=" + timestamp;
sigBaseStringParams += "&" + "scope=" + encodeURIComponent(scope);
var sigBaseString = "GET&";
sigBaseString += encodeURIComponent(requestUrl) + "&" + encodeURIComponent(sigBaseStringParams) + "\n" + "\n";
requestUrl += "?scope=https://mail.google.com/";
var keyText = encodeURIComponent(clientSecret) + "&";
//var keyText = rsakey;
var keyMaterial = Windows.Security.Cryptography.CryptographicBuffer.convertStringToBinary(keyText, Windows.Security.Cryptography.BinaryStringEncoding.Utf8);
var macAlgorithmProvider = Windows.Security.Cryptography.Core.MacAlgorithmProvider.openAlgorithm("HMAC_SHA1");
var key = macAlgorithmProvider.createKey(keyMaterial);
//var keyMaterial = Windows.Security.Cryptography.CryptographicBuffer.decodeFromBase64String(rsakey);
//var macAlgorithmProvider = Windows.Security.Cryptography.Core.AsymmetricKeyAlgorithmProvider.openAlgorithm("RSASIGN_PKCS1_SHA1");
//var key = macAlgorithmProvider.importKeyPair(keyMaterial);
var tbs = Windows.Security.Cryptography.CryptographicBuffer.convertStringToBinary(sigBaseString, Windows.Security.Cryptography.BinaryStringEncoding.Utf8);
var signatureBuffer = Windows.Security.Cryptography.Core.CryptographicEngine.sign(key, tbs);
var signature = Windows.Security.Cryptography.CryptographicBuffer.encodeToBase64String(signatureBuffer);
var dataToPost = "OAuth oauth_consumer_key=\"" + clientID + "\", oauth_nonce=\"" + nonce + "\", oauth_signature_method=\"HMAC-SHA1\", oauth_timestamp=\"" + timestamp + "\", oauth_signature=\"" + encodeURIComponent(signature) + "\", oauth_version=\"1.0\"";
var response = sendGetRequest(requestUrl, dataToPost, null);
});
And the SendGetRequest method is -
function sendGetRequest(url, authzheader, params) {
try {
var request = new XMLHttpRequest();
request.open("GET", url, false);
request.setRequestHeader("Authorization", authzheader);
request.send(params);
return request.responseText;
} catch (err) {
WinJS.log("Error sending request: " + err, "Web Authentication SDK Sample", "error");
}
}
I couldn't find any glaring errors in your code, but you'll probably have a much easier time using Google's OAuth 2 for client-side apps library at https://developers.google.com/accounts/docs/OAuth2UserAgent. Further, you may want to use the atom feed scope (https://mail.google.com/mail/feed/atom)--you can give it and other scopes a try at https://code.google.com/oauthplayground/.

Formatting Strings in JavaScript to use as HTML "MAILTO" links

Here are some strings that I'm using to ultimately form a HTML mailto link. I'm doing this in javascript. If I output the mailtoString to an alert() I get the link looks just fine. However, when I put it into the location.href the string is cut short at the "&" character. How do I tell the location.href that the "&" is not the end of the mailto link?
var subject = escape('subject');
var body = escape('body');
var reportUrl = document.URL + "/GetUpdatedTableResults?beginDate=" + beginDate + "&endDate=" + endDate + "&fileId=" + DocId + '&languageCode=' + LangCode + '&documentResultType=' + result + '&result=' + ReportedIssue;
var excelUrl = document.URL + 'CurReport/GetCSVReport?beginDate=' + beginDate + '&endDate=' + endDate + '&fileId=' + DocId + '&languageCode=' + LangCode + '&documentResultType=' + result + '&result=' + ReportedIssue;
var mailtoString = 'mailto:?subject=' + subject + '&body=' + body + '%0A%0AWeb:%0A' + reportUrl + '%0A%0AExcel:%0A' + excelUrl;
location.href = mailtoString;
After running the code above I get the following output.
http://localhost:5050/CurReport/GetUpdatedTableResults?beginDate=0
Because immediately after mailto: should be the email address. ? is a valid email characters but & is not. Anyway, the & should be escaped to &.

Categories