I have index not found exception when the first time I run my code for index creation,But second time it working good.
Here is my code
function searchIndex(callback){
client.search({
index: 'postgrescredentials-01',
type: 'credentials',
body: {
query: {
match: {
"username": "postgres"
}
},
}
},function (error, response,status) {
if (error){
console.log("search error: "+error)
}
else {
response.hits.hits.forEach(function(hit){
var ciphertext = hit._source.pswrd
callback(ciphertext)
})
}
});
};
exports.searchIndex = searchIndex;
encryptObj = enpyt.encrypt(password,function(encrypted){
client.index({
index: 'postgrescredentials-01',
id: '101',
type: 'credentials',
body: {
"username": "postgres",
"pswrd": encrypted
}
},function(err,resp,status) {
console.log(resp);
});
console.log("The encrypted password is-->",encrypted)
//Get The Searched Encrypted value
search.searchIndex(function(encryptedValue){
//Get the Decrypted Value
decrypt.decrypt(encryptedValue,function(decryptedValue){
console.log("The decrypted password is-->",decryptedValue);
});
});
})
Any idea why i am getting index not found exception at first time of execution.
Related
How to update Elasticsearch data multiple fields using UpdateByQuery in NodeJS ?
Note - My data is coming dynamically. I can't pass static value. I have to pass like - data.name, data.id
Code -
function updateInELK(data) { // Update by Id
const updateScript = {
inline: {
"ctx._source.name = "+data.name,
"ctx._source.role = "+data.role,
};
return new Promise((resolve, reject) => {
elasticsearch.updateByQuery({
index: indexName,
body: {
query: { match: { id: data.id } },
script: updateScript,
lang: 'painless',
}
}).then((response) => {
resolve(response);
}).catch((err) => {
console.log(err);
reject("Elasticsearch ERROR - data not updated")
})
});
}
Error -
TypeError: "ctx._source.name = " is not a function
Please let me know, if any other options are there. I can't update using id, because I don't know the id. I wanted to use updateByQuery, with conditions in the query parameters.
Here are the solutions -
await esClient.updateByQuery({
index: "data",
type: "doc",
refresh: true,
body:{
query:{
match: {
dataId: "70897e86-9d69-4700-b70e-881a7f74e9f9"
}
},
script:{
lang:"painless",
source:`ctx._source.data='This is updated test data';ctx._source.updatedAt=params.date;ctx._source.segmentId=params.segmentId`,
params:{
date: Date.now(),
segmentId: null
}
}
}
});
I've followed MongoDB's 'How To Use Mern Stack' tutorial to the letter, but I'm still getting null values stored in MongoDB. The console.log in the code does not appear, so I'm struggling to debug what's going on. Here's my code:
Client side
async function onSubmit(e) {
e.preventDefault();
// When a post request is sent to the create url, we'll add a new record to the database.
const newPerson = { ...form };
await fetch("http://localhost:5000/record/add", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(newPerson),
}).catch((error) => {
window.alert(error);
return;
});
setForm({ name: "", position: "", level: "" });
navigate("/");
}
Server side
recordRoutes.route("/record/add").post(function (req, response) {
console.log("hi");
let db_connect = dbo.getDb();
let myobj = {
name: req.body.name,
position: req.body.position,
level: req.body.level,
};
db_connect.collection("records").insertOne(myobj, function (err, res) {
if (err) throw err;
response.json(res);
});
});
Thanks for your help!
How to remove a nest attribute from dynamodb table on the basis of id? I m using nodejs(Typescript) with local dynamodb.
// check if post exists
const post = await dynamo.get({
TableName: "PostTable",
Key: { id: event.body.postId }
}).promise();
if (!post.Item) {
return formatJSONResponse({
message: `no post with this id`,
statuscode: 404
});
}
const params = {
TableName: "PostTable",
Key: { id: event.body.postId },
UpdateExpression:
"REMOVE comments.#id",
ExpressionAttributeValues: {
"#id": event.body.id
},
ReturnValues : "UPDATED_NEW"
}
let res= await dynamo.update(params).promise();
return formatJSONResponse({
message: `Comment has been removed
event,
result: res
});
dynamobdb table picture
Hi i am trying to setup LDAP authentication for my meteorJS app and i am following the steps listed in here https://janikvonrotz.ch/2017/02/08/meteor-register-ldap-login-request-handler/
i changed the search filter from mail to username and pushed everything inside of Meteor.startup() here is my code set up
UI code written in /imports/ui/loginform.jsx
let loginUserWithLDAP = (username, password, callback) => {
var loginRequest = {
ldap: true,
username: username,
email: username+"#company.com",
pass: password,
}
Accounts.callLoginMethod({
methodArguments: [loginRequest],
userCallback: callback
})
}
in my /server/ldap.js
Meteor.startup(() => {
var ldapAuth = {
url: 'ldap://company.com:389',
searchOu: 'ou=Employees,ou=\'company Users\', dc=company,dc=com',
searchQuery: (username) => {
return {
filter: '(&(objectclass=user)(samaccountname='+username+'))',
scope: 'sub'
}
}
}
ldapAuth.checkAccount = (options) => {
options = options || {}
ldapAuth.client = ldap.createClient({
url: ldapAuth.url
})
let dn = ['company', 'com']
var future = new Future()
ldapAuth.client.search(
ldapAuth.searchOu,
ldapAuth.searchQuery(options.username),
(error, result)=> {
assert.ifError(error)
result.on('searchEntry', (entry) => {
dn.push(entry.objectName)
return ldapAuth.profile = {
firstname: entry.object.cn,
lastname: entry.object.sn
}
})
result.on('error', function(error){
throw new Meteor.Error(500, "LDAP server error")
})
result.on('end', function(){
if (dn.length === 0) {
future['return'](false)
return false
}
return ldapAuth.client.bind(dn[0], options.pass, (error) =>{
if (error){
future['return'](false)
return false
}
return ldapAuth.client.unbind((error) => {
assert.ifError(error)
return future['return'](!error)
});
})
})
})
return future.wait()
}
Accounts.registerLoginHandler('ldap', (loginRequest)=>{
if (!loginRequest.ldap) {
return undefined
}
if (ldapAuth.checkAccount(loginRequest)){
var userId = null
var user = Meteor.users.findOne({"username": loginRequest.username })
if (!user) {
userId = Accounts.createUser({
username: loginRequest.username,
password: loginRequest.pass,
profile: ldapAuth.profile,
roles: ['user'],
})
Meteor.users.update(userId, { $set: { 'emails.0.verified': true } })
} else {
userId = user._id
}
let stampedToken = Accounts._generateStampedLoginToken()
let hashStampedToken = Accounts._hashStampedToken(stampedToken)
Meteor.users.update(userId,
{ $push: {'services.resume.loginTokens': hashStampedToken } }
)
return {
userId: userId,
token: stampedToken.token
}
}
})
});
In my debugging i found that its erroring out at
result.on('error', function(error){
throw new Meteor.Error(500, "LDAP server error")
})
due to '000004DC: LdapErr: DSID-0C0907E9, comment: In order to perform this operation a successful bind must be completed on the connection., data 0, v2580' what does this mean?
What is my code missing?
In short you need to define a search user that does the binding with the LDAP directory.
The post is outdated, I've got you this example: https://github.com/janikvonrotz/Zenkom/blob/0583f01abca96847178a248ff446d84c754965e9/server/actions/ldap.js#L18
Setup the search user like this:
"searchUser": {
"dn": "CN=username,OU=org,DC=company,DC=ch",
"password": "password"
}
The bind user is simply for search the directory. Another bind is executed to authenticate the found user.
I'm making an API server with Express, Graphql (Apollo server) and mongoose.
I'm testing the user creation. When the email is duplicated mongoose throws an error (Validation error. Unique = true) and graphql handles very good. But the console (terminal) shows the error too. How can i prevent that issue?
Resolver:
const MODEL_PATH = '../../models';
const User = require(MODEL_PATH + '/User');
const { register } = require('../../controllers/auth/RegisterController');
module.exports = {
RootQuery: {
users() {
return User.find({});
}
},
Mutation: {
registerUser(_, data) {
return register(data);
}
}
};
RegisterController (register function)
exports.register = function(data) {
const { email, password } = data;
const user = new User({
email,
password
});
return new Promise((resolve, reject) => {
user.save().then((user) => {
resolve(user);
}).catch((err) => {
reject(err);
});
});
};
And the error in the console (I DON'T WANT THAT. I HANDLED THE ERROR IN THE CONTROLLER. I WANT THE ERROR ONLY IN THE GRAPHQL RESPONSE)
MongoError: E11000 duplicate key error collection: y.users index: email_1 dup key: { : "test#example.com" }
at Function.MongoError.create (/Volumes/Datos/x/code/y/server/node_modules/mongodb-core/lib/error.js:31:11)
at toError (/Volumes/Datos/x/code/y/server/node_modules/mongodb/lib/utils.js:114:22)
....
Response in Graphiql (That is ok)
{
"data": {
"registerUser": null
},
"errors": [
{
"message": "E11000 duplicate key error collection: y.users index: email_1 dup key: { : \"test#example.com\" }",
"locations": [
{
"line": 9,
"column": 3
}
],
"path": [
"registerUser"
]
}
]
}
Thank you
According to: http://dev.apollodata.com/tools/graphql-server/setup.html
in server
app.use('/graphql', bodyParser.json(), graphqlExpress({ schema: myschema, debug: false }));
debug false did the trick.
Now. I'm check the packages for better error handling
Thanks
check out apollo-errors:
https://github.com/thebigredgeek/apollo-errors
and apollo-resolvers:
https://github.com/thebigredgeek/apollo-resolvers
These packages, together, were made to handle issues like the one you describe