matching req.body number without quotes - node.js

I have the following line of code which run when I send {"key":"1234"} to the server.
if (
(req.path === '/start' || req.path === '/start/') &&
(req.method === 'PUT') && (req.body.key === '1234')
)
However the app I am using sends this content as {"key": 1234} to the server without the quotes around the number and therefore the if statement is getting ignored.
How would I write the if statement above so that req.body.key matches 1234 without the need of the quotes.
Thanks for the help

Use two equals signs rather than three in
req.body.key == '1234'
That will let Javascript convert strings to numbers as it does the comparisons.
Your IDE may whine that you should use three equals signs. Ignore it. You're using two equals signs as intended by the language.

I am not sure if the issue is with how the server accepts the request. However, if it's just a matter of if statements, then you either:
Just leave the single quotes out in the condition req.body.key === 1234
Use == instead of ===, which does not strictly verify the value (including the type) req.body.key == '1234'. Though I wouldn't recommend this, as it this leaves room for errors.

Related

Kotlin and String.contains() not working as I thought

I thought I knew how string.contains() worked in Kotlin and Java, but apparently I don't.
I'vet got a small piece of code that takes a list of file names, and puts them in another list if the do not contain certain words.
for (i in 0..filliste.size-1) {
if (!filliste[i].contains("utenfastbopel") || !filliste.contains("sperret") ||
!filliste.contains("reservert")){
var a = filliste[i]
tempFnrliste += filliste[i].split("_")[0]
}
}
However, this does not exclude a file which contains the phrase "sperretstrengtreservert", even though both "reservert" and "sperret" is in the "not contains".
How come? I thought .contains found every occurence of a substring?
But if you look at the debug run, a file containing two of the phrases that are to be ignored, is indeed not ignored:
UPDATE:
To be clear, I'm looking for any of the file names to contain one OR more of the strings. So the logical OR/|| is correct.
However, I missed some indices. But adding them changed nothing. See the updated code below:
As far as I can see, the code now clearly says IF THE STRING DOES NOT CONTAIN THIS, THIS OR THIS SUBSTRING... But still, a string containing two of the substrings gets a match.
Strangely, if I only use ONE substring in the "not-contains" - for instance "reservert", the code does indeed skip all strings not containing that. But when I use the || operator for several substrings, things gets messed up.
"sperretstrengtreservert" does not contain utenfastbopel.
You are using || aka OR. Your first condition is true.
If any of these is true, it will go to the body of the condition.
!filliste[i].contains("utenfastbopel") ||
!filliste.contains("sperret") ||
!filliste.contains("reservert")
Also as said you are not accessing the same object in the follow-up conditions although it wouldn't change the result as is.
You need to change it from "at least one of these conditions must be true" to "all of these conditions must be true" && aka AND.
for (i in 0..filliste.size-1) {
val f = filliste[i]
if (!f.contains("utenfastbopel") && !f.contains("sperret") && !f.contains("reservert")) {
tempFnrliste += f.split("_")[0]
}
}

Why postgres is returning additional backslash in a simple query

So in my node code postgres query is returning double quotes when it's returning its values.
As opposed to the query at pgAdmin.
I already tried to solve it using regex but this attempt was innefective. So if anyone had a problem like this and could help me, I would be glad.
Thanks in advance
There are neither quotes nor extra back slashes in the string. They are part of the string representation as literal.
Try console.log(value) - or even directly console.log('/\\w/g') - and you'll see the output is /\w/g as expected.
To answer my own question, after a lot of reading and researching, I managed to discover that because a backslash character is a special character it will create some problems around its implementation in regex, because it is not permitted to have a lone backslash stored in a variable for example.
This would never work stored inside a variable because the backslash have to be escaped.
/\w+/ig
Javascript will transform it automatically to be able to perform.
/\w+/ig
When reading
RegExp - Javascript documentation, I came across an interesting statement, the RegExp function will recognize and use a double slash regex, thankfully!
So I just adapted my regex to split it's statement from it's flags and mount it again using RegExp.
Below is the code that I used to solve this problem
// Getting values from postgres
const values = (await pgConn.admRead.query(clientQuery)).rows[0].value || [];
// Splitting regex ( values: /\w/g )
const valuesSplit = values.split('/'); // RESULT -> ['', w, g]
// Removing first array item when it's empty
if (valuesSplit[0].length === 0) {
valuesSplit.shift();
}
// Creating regex from splitted array
const regexOperation = new RegExp(valuesSplit[0], valuesSplit[1]);
// Executing replace function
const messageMasked = message.replace(regexOperation, '*');
return messageMasked;

how to do date search in mvc core c# when date format is yyyy-mm-dd?

I have a grid in .net mvc core that I apply a search in every column in the grid based on a search string. It works on every search string I put in EXCEPT for date strings like yyyy-mm-dd ( ie when hyphens are used).
When I put in yyyy or mm or dd individually the search works. But when I put in yyyy plus the hyphen (ie yyyy-) , it never finds any records.
Here is my c# code for the filter:
if (!String.IsNullOrEmpty(searchString))
{
serviceRequests = serviceRequests.Where(s => s.Id.ToString().ToLower().Contains(searchString.ToLower())
|| s.DateTimeSubmitted != null && s.DateTimeSubmitted.ToString().ToLower().Contains(searchString.ToLower())
|| s.RequestHeading != null && s.RequestHeading.ToLower().Contains(searchString.ToLower())
|| s.RequestDescription != null && s.RequestDescription.ToLower().Contains(searchString.ToLower())
|| s.RequestorId != null && s.RequestorId.ToLower().Contains(searchString.ToLower())
|| s.RequestorFirstName != null && s.RequestorFirstName.ToLower().Contains(searchString.ToLower())
|| s.RequestorLastName != null && s.RequestorLastName.ToLower().Contains(searchString.ToLower())
);
}
How does the filter syntax have to be changed to allow for "yyyy-mm-dd" strings to be used? Why does the hyphen cause problems?
Thanks
It looks like DateTimeSubmitted is of type DateTime. What happens if you use the DateTime.ToString() method? Citing from the documentation:
Converts the value of the current DateTime object to its equivalent
string representation using the formatting conventions of the current
culture.
So, the string representation may not what you expect, e.g. 01.01.0001 00:00:00
I suggest to format the source with a format string like this:
DateTimeSubmitted.ToString("yyyy-MM-dd");
Or another format that fits your needs.
turns out it was a slight twist on suggestion:
|| s.DateTimeSubmitted != null && s.DateTimeSubmitted.Value.ToString("yyyy-MM-dd").ToLower().Contains(searchString.ToLower())
Had to change DateTimeSubmitted.ToString to DateTimeSubmitted.Value.ToString(yyyy-MM-dd) to be able to specify formatting. - ie adding .value before .ToString
Thanks so much!

String Comparison with Elasticsearch Groovy Dynamic Script

I have an elasticsearch index that contains various member documents. Each member document contains a membership object, along with various fields associated with / describing individual membership. For example:
{membership:{'join_date':2015-01-01,'status':'A'}}
Membership status can be 'A' (active) or 'I' (inactive); both Unicode string values. I'm interested in providing a slight boost the score of documents that contain active membership status.
In my groovy script, along with other custom boosters on various numeric fields, I have added the following:
String status = doc['membership.status'].value;
float status_boost = 0.0;
if (status=='A') {status_boost = 2.0} else {status_boost=0.0};
return _score + status_boost
For some reason associated with how strings operate via groovy, the check (status=='A') does not work. I've attempted (status.toString()=='A'), (status.toString()=="A"), (status.equals('A')), plus a number of other variations.
How should I go about troubleshooting this (in a productive, efficient manner)? I don't have a stand-alone installation of groovy, but when I pull the response data in python the status is very much so either a Unicode 'A' or 'I' with no additional spacing or characters.
#VineetMohan is most likely right about the value being 'a' rather than 'A'.
You can check how the values are indexed by spitting them back out as script fields:
$ curl -XGET localhost:9200/test/_search -d '
{
"script_fields": {
"status": {
"script": "doc[\"membership.status\"].values"
}
}
}
'
From there, it should be an indication of what you're actually working with. More than likely based on the name and your usage, you will want to reindex (recreate) your data so that membership.status is mapped as a not_analyzed string. If done, then you won't need to worry about lowercasing of anything.
In the mean time, you can probably get by with:
return _score + (doc['membership.status'].value == 'a' ? 2 : 0)
As a big aside, you should not be using dynamic scripting. Use stored scripts in production to avoid security issues.

what does pam_unix : bad username mean?

Can anybody please tell me what does this error mean.And when will this appear. I tried googling, but with no result. Please point me to the correct document to understand this error.
This error is triggered by the following code in the pam_unix module (source: Linux-PAM-0.99.5):
if (name == NULL || !isalnum(*name))
the name == NULL would be triggered by a programmatic error in the use of the PAM protocol where the username variable is not being set as part of the pam conversation.
The second reason, and probably the most interesting is that the first character of the username is required to be an alpha-num i.e the character must be one of A-Z, a-z or 0-9. Accented characters are not accepted.
A newer version of Linux-PAM (as seen from the fedorahosted source of pam_unix.c) says:
if (name == NULL || name[0] == '-' || name[0] == '+')
Which means that it only rejects the - and + characters - i.e. it is less strict than the older source.

Resources