In MongoUri how can I handle # in my password? - node.js

My Mongo Uri is like this. There must be an # at the end of my password. And Mongo throws an error called= Unescaped at-sign in authority section. Is there a way to make it work?
const url = 'mongodb://roots:something##localhost:27017?authMechanism=DEFAULT&authSource=db';

you can also encode your string using template literals like this:
const DB_USER = 'roots';
const PASSWORD = encodeURIComponent('something#');
const DB_URL = mongodb://${DB_USER}:${PASSWORD}#localhost:27017?authMechanism=DEFAULT&authSource=db';
in my opinion it is also more easy to read
hope it helps =)

Try encoding your user and password with this:
function percentEncode(string) {
let encoded = '';
string.split('').forEach(function(char) {
encoded += '%' + char.charCodeAt(0).toString(16).toUpperCase();
});
return encoded;
}
https://www.rfc-editor.org/rfc/rfc3986#section-2.1
Here's where I got the idea from: https://github.com/strongloop/loopback-connector-mongodb/issues/499
Good Luck =)

You can use URL encoding ,the default ASCII code for # is %40. See link here
const url = 'mongodb://roots:something%40#localhost:27017?authMechanism=DEFAULT&authSource=db';

Related

Issue creating password digest for Amadeus SOAP API

I followed the instructions in the docs and tried to do the same formula in Node, however, I'm not able to correctly authenticate with the server as I receive an 11|Session| response. I assume that error is in response to incorrectly set nonce and/or password digest.
The formula: Base64(SHA1($NONCE + $TIMESTAMP + SHA1($CLEARPASSWORD)))
The variables: $CLEARPASSWORD=AMADEUS, $TIMESTAMP=2015-09-30T14:12:15Z, $NONCE=c2VjcmV0bm9uY2UxMDExMQ==.
The expected hash: +LzcaRc+ndGAcZIXmq/N7xGes+k=
The code I tried was:
const crypto = require('crypto')
const hashedPassword = crypto.createHash('sha1').update(CLEARPASSWORD).digest() // Returns a buffer
crypto.createHash('sha1').update(NONCE + TIMESTAMP + hashedPassword).digest('base64') // Returns a Base64 String
However, this returns DDcZEaS5AtoVaZhsARy9MqV+Y34=. And if I change the nonce to its plain string secretnonce10111, then I get gHOoqyDb9YJBrk30iabSO8nKxio= which still isn't correct.
I'm not sure what could be the issue.
I finally figured out what was wrong. The problem was I was trying to concatenate a string with a Buffer, when I should have just made everything a buffer from the start.
So, instead of
const hashedPassword = crypto.createHash('sha1').update(CLEARPASSWORD).digest()
crypto.createHash('sha1').update(NONCE + TIMESTAMP + hashedPassword).digest('base64')
It should have been
const buffer = Buffer.concat([Buffer.from(NONCE), Buffer.from(TIMESTAMP), nodeCrypto.createHash('sha1').update(CLEARPASSWORD).digest()])
const hashedPassword = nodeCrypto.createHash("sha1").update(buffer).digest("base64")
you can use this php code to generate Digest Password
<?php
date_default_timezone_set('UTC');
$t = microtime(true);
$micro = sprintf("%03d",($t - floor($t)) * 1000);
$date = new DateTime( date('Y-m-d H:i:s.'.$micro) );
echo $timestamp = $date->format("Y-m-d\TH:i:s").$micro . 'Z';
$nonce = mt_rand(10000000, 99999999);
echo $nounce = base64_encode($nonce);//we have to decode the nonce and then apply the formula on it and in xml we have to send the encoded nonce
$password = "AMADEUS"; //clear password
echo $passSHA = base64_encode(sha1($nonce . $timestamp . sha1($password, true), true));
?>

Concatenate strings in flutter adds ""

This is rather a silly question but I can't seem to figure it out. I'm building a flutter app that communicates to an API and in order for the user to be authenticated it sends an token.
Whenever the user logs in I save the token in the Shared Preferences and then when I make an request add the token to the headers or in this case I need it in the url.
However, whenever I concatenate the strings: the server url and the token it adds extra "" to the token. something like:
http://10.0.2.2:64342/chatHub?access_token="token-value"
instead of
http://10.0.2.2:64342/chatHub?access_token=token-value
here's the code:
var preferences = await SharedPreferences.getInstance();
token = preferences.getString(token_key);
var url = '$serverURl?access_token=$token';
As far as I understand your question, I would like to answer it.
That's not possible!
var serverURl = 'http://10.0.2.2:64342/chatHub';
var token = 'token-value';
var url = '$serverURl?access_token=$token';
print(url);
It just prints the correct one!
You can check the string that is stored in the SharedPreferences! That maybe with quotes.
Okay, I figured it out. Since I was sending only the token from the API. I was receiving it with the "" in it.
Instead I now send a json with the token, like: { "token": "token_value"} and then decode it to get the actual value. So when I store it the shared preferences it doesn't keep the "".
So in the backend:
return Ok(new {token = generatedToken});
and in dart
var tokenJson = json.decode(response.body);
var token = tokenJson['token'];
preferences.setString(token_key, token);
Thanks to everyone that helped :)

Combine two urls into one in node.js

I am trying to combine two urls into a single url.
var access_token = 138def4a4e;
var url = "https://graph.facebook.com/app/?access_token=";
I want the final url to be:
url = "https://graph.facebook.com/app/?access_token=[access_token]";
How to do that in node.js? I tried using url. Resolve but it was of no use.
pls help
TIA
As noted above the selected solution is unsafe.
The following snippet should be preferred:
const accessToken = '138def4a4e';
const someValidUrl = 'https://graph.facebook.com/app/?foo=bar'; // note the querystring param
const url = new URL(someValidUrl);
url.searchParams.append('access_token', accessToken);
console.log(url.href);
As you can notice it's able to manage an Url that contains query parameters and the URLencoding of the querystring params.
I am assuming your code looks like this:
var access_token = '138def4a4e'
var url = 'https://graph.facebook.com/app/?access_token='
If so, the answer is:
var combined = url + access_token
For a final answer of:
var access_token = '138def4a4e'
var url = 'https://graph.facebook.com/app/?access_token='
url += access_token
console.log(url)

NodeJS crypto and binary encoding by default

We have a legacy NodeJS API we are looking to move away from. We are extracting the auth component out of it.
We have a function that hashes a password, that looks a bit like:
var sha256 = crypto.createHash('sha256');
sha256.update(password + secret);
return sha256.digest('hex');
Aside from the obvious security implications a function like this has, it's encoded using the binary encoding NodeJS has.
If you pass in a String to update, it will use 'binary' as the encoding format. This results in it actually encoding unicode characters like "Kiełbasa" as "KieBbasa", before SHA256'ing them.
In our Scala code we are now looking to rewrite this legacy function so we can auth old users. But we cannot find a charset to use on these strings that has the same resulting output. Our Scala code looks like:
def encryptPassword(password: String): String = {
Hashing.sha256().hashString(in, Charsets.UTF_8).toString
}
We need the in string to be the same as what Node is using, but we can't figure it out.
Ideas? Node.js... not even once.
Well, turns out this is much easier than it seems. The following code works:
def encryptPassword(password: String): String = {
val in = (password + secret).map(_.toByte.toChar).mkString("")
Hashing.sha256().hashString(in, Charsets.UTF_8).toString
}
Thanks #stefanobaghino

convert byte[] to string with charset Encoding in C#

I'm new to Windows phone 8 Dev and C#. I try to get String from remote server. This is my code:
var client = new HttpClient();
var response = await client.GetAsync(MyUrl);
string charset = GetCharset(response.Content.Headers.ContentType.ToString());
Debug.WriteLine("charset: " + charset); \\debug show: charset: ISO-8859-1
var bytesCharset = await response.Content.ReadAsByteArrayAsync();
Debug.WriteLine(Encoding.UTF8.GetString(bytesCharset,0,bytesCharset.Length));
//Debug show: `m\u1EF9 t�m`
m\u1EF9 t�m is what I got, but I expect it's Vietnamese: Mỹ Tâm. Can anyone give me an idea to get expected result? (I think the bytes is encoded in IOS-8859-1).
Encoding.UTF8 should be interpreting your data correctly, as ISO-8859-1 is a subset of UTF-8. However, so that other encodings are handled transparently, it is probably better to use HttpContent's ReadAsStringAsync() method instead of ReadAsByteArrayAsync().
I suspect you have the correct string there but your debug window simply cannot display those two unicode characters properly.
You can use the static GetEncoding method to request a specificy codepage.
e.g.:
var encoding = Encoding.GetEncoding("ISO-8859-1");
Finally I found the solution. After using Json.Net to parse json from remote server, my problem's gone, and I can get expected result:
JArray jArray = JArray.Parse(isoText);
String exptectedText= jArray[1].ToString();
Actually, I dont know why my code works :( Thank you anyway!

Resources