CloudSearch javaScript API help to configure fq and query - javascript

I know I am doing wrong somewhere in setting parameters. Basically, I want to convert the below link to script.
Click here to check the query
aws.config.update({
region: 'us-east-1'
});
AWS.config.apiVersions = {
cloudsearchdomain: '2013-01-01',
// other service API versions
};
var csd = new AWS.CloudSearchDomain({
endpoint: 'search-vegme-user-7l3rylms73566frh4hwxblekn4.us-east-1.cloudsearch.amazonaws.com'
});
var params = {
query: 'nikhil',
/* required */
expr: 'distance=haversin(35.621966,-120.686706,latlong.latitude,latlong.longitude)&sort=distance%20asc&return=distance,displayname,profileimageurl',
filterQuery: 'latlong:['
44.37094377949903,
-78.40296337445523 ','
42.92362822050097,
-80.40316462554478 ']',
partial: true,
queryOptions: 'STRING_VALUE',
queryParser: 'simple,
return :'distance,id,fname',
sort: 'asc',
};
csd.search(params, function(err, data) {
if (err) {
console.log(err, err.stack); // an error occurred
} else {
console.log(data); // successful response
}
});

Instead of using the above method to get the nearby locations
I am using
the below link with HTTP module in my nodeJS
http://search-vegme-user-7l3rylms73566frh4hwxblekn4.us-east-1.cloudsearch.amazonaws.com/2013-01-01/search?q=nikhil&expr.distance=haversin(35.621966,-120.686706,latlong.latitude,latlong.longitude)&sort=distance%20asc&return=distance,displayname,profileimageurl
It will return all the top near locations for a given point
latlong is the valiable of type latlon

You need to add params something like this
var params = {
'q': queryString,
'cursor': "initial",
'size': 5,
'expr.distance': "(haversin(35.621966,-120.686706,latlong.latitude,latlong.longitude))",
'sort': "distance asc",
'q.parser': "structured",
'return': "dietsinceyear,fbprofileid,reasonforveg,verified,since,displayname,locale,link,tagline,email,followingcount,agerangemin,shortdescription,vegstory,lastupdated,timezone,diet,followercount,fbupdated_time,coverimageurl,lname,id,gender,profileimageurl,categoryids,fname,distance"
}

Related

Parse Cloud Code - Add To Array

Tried loads of different variations with my cloud code and I can't get it to work. Basically I've got a push notification function, and in this function I want to add an object to a PFUser's array, but you can't use a master key in Xcode so here's what I have:
Parse.Cloud.define("iOSPush", function (request, response) {
console.log("Inside iOSPush");
var data = request.params.data;
var not_class = request.params.not_class;
var not_objectid = request.params.not_objectid;
var not_date = request.params.not_date;
var userid = request.params.userid;
var recipientUser = new Parse.Query(Parse.User);
recipientUser.equalTo("objectId", userid);
// set installation query:
var pushQuery = new Parse.Query(Parse.Installation);
pushQuery.equalTo('deviceType', 'ios');
pushQuery.matchesQuery('user', recipientUser);
pushQuery.find({ useMasterKey: true }).then(function(object) {
response.success(object);
console.log("pushQuery got " + object.length);
}, function(error) {
response.error(error);
console.error("pushQuery find failed. error = " + error.message);
});
// send push notification query:
Parse.Push.send({
where: pushQuery,
data: data
}, { useMasterKey: true }).then(function() {
console.log("### push sent!");
// create notification:
var notification = {
"title": not_class,
"body": request.params.data.alert,
"class": not_class,
"objectId": not_objectid,
"date": not_date
};
// get notifications:
var tmp_notifications = recipientUser.get("notifications");
// add notification:
tmp_notifications.push(notification);
// update with notifications:
recipientUser.set("notifications", tmp_notifications);
recipientUser.save();
}, function(error) {
console.error("### push error" + error.message);
});
response.success('success. end of iospush');
});
The Xcode cloud function I have provides the correct information, the function gets to the end.. just the function is not setting the notifications for some reason
I ended up figuring out the answer to this post myself. The reason this didn't work is because I needed to first fetch the user object in a separate query, then save it using the master key. I also found out that there's a function for appending data onto an existing array without having to create another one (parseObject.add()):
var userQ = new Parse.Query(Parse.User);
userQ.get(userid, {
success: function(theuser) {
console.log("### got userrrrrrrrrr!");
theuser.add("notifications", n_object);
theuser.save(null, {useMasterKey:true});
},
error: function(object, error) {
// The object was not retrieved successfully.
// error is a Parse.Error with an error code and message.
}
});
This set of code was executed just before:
response.success('success. end of iospush');

How to get the revision history of user from Rally using Node js scripting

My requirement is to get the exact date/time when a user gets disabled.
To achieve this, I need to query for the line 'user set to INACTIVE' in the Revision History to find the date the user was switched from enabled to disabled.
How can I get the revision history using node js ?
I tried below code, but its not working as Rally support team mentioned that its older code and i have to try with v2.0.
Can somebody help me to achieve my requirement ?
var revisions = story.RevisionHistory.Revisions;
revisions.sort(byRevisionNumber);
var story_was_blocked = false;
// it doesn't matter how many revs have been in BLOCKED state, presence of one is sufficient
for (var rix = 0; rix < revisions.length && story_was_blocked === false; rix++) {
var rev = revisions[rix];
if (rev.Description.indexOf("BLOCKED changed from ") >= 0) {
story_was_blocked = true;
}
}
Here's a brief example of how this might be accomplished. Note that this just shows how to fetch all revisions in the collection on a User, you'd need to iterate through them and match the Description field on 'Disabled':
var rally = require('rally'),
queryUtils = rally.util.query,
rallyApi = rally({
// Example key, not valid
apiKey: '_UkMasZfjPZfquDIMExfEKnAboQUlyT2SP4UppMHir',
server: 'https://rally1.rallydev.com',
requestOptions: {
headers: {
'X-RallyIntegrationName': 'Query User Revisions',
'X-RallyIntegrationVendor': 'Stackoverflow user4211235',
'X-RallyIntegrationVersion': '1.0'
}
}
});
function onError(error) {
console.log('Failure!', error);
}
function queryUserRevisions(result) {
var revisions = result.Revisions;
rallyApi.query({
ref: revisions,
start: 1,
limit: Infinity,
order: 'RevisionNumber',
fetch: ['RevisionNumber','Description','CreationDate']
}, function(error, result) {
if(error) {
onError(error);
} else {
console.log('Success querying User Revisions...');
console.log('Summary of revisions on User:')
console.log(result);
}
});
}
function queryUserRevisionHistory(result) {
rallyApi.query({
ref: result.Results[0].RevisionHistory,
start: 1,
limit: Infinity,
fetch: ['Revisions','RevisionNumber','Description','CreationDate']
}, function(error, result) {
if(error) {
onError(error);
} else {
console.log('Success querying User Revision History. Querying Revisions...');
queryUserRevisions(result);
}
});
}
function queryUser(callback) {
rallyApi.query({
type: 'user',
start: 1,
pageSize: 2,
limit: 10,
order: 'CreationDate',
fetch: ['UserName', 'EmailAddress', 'RevisionHistory'],
query: queryUtils.where('UserName', '=', "user#company.com")
}, function(error, result) {
if(error) {
onError(error);
} else {
console.log('Success querying User. Querying Revision History...');
callback(result);
}
});
}
queryUser(queryUserRevisionHistory);

InvalidInput: Invalid request on AWS Route 53

I am trying to set resource records in AWS route 53 via the SDK and I am getting an Invalid Request error(InvalidInput). Can you double check my params to make sure that I have them set correctly?
function testw () {
var params = {
ChangeBatch: {
Changes: [
{
Action: 'CREATE',
ResourceRecordSet: {
Name: 'example.com',
Type: 'A',
AliasTarget: {
DNSName: 's3-website-us-east-1.amazonaws.com',
EvaluateTargetHealth: false,
HostedZoneId: 'Z1YU6G6WEXAMP'
},
}
},
],
Comment: 'This is a test and it should be working.'
},
HostedZoneId: 'Z1YU6G6WEXAMP'
};
route53.changeResourceRecordSets(params, function (err, data) {
if (err) console.log(err, err.stack); // an error occurred
else console.log(data); // successful response
});
}
Thanks for any help!!
Can you try removing the TTL? When you use aliases, you do not specify the TTL as Route 53 will use the target's TTL. Also, per the documentation, your alias target zone id should be Z3AQBSTGFYJSTF.

Inserting an event with the nodejs google calendar API returns 400: "Missing end time"

I am trying to insert events via the Google Calendar API with a service account. The goal is to have one calendar that all users view: a server-to-server setup.
As of now, I can properly call the calendar API and list the events on said calendar:
var moment = require("moment"),
googleapis = require("googleapis"),
googleCal = googleapis.calendar("v3");
serviceEmail = "********#developer.gserviceaccount.com",
serviceKeyFile = "./key.pem";
var authClient = new googleapis.auth.JWT(
serviceEmail,
serviceKeyFile,
null,
["https://www.googleapis.com/auth/calendar"]
);
authClient.authorize(function (err, tokens) {
if (err) {
console.log(err);
} else {
googleCal.events.list({
auth: authClient,
calendarId: "********#gmail.com",
fields: {
items: ["end","start","summary"]
}
}, function (err, CL) {
if (err) {
console.log(err);
} else {
console.log(CL);
}
});
}
})
This properly returns a JSON object that lists all the different objects on the calendar. However, when I try to insert an event directly below the googleCal.events.list call:
googleCal.events.insert({
auth: authClient,
calendarId: "primary",
resources: {
start: {
dateTime: "2014-07-23T18:25:00.000-07:00",
timeZone: "America/New_York"
},
end: {
dateTime: "2014-07-23T19:25:00.000-07:00",
timeZone: "America/New_York"
},
summary: "winning # life",
description: "winning # life description"
}
}, function (err, something) {
if (err) {
console.log(err);
} else {
console.log(something);
// do something else
}
})
The following 400 is returned:
{ errors:
[ { domain: 'global',
reason: 'required',
message: 'Missing end time.' } ],
code: 400,
message: 'Missing end time.'}
How do I go about fixing this? The authorization is clearly working—I know because I've used up my unauthorized requests for the day and because I can list all the events. I have also specified an endTime. Why is the google calendar API telling me that I haven't?
I think the problem is in the keyword "resources" on line 4 of your second snippet. Based on the documentation, it should be a "resource":
* #param {object} params.resource - Request body data

Web FTP Portal Logins

I have a web ftp portal that was created a few years ago by a developer that is no longer around. The code for the website is written in Node.js. Inside of app.js is the following code:
var validUsers = [{
name:'x',
user:'907c78ef73998eafc2680e5fdd4798a8eef0881a',
pass:'95489cf3039eb2f5938e3daa954d04276bbf90e7',
dir:''
},{
name:'y',
user:'b26e5ebda152e81099ec78be2f9c191ee25e1cd6',
pass:'e3725873ae302e3f12eb97b02feb7457de9706c2',
dir:'y'
},{
name:'y2',
user:'3182b54d9f4d08641b5a9a0fb33f74df5d76b222',
pass:'916b2e1941c9e23610f8bd3462cdb19f55b5c631',
dir:'y2'
},{
name:'y3',
user:'38aa53de31c04bcfae9163cc23b7963ed9cf90f7',
pass:'7a98cf84c2c61a30f6c4e3984c0cad2eb29f5d6f',
dir:'y3'
},{
name:'y4',
user:'51e822c50cc62cdbdb850a439ea75b6d45ac487b',
pass:'da6a77293ddcdc7047dd461a94c88c8377753265',
dir:'y4'
},{
name:'y5',
user:'14ad0aca26e00f615990946181ee3405c6ede0f1',
pass:'4eb4e0e1ea0f04422b5bc6031ee37c8dc971236d',
dir:'y5'
},{
name:'y6',
user:'4ec9bdb28c5da0f9813e9eed55a0f1dc6217a305',
pass:'e72bd0bbd37423bb0c9b9edfb9ce94446161c511',
dir:'y6'
},{
name:'y7',
user:'f4603bd4ae9e4aa2a11d903d0b178b37a57b1bac',
pass:'8a6a67f235738c4b2e4f88d4608bdcf0bbc49f51',
dir:'y7'
},{
name:'Guest',
user:'35675e68f4b5af7b995d9205ad0fc43842f16450',
pass:'370bb444ef91a3999b1c36af97e166f18848e7b7',
dir:'Guest'
},{
name:'y8',
user:'d8f51fbf5e13e9f2637a8d5c4bd1ab251bd61c30',
pass:'1a047e6dd554ffdd67524916820a8fa23acd2c6e',
dir:'y8'
}];
The x and y1-8 are substitutions for the actual client names and corresponding directories. Example being the 'Guest' name and directory. My question is, the user and pass are hash values from crypto. Yet they result in specific usernames and passwords. If I wanted to reset a username or password, or add another. How would I figure out the corresponding hash value to add to the code based on the username/password strings I want to add.
Any input would be very helpful.
EDIT:
The rest of the FTP code:
app.get('/ftp/', function(req, res){
var pageName = 'File Transfer Portal';
var rNav = '',
sNav = '',
cNav = '',
imNav = '',
title = 'companyNameOmitted: '+pageName,
bodyClass = 'top ftp',
keywords = 'keywordsOmitted',
description = 'descriptionOmiited',
url = '/ftp/';
res.render('ftp', {
title: title,
bodyClass: bodyClass,
keywords: keywords,
description: description,
url: siteRoot+url,
pageEmail: 'mailto:?subject='+escape(title)+'&body='+escape(description)+'%0A'+siteRoot+url,
eUrl:escape(siteRoot+url),
eTitle:escape(title),
eDescription:escape(description),
rNav:rNav,
sNav:sNav,
cNav:cNav,
imNav:imNav});
//console.log(uniqId()+':'+pageName);
});
app.post('/ftp/upload', function(req, res){
//console.log(req.files);
var SID = req.cookies.SID;
var sessionUser = (users[SID]) ? users[SID] : false;
if (!!sessionUser){
_.each(req.files,function (file) {
console.log(new Date(curTime()).toGMTString()+' | Recieved '+file.name+' ('+file.size+' bytes) from '+sessionUser.name);
var newPath = __dirname + '/complete/'+_.where(validUsers,{user:sessionUser.user})[0].dir+'/'+file.name;
fs.rename(file.path,newPath,function(err) {
if (err) throw err;
else {
res.redirect('back');
if (sessionUser.name != 'adminOmitted') {
var htmlString = '<b>'+sessionUser.name+'</b> has uploaded a file <b>'+file.name+'</b>.<br /><br />View it on the File Transfer Portal.';
var transport = nodemailer.createTransport("SMTP",{
host: "hostname.com", // hostname
secureConnection: true, // use SSL
port: 465, // port for secure SMTP
auth: {
user: "user#host.com",
pass: "pass"
}
});
transport.sendMail({
sender:'sender#host.com',
to:'receiver#host.com',
subject:'File Upload: '+sessionUser.name+' uploaded '+file.name,
html: htmlString
},function(err) {
if (err) console.log(err);
else console.log('Notification Sent: S&A File Upload: '+sessionUser.name+' uploaded '+file.name);
});
}
}
});
And the login code...
app.get('/ftp/d/:hash/:filename', function(req, res){
var SID = req.cookies.SID;
var ip = req.ip;
//console.log(ip);
var sessionUser = (users[SID]) ? ((users[SID].md5==req.params.hash)&&(users[SID].ip==ip)) ? users[SID] : false : false;
if (sessionUser) {
var realpath = __dirname +'/complete/'+_.where(validUsers,{user:sessionUser.user})[0].dir+'/'+req.params.filename.replace('>','/');
console.log(new Date(curTime()).toGMTString()+' | Sending '+realpath.substr(realpath.indexOf('complete')+9)+' to '+sessionUser.name);
res.download(realpath,realpath.substr(realpath.lastIndexOf('/')+1),function(err){
if (err) {
res.redirect(302,'/ftp/');
throw (err);
}
});
} else {
console.log(new Date(curTime()).toGMTString()+' | Download request failed authorization for '+req.params.filename);
console.log(new Date(curTime()).toGMTString()+' | Hash: '+req.params.hash);
console.log(new Date(curTime()).toGMTString()+' | SID: '+req.cookies.SID);
res.redirect(302,'/ftp/');
}
});
sio.sockets.on('connection', function (socket) {
var SID = socket.handshake.SID;
if (!users[SID]) register(SID,socket.handshake.address.address);
//console.log(users);
socket.on('login',function(data) {
var thisUser = _.where(validUsers,{user:data.u,pass:data.p})[0];
if (_.isEmpty(thisUser)) {
if (!!users[SID].ip) {
console.log(new Date(curTime()).toGMTString()+' | '+users[SID].ip+' has failed logging in.');
console.log(new Date(curTime()).toGMTString()+' | '+'U:'+data.u);
console.log(new Date(curTime()).toGMTString()+' | '+'P:'+data.p);
}
socket.emit('login',{complete:false,name:false});
} else {
console.log(new Date(curTime()).toGMTString()+' | '+thisUser.name+' has logged in.');
users[SID].name = thisUser.name;
users[SID].user = thisUser.user;
socket.emit('login',{complete:true,name:thisUser.name});
}
});
And the disconnect function, the only code between the login and the disconnect functions are a move file and a delete file function which I doubt are of any use.
//console.log(users);
socket.on('disconnect',function() {
setTimeout(function() {
if (!!users[SID]) {
if (curTime()-users[SID].lastTap>30000)
unregister(SID);
else console.log('Not removing; connection still active. ('+users[SID].name+')');
} else (unregister(SID));
},30000);
});
});
and finally, the crypto functions:
function getMD5(string) {
return crypto.
createHash('md5').
update(string).
digest("hex");
}
function getSHA1(string) {
return crypto.
createHash('sha1').
update(string).
digest("hex");
}
I know the formatting isn't perfect, I've tried to keep it as neat as possible, I think that's all of the relevant functions. I doubt the .jade file for the FTP Portal would be of any use.
You can't.
The usernames and passwords have been put through an asymmetric encryption (ie MD5). This was likely done to protect the user's personal information if the server is hacked.
You're still missing the part of the code that handles the authentication and sets the session cookie.
If you can find the code that handles the auth and you know the username beforehand you could re-hash it to cross-reference the username to the entries list.
Otherwise, your only option is to crack the usernames/passwords which can be difficult/impossible depending on their complexity.
Good luck...

Categories

Resources