Algolia generate Invalid Secured API-Keys - javascript

So I'm trying to generate some secured API-Keys but it seems that they aren't generated right, I've followed the API docs without any luck.
This is what I'm doing
var algoliasearch = require('algoliasearch');
var admin_client = algoliasearch('APP', 'ADMIN_KEY');
var search_client = algoliasearch('APP', 'ONLY_SEARCH_KEY');
var admin_index = admin_client.initIndex('INDEX');
var search_index = search_client.initIndex('INDEX');
admin_index.search('dav', (err, content) => { console.log(err, content) });
//------------------CONSOLE-------------------------------
null { hits:
[ { firstname: 'David',
lastname: 'De Anda',
_tags: [Object],
objectID: '2',
_highlightResult: [Object] } ],
nbHits: 1,
page: 0,
nbPages: 1,
hitsPerPage: 20,
processingTimeMS: 1,
query: 'dav',
params: 'query=dav' }
//-------------------------------------------------
search_index.search('dav', (err, content) => { console.log(err, content) });
//------------------CONSOLE-------------------------------
null { hits:
[ { firstname: 'David',
lastname: 'De Anda',
_tags: [Object],
objectID: '2',
_highlightResult: [Object] } ],
nbHits: 1,
page: 0,
nbPages: 1,
hitsPerPage: 20,
processingTimeMS: 1,
query: 'dav',
params: 'query=dav' }
//-------------------------------------------------
Everything seems to work until now
But now I want to generate some Secured API-Keys
var valid_until = Math.floor(Date.now() / 1000) + 3600
var from_admin_api_key = admin_client.generateSecuredApiKey('from_admin', {validUntil: valid_until});
var from_search_api_key = search_client.generateSecuredApiKey('from_search', {validUntil: valid_until});
var sub_admin_client = algoliasearch('APP', from_admin_api_key);
var sub_search_client = algoliasearch('APP', from_search_api_key);
var sub_admin_index = sub_admin_client.initIndex('INDEX');
var sub_search_index = sub_search_client.initIndex('INDEX');
sub_admin_index.search('dav', (err, content) => { console.log(err, content) });
//------------------CONSOLE-------------------------------
{ Error
at success (/app/node_modules/algoliasearch/src/AlgoliaSearchCore.js:334:32)
at process._tickDomainCallback (internal/process/next_tick.js:129:7)
name: 'AlgoliaSearchError',
message: 'Invalid Application-ID or API key',
debugData:
[ { currentHost: 'https://ge24e6css9-dsn.algolia.net',
headers: [Object],
content: '{"params":"query=dav"}',
contentLength: 22,
method: 'POST',
timeouts: [Object],
url: '/1/indexes/INDEX/query',
startTime: 2017-01-13T17:46:42.519Z,
endTime: 2017-01-13T17:46:44.038Z,
duration: 1519,
statusCode: 403 } ],
statusCode: 403 } undefined
//-------------------------------------------------
sub_search_index.search('dav', (err, content) => { console.log(err, content) });
//------------------CONSOLE-------------------------------
{ Error
at success (/app/node_modules/algoliasearch/src/AlgoliaSearchCore.js:334:32)
at process._tickDomainCallback (internal/process/next_tick.js:129:7)
name: 'AlgoliaSearchError',
message: 'Invalid Application-ID or API key',
debugData:
[ { currentHost: 'https://ge24e6css9-dsn.algolia.net',
headers: [Object],
content: '{"params":"query=dav"}',
contentLength: 22,
method: 'POST',
timeouts: [Object],
url: '/1/indexes/INDEX/query',
startTime: 2017-01-13T17:46:42.519Z,
endTime: 2017-01-13T17:46:44.038Z,
duration: 1519,
statusCode: 403 } ],
statusCode: 403 } undefined
//-------------------------------------------------

I misunderstood the generateSecuredApiKey first parameter that actually was the origin API Key.
So the right code will be
var from_admin_api_key = admin_client.generateSecuredApiKey('ADMIN_KEY', {validUntil: valid_until});
var from_search_api_key = search_client.generateSecuredApiKey('ONLY_SEARCH_KEY', {validUntil: valid_until});
And of course the generated key form the ADMIN_KEY won't work.

Related

How to reply to someone's tweet using node.js twit?

I'm trying to make a bot that responds to my friend's tweets with an image every time they tweet. Everything works fine, but I can't get it to respond to the original tweet, only replies. Is there any way to do this?
function tweetEvent(tweetMsg) {
var replyto = tweetMsg.in_reply_to_screen_name;
var from = tweetMsg.user.screen_name;
var id = tweetMsg.id_str;
if(from === "---"){
var b64content = fs.readFileSync('media/img.png', {
encoding: 'base64'
})
T.post('media/upload', {
media_data: b64content
}, uploaded);
function uploaded(err, data, response) {
var mediaIdStr = data.media_id_string;
var params = {
status,
in_reply_to_status_id: id,
media_ids: [mediaIdStr]
}
//! Post tweet
T.post('statuses/update', params, tweeted);
};
function tweeted(err, reply) {
if(err) {
console.log(err);
console.log();
console.log("Error.");
} else {
console.log("tweeted");
}
}
}
}
I want it to reply to the original tweet, the only way it's worked is by using:
if(replyto === "---"){
}
But that doesn't do what I want it to do.
I was able to do it with if (tweet.in_reply_to_screen_name === null) tweetEvent(tweet);
const tweets = [
{
created_at: "Wed Feb 10 03:50:17 +0000 2021",
id: 1359348938248183800,
id_str: "1359348938248183809",
text: "reply test 1290hHhbjikl",
truncated: false,
entities: [Object],
metadata: [Object],
source:
'Twitter Web App',
in_reply_to_status_id: 1359339654080790500,
in_reply_to_status_id_str: "1359339654080790530",
in_reply_to_user_id: 1167232572067369000,
in_reply_to_user_id_str: "1167232572067368960",
in_reply_to_screen_name: "OpenDreamPhone",
user: [Object],
geo: null,
coordinates: null,
place: null,
contributors: null,
is_quote_status: false,
retweet_count: 0,
favorite_count: 0,
favorited: false,
retweeted: false,
lang: "in",
},
{
created_at: "Wed Feb 10 03:13:23 +0000 2021",
id: 1359339654080790500,
id_str: "1359339654080790530",
text: "this is a test. 1290hHhbjikl",
truncated: false,
entities: [Object],
metadata: [Object],
source:
'Twitter Web App',
in_reply_to_status_id: null,
in_reply_to_status_id_str: null,
in_reply_to_user_id: null,
in_reply_to_user_id_str: null,
in_reply_to_screen_name: null,
user: [Object],
geo: null,
coordinates: null,
place: null,
contributors: null,
is_quote_status: false,
retweet_count: 0,
favorite_count: 0,
favorited: false,
retweeted: false,
lang: "en",
},
];
const tweetEvent = (tweet) => {
var b64content = fs.readFileSync("twitt/img.png", {
encoding: "base64",
});
T.post(
"media/upload",
{
media_data: b64content,
},
uploaded
);
function uploaded(err, data, response) {
var mediaIdStr = data.media_id_string;
var params = {
status: "hi",
in_reply_to_status_id: tweet.id_str,
media_ids: [mediaIdStr],
};
//! Post tweet
T.post("statuses/update", params, tweeted);
}
function tweeted(err, reply) {
if (err) {
console.log(err);
console.log();
console.log("Error.");
} else {
console.log(reply);
console.log("tweeted");
}
}
};
tweets.forEach((tweet) => {
if (tweet.in_reply_to_screen_name === null) tweetEvent(tweet);
});

Express, Mongoose - .update() is returning null

When I am trying to update a document in my model, the .update() is returning null but the .find() method works fine.
module.exports.updateBio = function(req, res) {
var userID = req.params.id;
var objForUpdate = {};
if (!troolr.isEmptyString(req.body.profile_picture)) objForUpdate.profile_picture = req.body.profile_picture;
if (!troolr.isEmptyString(req.body.title)) objForUpdate.title = req.body.title;
if (!troolr.isEmptyString(req.body.intro)) objForUpdate.intro = req.body.intro;
if (!troolr.isEmptyString(req.body.summary)) objForUpdate.summary = req.body.summary;
if (!troolr.isEmptyString(req.body.skills)) objForUpdate.skills = req.body.skills;
if (!troolr.isEmptyString(req.body.facebook)) objForUpdate.social.facebook = req.body.facebook;
if (!troolr.isEmptyString(req.body.twitter)) objForUpdate.social.twitter = req.body.twitter;
if (!troolr.isEmptyString(req.body.linkedin)) objForUpdate.social.linkedin = req.body.linkedin;
if (!troolr.isEmptyString(req.body.website)) objForUpdate.social.website = req.body.website;
var conditions = { "_id": userID }
, setObj = { $set: objForUpdate }
, options = { multi: true };
//This throws error
// Error: { ok: 0, n: 0, nModified: 0 }
Profile.update(conditions, setObj, (err, page) =>{
if(err) throw err;
console.log(page);
});
// This works fine but it erases old values if they are empty
/* Profile.findById(userID, (error, user) => {
if(error) return res.status(500).json({ success: false, error: error });
user.bio = objForUpdate;
user.save(function(error) {
if(error) return res.status(500).json({ success: false, error: error });
return res.status(200).json({ success: true, message: "Bio successfully updated." });
});
}); */
};
// API Endpoint
http://localhost:3000/api/v1/profile/592c53b3bdf350ce004ad717/updatebio
// API Define
'use strict';
/**
* Routes for Profile Model
*
**/
var passport = require('passport');
var jwt = require('jwt-simple');
var settings = require("settings");
var profileCtrl = require(settings.PROJECT_DIR + 'routes/controllers/api/profile');
module.exports = function(app) {
app.get('/all', profileCtrl.getAll);
app.get('/:id', profileCtrl.getSingle);
app.put('/:id/updateurl', profileCtrl.updateURL);
app.put('/:id/updateaddress', profileCtrl.updateAddress);
app.put('/:id/updatebio', profileCtrl.updateBio);
}
// Model
var mongoose = require('mongoose');
// User Schema
var ProfileSchema = mongoose.Schema({
url : {
type: String,
unique: true,
},
fname: {
type: String,
required: true
},
lname: {
type: String,
required: true
},
email: {
type: String,
unique: true,
required: true
},
bio: {
profile_picture: {
type: String
},
title: {
type: String
},
intro: {
type: String
},
summary: {
type: String
},
skills: {
type: Object
},
social: {
linkedin: {
type: String
},
twitter: {
type: String
},
facebook: {
type: String
},
website: {
type: String
}
},
},
location: {
address: {
type: String
},
apt: {
type: String
},
city: {
type: String
},
state: {
type: String
},
zip_code: {
type: String
},
country: {
type: String
}
},
phone: {
type: Number
},
listings: {
type: Object
},
reviews: {
type: Object
},
verfied: {
type: Boolean,
default: false
},
// expires: {
// type: Date,
// expires: '1h',
// default: Date.now
// },
});
var Profile = module.exports = mongoose.model('Profile', ProfileSchema);
module.exports.getUserByEmail = function(email, callback){
var query = {'email': email};
Profile.findOne(query, callback);
}
module.exports.checkIfUrlExists = function(res, url, callback){
var query = {'url': url};
Profile.findOne(query, function(error, found) {
if(error) return res.status(500).json(error);
if(found) return res.status(500).json({success: false, message: "URL already exists" });
if(callback) callback();
});
}
// Document which I am trying to update
{
"_id": "592c53b3bdf350ce004ad717",
"url": "hyoh7ryb-",
"fname": "Foo",
"lname": "Bar",
"email": "foobar#gmail.com",
"__v": 0,
"verfied": false
}
Anything not defined in schema is not saved. That's what happening when you're missing bio key while preparing the objForUpdate to $set:
var objForUpdate = {};
if (!troolr.isEmptyString(req.body.profile_picture)) objForUpdate.profile_picture = req.body.profile_picture;
which should be
var objForUpdate = {
bio: {}
};
if (!troolr.isEmptyString(req.body.profile_picture)) objForUpdate.bio.profile_picture = req.body.profile_picture;
if (!troolr.isEmptyString(req.body.title)) objForUpdate.bio.title = req.body.title;
// and so on
Your save is working because of saving the object in the right keyuser.bio = objForUpdate;

Node.js - Counting the number of objects in MongoDB collection

I am new to Node.js and MongoDB and I am really struggling to wrap my head around callbacks. I have read a few articles but it is still quite confusing to me. In the code below, I am trying to return the count of orders that have some properties which I have expressed in the query in orderModel.count(query, next):
controllers/order.js:
var mongoose = require ('../config/db');
var orderModel = require('../models/order').model;
var User = require('./user');
var Error = require('../config/error');
createOrder: function (user, order, next) {
if (newOrder.totalPrice > user.credit && orderModel.
count({$and: [{user: order.user}, {active: true}, {$or: [{status: 0}, {status: 1}]}]},
function(err, count){
if(err)
console.log(err);
else
count; }) > 0)
return next({error: Error.InsufficientCredits});
}
I don't think I am correctly obtaining the variable count because when I tried printing out the result of the second condition in the if statement, I got this data printed out:
Query {
_mongooseOptions: {},
mongooseCollection:
NativeCollection {
collection: Collection { s: [Object] },
opts: { bufferCommands: true, capped: false },
name: 'orders',
collectionName: 'orders',
conn:
NativeConnection {
base: [Object],
collections: [Object],
models: [Object],
config: [Object],
replica: false,
hosts: null,
host: 'dsXXXXXX.mlab.com',
port: XXXXXX,
user: 'XXXX',
pass: 'XXXX',
name: 'X',
options: [Object],
otherDbs: [],
_readyState: 1,
_closeCalled: false,
_hasOpened: true,
_listening: false,
db: [Object],
_events: {},
_eventsCount: 0 },
queue: [],
buffer: false,
emitter:
EventEmitter {
domain: null,
_events: {},
_eventsCount: 0,
_maxListeners: undefined } },
....
You need to put your logic inside the Model.count() method callback function as:
var mongoose = require ('../config/db'),
orderModel = require('../models/order').model,
User = require('./user'),
Error = require('../config/error');
var createOrder = function (user, order, next) {
orderModel.count({
"user": order.user,
"active": true,
"status": { "$in": [0, 1] }
}, function(err, count) { //<-- put logic in this callback
if (err) {
console.log(err);
throw err;
} else if (newOrder.totalPrice > user.credit && count > 0) {
// logic for creating order here
} else {
return next({ "error": Error.InsufficientCredits });
}
})
}

Add element to existing JSON in javascript

Hi I have the following JSON named departments. When i do console.log(departments) i get this.
{ _id: 58089a9c86337d1894ae1834,
departmentName: 'Software Engineering',
clientId: '57ff553e94542e1c2fd41d26',
hodName: 'Mr Shekar Krishna',
noOfEmployees: 90,
hodId: 'djekjakejkjkjekajk3j33',
__v: 0 }
But when i try to assign a value like hodId to a variable like this.
var hodId=departments.hodId;
and then do console.log i get undefined.
Also i need to add this value "hodId" to t to another JSON "user" which is currently like this:
{ fullName: 'Rohit',
password: '123',
contactNum: '00000',
homeNum: '9998889999',
officeNum: '9998889999',
emailId: 'dv000d0v#yopmail.com',
employeeAddress: '10 ,Lakshmi Apartments, Sarai Kale Khan,New Delhi',
clientId: 'general',
clientName: 'Restaurant',
accessLevelId: 'sscaskoo31',
accessLevelName: 'basic',
departmentName: 'test',
departmentId: '58089a9c86337d1894ae1834',
employeeId: 'EMP1102',
employeeGrade: 'A',
employeeGradeId: '1221' }
Suggest what i am doing wrong?
Adding the code
var user=req.body;
// var hodId="";
if (req.body.clientId=="general") {
user.accessLevelName="basic";
}
if (!(req.body.departmentId==null || req.body.departmentId=="")) {
Departments.find({ '_id': req.body.departmentId },function(err, departments) {
// if there is an error retrieving, send the error. nothing after res.send(err) will execute
if (err) {
res.send(err);
}
console.log("department"+departments);
// user.hodId="test";
user.departmentName=departments.departmentName;
var newUser =new User(user);
newUser.save(function(err,obj) {
if (err) {
return res.json({success: false, msg: "User Name Already Exists"});
} else {
var token = jwt.encode(obj, config.secret);
res.json({success: true, token: 'JWT ' + token,msg: 'Successful created new user.',user:obj});
}
});
});
} else{
newUser.save(function(err,obj) {
if (err) {
return res.json({success: false, msg: "User Name Already Exists"});
} else {
var token = jwt.encode(obj, config.secret);
res.json({success: true, token: 'JWT ' + token,msg: 'Successful created new user.',user:obj});
}
The mongoose .find() method returns an Array, not an object.
The output of console.log(departmants) is, or at least should be:
[{ _id: 58089a9c86337d1894ae1834,
departmentName: 'Software Engineering',
clientId: '57ff553e94542e1c2fd41d26',
hodName: 'Mr Shekar Krishna',
noOfEmployees: 90,
hodId: 'djekjakejkjkjekajk3j33',
__v: 0 }]
Which means that to access what youre looking for you need to access the first object in the array first.
var hodId=departments[0].hodId;
Once you have that var you can then add it to another user
user.hodId = hodId;

mongoose findall return data from a different model

In users.js:
var mongoose = require('mongoose');
var User = mongoose.model('user', {
username: {
type: String,
required: true,
unique: true,
lowercase: true,
},
tasks: [{
type: mongoose.Schema.Types.ObjectId,
ref: 'Tasks',
}],
});
module.exports = User;
I then add a newUser named user1 and save to mongo.
The mongo doc looks like:
{
"_id" : ObjectId("574fb94f6a1e7d1826c16058"),
"username" : "user1",
"tasks" : [ ],
"__v" : 0
}
then try to fetch the document and it works fine in this handler:
In handlerA.js:
var User = require('../models/users.js');
module.exports.getUser = function(req, res){
User.findOne({username: "user1"}, function(err, data){
if(err){
console.log('getUser err', err);
res.send('ERROR')
} else {
console.log('getUser fx success = ', err, data);
res.send(data)
}
});
};
The result of the console.log:
getUser fx success = null { tasks: [], __v: 0, username: 'user1', _id: 574fb94f6a1e7d1826c16058 }
but same code fails in this other handler in a separate file.
In handlerB.js:
var User = require('../models/users.js');
module.exports.addStuff = function(req, res){
User.findOne({username: "user1"}, function(err, data){
if(err){
console.log('addStuff err', err);
res.send('ERROR')
} else {
console.log('addStuff fx success =', err, data);
res.send(data)
}
});
};
The result of the console.log:
addStuff fx success null null
Tried....and Failed....
I also tried this other solution from this question: Mongoose query return null
Mongoose pluralizes model names so it's running find on the "blogposts" collection instead of "blogpost". That said, your query in the mongo shell is on the "blogmodel" collection. In that case:
var BlogModel = mongoose.Model("BlogModel", ..)
or pass the collection name as the third param:
var BlogModel = mongoose.model("BlogPost", schema, "blogmodel")
This solution results in handlerA.js returning a null document as well as handlerB.js.
Thanks for your time. Much appreciated.
ADDENDUM.
I ran a find({}) under both the User and the Tasks models in handlerB.js
The returned document IN BOTH cases is based on the Tasks model.
see console.logs below for User.find({}) and Tasks.find({})
the err is the null value then the data.
How badly have I broken things? How can a Model.find return data that is not even in the model?
User.find({},funtion(err, data) ____________________
console.log of err then data
null
[ { subtasks: [],
team: [ [Object] ],
__v: 0,
maintask: '1',
_id: 574fce63d744cba421f750c1
},
{ subtasks: [],
team: [ [Object] ],
__v: 0,
maintask: '2',
_id: 574fce65d744cba421f750c2
}
]
Tasks.find({},function(err, data) ___________________
console.log of err then data
null
[ { subtasks: [],
team: [ [Object] ],
__v: 0,
maintask: '1',
_id: 574fce63d744cba421f750c1 },
{ subtasks: [],
team: [ [Object] ],
__v: 0,
maintask: '2',
_id: 574fce65d744cba421f750c2
},
]
This is the Tasks model...
tasks.js
var mongoose = require('mongoose');
var subtaskSchema = new mongoose.Schema({
subtask: {
type: String,
},
team: {
type: Array,
'defualt': [],
},
done: {
type: Boolean,
'defualt': false,
},
});
var Tasks = mongoose.model('tasks', {
maintask: {
type: String,
},
subtasks: {
type: [subtaskSchema],
},
team: {
type: Array,
'defualt': [],
},
done: {
type: Boolean,
'defualt': false,
},
});
module.exports = Tasks;
The mongoose docs suggest to define a model like so, did you try this?
var schema = new mongoose.Schema({ name: 'string', size: 'string' });
var Tank = mongoose.model('Tank', schema);

Categories