How to sanitize inputs in nodejs to prevent sql injection? - sql

i have this sanitize function
sanitizeXSS: string => {
const map = {
'&': '&',
'<': '<',
'>': '>',
'"': '"',
"'": ''',
"/": '/',
};
const reg = /[&<>"'/]/ig;
return string.replace(reg, (match)=>(map[match]));
}
And this sanitize function is being used here
addOrUpdateAddress : function (request, resolve)
{
const customerKey = sanitizeXSS(decrypt_key(request.customer_key));
const lat = sanitizeXSS(decrypt_key(request.lat));
const lng = sanitizeXSS(decrypt_key(request.lng));
const line1 = sanitizeXSS(decrypt_key(request.line1));
const line2 = sanitizeXSS(decrypt_key(request.line2));
const city = sanitizeXSS(decrypt_key(request.city));
const pincode = sanitizeXSS(decrypt_key(request.pincode));
const state = sanitizeXSS(decrypt_key(request.state));
const contact = sanitizeXSS(decrypt_key(request.contact));
const landmark = request.landmark?sanitizeXSS(decrypt_key(request.landmark)):null;
let req=request;
if(req.name && req.email)
{
updateUser(req,function(err,result)
{
console.log(err);
console.log(result);
});
}
let addressId = (!req.address_id || req.address_id == null || req.address_id == '')
? -1 : req.address_id;
console.log(addressId);
async.auto({
serviceability : function (cb)
{
searchServiceArea(req,function(err,result)
{
if(err)
{
resolve(null, {'errorMessage':'Address selected not serviceble'}, 203, 'error');
}
else
{
if(!result.hub_id)
{
resolve(null, {'errorMessage':'Address selected not serviceble'}, 203, 'error');
}
if(addressId == -1)
{
let s=mysql.write('customer_address').insert({customer_key: customerKey,line1:line1,line2:line2,lat: lat,lng: lng,city: city,state: state,pincode: pincode,contact: contact,landmark : landmark,updated_at:moment().format("YYYY-MM-DD HH:mm:ss"),created_at:moment().format("YYYY-MM-DD HH:mm:ss")}).then(function(res)
{
if(res.length > 0)
{
cb(null,{address_id:res[0],customer_key: customerKey,line1:line1,line2:line2,lat: lat,lng: lng,city: city,state: state,pincode: pincode,contact: contact,landmark : landmark,updated_at:moment().format("YYYY-MM-DD HH:mm:ss"),created_at:moment().format("YYYY-MM-DD HH:mm:ss"),'hub_id':result.hub_id})
}
else
{
cb(true,{'errorMessage':'Unable to add address try again'})
}
});
}
else
{
let s=mysql.write('customer_address').update({line1:line1,line2:line2,lat: lat,lng: lng,city: city,state: state,pincode: pincode,contact: contact,landmark : landmark,updated_at:moment().format("YYYY-MM-DD HH:mm:ss")}).where({customer_key:customerKey, address_id:addressId}).then(function(res)
{
console.log(res)
if(res == 1)
{
cb(null,{address_id:addressId,customer_key: customerKey,line1:line1,line2:line2,lat: lat,lng: lng,city: city,state: state,pincode: pincode,contact: contact,landmark : landmark,updated_at:moment().format("YYYY-MM-DD HH:mm:ss"),created_at:moment().format("YYYY-MM-DD HH:mm:ss"),'hub_id':result.hub_id})
}
else
{
cb(true,{'errorMessage':'Unable to update address try again'})
}
},
},
);
}
So while inserting the address I'm identifying sql injection. I checked everywhere the possible solutions i was not able to solve it. Please do check the sql query also which i have mentioned.
How to solve this?
That would be a lot of help. Thanks in advance

I'd just use a standard library that already provides sanitization, like node-mysql.
https://github.com/mysqljs/mysql#escaping-query-values
const mysql = require('mysql');
const connection = mysql.createConnection({
host : 'example.org',
user : 'bob',
password : 'secret'
});
const post = {title: 'Hello MySQL', 'content': '...'};
connection.query(
'insert into posts (title, content, updated_at, created_at) values (?, ?, ?, ?);',
[
connection.escape(post.title),
connection.escape(post.content),
connection.escape(new Date()),
connection.escape(new Date())
]
).then((err, res, fields) => {
//do stuff
})

Related

How do I resolve a callback error with 'callback' is an instance of Object)?

TypeError: callback is not a function. (In 'callback(data)',
'callback' is an instance of Object)
The code here works just fine when I write it like this:
const onSelectFilterDone = (filter) => {
setFilter(filter);
setFilterModalVisible(false);
unsubscribe.current = listingsAPI.subscribeListings(
{ categoryId: category.id },
// { categoryId2: category2.id },
favorites,
onListingsUpdate,
);
};
When i uncomment that other line, it breaks and gives me this error.
const onSelectFilterDone = (filter) => {
setFilter(filter);
setFilterModalVisible(false);
unsubscribe.current = listingsAPI.subscribeListings(
{ categoryId: category.id },
{ categoryId2: category2.id },
favorites,
onListingsUpdate,
);
};
Here is the relevant snippet from listingsAPI (below) if it helps but this code works fine when there is only one object. Is there a specific way to make this work with two objects like above?
if (categoryId) {
return (
listingsRef
.where('categoryID', '==', categoryId)
.where('isApproved', '==', isApproved)
.onSnapshot((querySnapshot) => {
const data = [];
querySnapshot.forEach((doc) => {
const listing = doc.data();
if (favorites && favorites[doc.id] === true) {
listing.saved = true;
}
data.push({ ...listing, id: doc.id });
});
callback(data);
})
);
}
if (categoryId2) {
return (
listingsRef
.where('categoryID2', '==', categoryId2)
.where('isApproved', '==', isApproved)
.onSnapshot((querySnapshot) => {
const data = [];
querySnapshot.forEach((doc) => {
const listing = doc.data();
if (favorites && favorites[doc.id] === true) {
listing.saved = true;
}
data.push({ ...listing, id: doc.id });
});
callback(data);
})
);
}
You can combine your queries via this way if you want to have it optional:
let query = listingsRef.where('isApproved', '==', isApproved)
if (categoryId) {
query = query.where('categoryID', '==', categoryId)
}
if (categoryId2) {
query = query.where('categoryID2', '==', categoryId2)
}
query.onSnapshot...

vscode extension completion: how to replace the original text?

const scarlingProvider = vscode.languages.registerCompletionItemProvider(
'javascript',
{
provideCompletionItems(document, position, token, context) {
const linePrefix = document.lineAt(position).text.substr(0, position.character);
if (!hasChinese(linePrefix)) {
return undefined;
}
const reminds = starling.match(linePrefix)
console.log('reminds: ', reminds);
return [reminds].map(val => {
try {
const item = new vscode.CompletionItem(val, vscode.CompletionItemKind.Method)
item.insertText = `$t('${val}', '${linePrefix.trim()}')`
return item
} catch(err) {
console.log('err: ', err);
}
})
}
},
' '
As above, it's a snippet of a completion extension. I want the selected text to replace the original text instead of inserting that after the original text. What should I do?
You have to specify a range with your completion item. The model can give you the position of the original text for which the provider has been invoked:
const scarlingProvider = vscode.languages.registerCompletionItemProvider(
'javascript',
{
provideCompletionItems(document, position, token, context) {
const linePrefix = document.lineAt(position).text.substr(0, position.character);
if (!hasChinese(linePrefix)) {
return undefined;
}
const info = model.getWordUntilPosition(position);
const range = {
startLineNumber: position.lineNumber,
startColumn: info.startColumn - 1,
endLineNumber: position.lineNumber,
endColumn: info.endColumn,
};
const reminds = starling.match(linePrefix)
console.log('reminds: ', reminds);
return [reminds].map(val => {
try {
return {
label: "<a label>",
kind: CompletionItemKind.Method,
range,
insertText: `$t('${val}', '${linePrefix.trim()}')`,
detail: "<a description>",
}
} catch(err) {
console.log('err: ', err);
}
})
}
},
' '

React Native SectionList (title, data) - Search in the data field

I am trying to build Search function in SectionList. I have search inside the 'data' (second field) and not inside 'title' but I am not able to make it work.
My Data is about the Flat / resident details of an Apartment -
sectiondata =
[{"title":"GROUND FLOOR",
"data":[
{"id":"48","res_type":"owner","user_name":"Ashwani","flat_id":"1","flat_name":"001","floor_no":"GROUND FLOOR","floor_int":"0","signal_player_id":"aa","user_phone":"98855550"},
{"id":"49","res_type":"owner","user_name":"Rahul","flat_id":"2","flat_name":"002","floor_no":"GROUND FLOOR","floor_int":"0","signal_player_id":"aa","user_phone":"999999"}
]
}]
I am trying something like this but it is not working.
searchFilterFunction = (text) => {
let search = text.toLowerCase();
this.setState({
check: this.state.sectiondata.filter(
obj => obj.data['flat_name'].toLowerCase().includes(search))
});
}
How to filter data base on name? Please assist here.
Thanks.
You can try to search like this:
onChangeText(text) {
if (text.trim().length > 0) {
var temp = []
sectiondata.map((item) => {
var dataItem = {};
var brandData = [];
item.data.map((searchItem) => {
let flatName = searchItem.flat_name
if (flatName.match(text)) {
brandData.push(searchItem);
}
})
if (brandData.length > 0) {
} else {
return null;
}
dataItem.brandData = brandData;
temp.push(dataItem);
this.setState({
sectiondata: temp
})
})
} else {
this.setState({
sectiondata: this.state.tempData
})
}
}
searchFilterFunction(text) {
if( text == undefined || text == '') {
this.setState({
sectiondata: this.arrayholder
})
return;
}
if (text.trim().length > 0) {
var temp = []
this.state.sectiondata.map((item) => {
var dataItem = {};
var title = item.title;
var brandData = [];
item.data.map((searchItem) => {
let flatName = searchItem.flat_name
if (flatName.match(text)) {
brandData.push(searchItem);
}
})
if (brandData.length > 0) {
} else {
return null;
}
dataItem.title = title;
dataItem.data = brandData;
temp.push(dataItem);
this.setState({
sectiondata: temp
})
})

I am getting this error ,"value for message cannot be cast from double to string"

I am getting this error when I am trying pass object to axios method "value for message cannot be cast from double to string". Does any one have Idea about this.
I have added my two functions.
addNotes = (formData) => {
let noteText = ''
Object.keys(formData).map((item) => {
noteText += formData[item] !== undefined ? `${formData[item]} \n` : ``
})
let localLocation = `${this.state.localAddress.locality}, ${this.state.localAddress.subLocality}`
let { userMetaData, graphListlimit, graphListoffset, imdCode } = this.state
let obj = {
'edEmployeeCode': userMetaData.ed_employee_code,
'edName': userMetaData.ed_name,
'edRoleCode': userMetaData.ed_role_code,
'imdCode': imdCode,
'imdSegment': null,
'bnNoteText': noteText,
'location': localLocation,
'meetingType': this.state.meetingType
}
this.props.onAddNotesAction(obj)
}
export const addNotesAction = (obj) => {
let params = {
ed_employee_code: obj.empCode,
ed_role_code: obj.empRoleCode,
ed_channel: obj.empChannel,
ed_name: obj.edName,
imd_code: obj.imdCode,
imd_segment: null,
bn_note_text: obj.bnNoteText,
location: obj.location,
meeting_type: obj.meetingType
}
return dispatch => {
axios.defaults.headers.common['Authorization'] = obj.token;
axios.post(`${Config.apiRootPath}/meetings/addbranchnote`,
params,
).then(response => {
dispatch(addNotesSuccess(response));
}).catch(err => {
dispatch(addNotesFailure(err.response));
});
};
};

How to unit test API calls with axios() in react-native with Jest

I am developing Sample Application in React-native . I used Jest to use unit testing, i don't have an idea about Jest Api call
I want to need without using Promises:
Here this is my Code:
this is My Function Code:
/**
* #description Action to call nilpick service ,on success increment route as well as mark the location as fulfilled
*/
function nilPick() {
return async (dispatch, getState) => {
const currentState = getState();
const { user, picking } = currentState;
const { currentRouteIndex, pickRoute } = getState().picking.pickRouteInfo;
const { workId } = picking.pickWorkInfo;
const nilPickItem = pickRoute[currentRouteIndex];
const currentItem = getCurrentItem(currentState);
const currentTime = dateFunctions.getCurrentUTC();
const nilpickedItem = [
{
orderId: nilPickItem.fulfillOrdNbr,
lineNbr: nilPickItem.ordLine,
pickUpcNbr: nilPickItem.upc,
pickDisplayTs: currentTime,
pickUom: currentItem.workDetail.uom,
pickedLoc: nilPickItem.location,
locationType: nilPickItem.locType,
locId: nilPickItem.locId,
pickByType: currentItem.workDetail.pickByType,
exceptionPick: false,
gtinPrefRankNbr: 0,
pickUpcTypeCd: 5100
}
];
const { status, statusText } = await pickingService.nilPick(nilpickedItem, user, workId);
if (status === 200 || statusText === 'Created') {
console.info('Item nilpicked');
if (currentRouteIndex < pickRoute.length) {
dispatch(incrementRoute());
} else {
Alert.alert(
'Nilpick Complete',
[
{
text: 'OK',
onPress: () => {
dispatch(endPicking());
}
}
],
{ cancelable: false }
);
console.log('End of pickwalk');
return;
}
} else {
console.info('error in nilpicking item ');
}
};
}
This is my code above method to Converting Like this below sample test Case:
This is sample Test i want to call Api How to implement in Jest
it('Test For nillPic', () => {
const initialState = {
picking: {
pickRouteInfo: {
"fulfillOrdNbr": pickRouteInfo.fulfillOrdNbr,
"orderLine": '1',
"upc": '4155405089',
"location": 'A-1-1',
"availableLocsToPick": '2',
'suggSubPendingPicks?': 'N',
'manualSubPendingPicks?': 'N',
"lineFullfilled": 'false',
"currentRouteIndex": 1,
"pickRoute": ['r1', 'r2', 'r3']
}
}
};
// console.log("state data...", initialState);
const store = mockStore(initialState);
store.dispatch(actions.pickRouteActions.nilPickSuccess());
const expectedAction = [{ type: 'INCREMENT_ROUTE' }];
const localActions = store.getActions();
expect(localActions).toEqual(expectedAction);
});
Finally This is my code Please . Thanks in Advance