I'm having a problem with using passport-ldap. I just can't seem to get anything other than Bad Request. I've got scripts working in Python and Bash, so I know the information is correct and maybe I'm just not seeing something. Any help would be great.
Here's a condensed version with just the bits necessary.
const passport = require('passport');
const LdapStrategy = require('passport-ldapauth');
var ldapOptions = {
server: {
url: <URL>,
bindDN: 'uid=<username>',
bindCredentials: '<password>',
searchBase: 'ou=Users, ou=Internal, o=<Corporate>,
searchAttributes: ['uid', 'mail', 'displayName'],
searchFilter: 'uid={{username}}'
}
}
passport.use('ldapauth', new LdapStrategy(ldapOptions));
router.post('/login', passport.authenticate('ldapauth', {session: false}), function(req, res) {
console.log('Hello');
});
The problem is in router.post, you cannon handle for a request without sand back something.
try res.send('somethings');
Best regards
Related
We're trying to create a trigger in MongoDB Atlas that will automatically reduce our Azure tier of an evening to save cost. The function we've put together (probably incorrectly!) returns an error when we try to run it. The result output is:
logs:
uncaught promise rejection: StitchError: HTTP request failed: unexpected status code: expected=200, actual=415
> result:
{
"$undefined": true
}
> result (JavaScript):
EJSON.parse('{"$undefined":true}')
We've tried messing around with the headers and body, but the end result is always the same.
Here's the WIP function:
exports = function() {
const response = context.http.patch({
scheme: "https",
host: "cloud.mongodb.com",
path: "/api/atlas/v1.0/groups/abc123/clusters/fake-server",
username: "usernamehere",
password: "passwordhere",
digestAuth: true,
headers: {"Content-Type": [ "application/json" ]},
body: {"clusterType":"REPLICASET", "providerSettings":{"providerName":"AZURE", "instanceSizeName":"M10", "regionName":"regionhere" } },
encodeBodyAsJSON: true
});
};
Any help would be greatly appreciated.
It turns out that we had it right the whole time.
Executing the exact same code as above is now correctly reducing our tier. I don't know what was causing the MongoDB Atlas API to think that our headers and / or request body were incorrect, but it's perfectly happy with it today.
The only other thing I will point out is that if you want this part of the error to go away...
> result:
{
"$undefined": true
}
> result (JavaScript):
EJSON.parse('{"$undefined":true}')
...you need to change the function to async / await like so:
exports = async function() {
const response = await context.http.patch({
I think this is related to how I've defined my schemas, but I can't seem to find where the bug is... I have an almost identical file set up that's working perfectly and I've unfortunately not been able to find a duplicate of this issue anywhere.
When sending an API request to my local Express instance via Postman, only the 'title' request body value is stored in the database. I am sending the following simple request to my route as Application/Json (thought the same happens when using x-www-form-urlencoded):
{
"postTitle": "title goes here",
"postContent": "body goes here",
"isPublished": true
}
This is clearly being registered in express, as if I log the object I can see this data (plus timestamps and an _id):
{ _id: 5b07d9c0b8124e0599079c04,
postTitle: 'title goes here',
postContent: 'body goes here',
isPublished: true,
createdAt: 2018-05-25T09:39:12.869Z,
updatedAt: 2018-05-25T09:39:12.869Z,
__v: 0 }
However, when I send a get request to my route on this object using its ID, I receive the following in response:
{ "_id": "5b07d9c0b8124e0599079c04" }
Likewise, if I send a request to list all objects, I receive the following response:
{
"posts": [
{
"_id": "5b07d9c0b8124e0599079c04"
},
{
"_id": "5b07d9c0b8124e0599079c03"
},
{
"_id": "5b07d9914f10ce058f137eba"
}
]
}
Weirdly, sometimes the post title sent as part of the response is included in the response, and sometimes it isn't.
My schema is as follows:
var postSchema = new Schema({
postTitle: String,
postContent: String,
isPublished: Boolean
},
{
timestamps: true
});
My post API route for POST requests is as follows:
router.post('/posts', (req, res, next) => {
var postTitle = req.body.postTitle;
var postContent = req.body.postContent;
var isPublished = req.body.isPublished;
var newPost = new Post({
postTitle: postTitle,
postContent: postContent,
isPublished: isPublished
});
newPost.save(function (error) {
if (error) {
console.log(error)
}
res.send({
success: true,
message: 'Post saved successfully!'
})
})
});
(If you're not using Router, you'll have 'app.post' instead of 'router.post') Again, this is a bit longwinded but everything works fine.
My GET route is as follows:
router.get('/posts', (req, res) => {
Post.find({}, 'title content published', function (error, posts) {
if (error) { console.error(error); }
res.send({
posts: posts
})
}).sort({_id:-1})
});
OK - so, by going through my code in detail I've figured out where I was going wrong and fixed the issue, however, in my searching I found very little in the way of results. I'm pretty new to Express, so I'm going to outline the cause of the issue and how I resolved it in order to potentially save someone else a bunch of time if they make the same stupid mistake.
Now, the issue I'm having results from the way I was retrieving the data and serving that in response to get requests. As an example, here's my GET route to list all of the objects.
I was entirely focusing on the post request and assuming it was a problem with the database. It turns out what I'd actually done, is in order to make my schemas and routes less confusing, I'd changed the names of the relevant variables. What I'd forgotten to do, however, is update this line in my GET route to reflect the change:
Post.find({}, 'postTitle postContent isPublished', function (error, posts) {
Which I'd left as:
Post.find({}, 'title content published', function (error, posts) {
The reason the title sometimes displayed is that I tried undoing changes back and forth to spot the issue.
I know this is a super basic query but I got stuck on this for the best part of a day, and the only other relevant discussion on this ended with OP saying that it magically fixed itself.
I'm new to Javascript and I'm having a recurring error with a REST API. It's a strange error (for me at least), so strange that I don't know what to call it. I'm calling it "Doubling", but it probably has a proper name, I just don't know what it is.
Anyway, the situation is this. I'm creating a REST API about cars. I'm using Javascript and the following node modules:
1) Express
2) Body-Parser
3) Mongoose
4) MongoDB
5) Mongod
The DB is very simple. It literally just lists the names of cars. Here's the code for it:
var express = require('express');
var bodyParser = require('body-parser');
var theAutos = require('./cardata');
var mongoose = require('mongoose');
var app = express();
app.use(express.static('public'));
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
mongoose.Promise = global.Promise;
var promise = mongoose.connect('mongodb://localhost/car_test_project', {
useMongoClient: true,
});
promise.then(function(db){
console.log('DATABASE NOW CONNECTED!!');
}).catch(function(err){
console.log('CONNECTION ERROR', err);
});
//*****SCHEMA*****
var Schema = mongoose.Schema;
var carTestSchema = new Schema({
name: String,
});
var Car = mongoose.model('Car', carTestSchema);
//*****END SCHEMA*****
//*****CAR DATA 'FOR EACH' FUNCTION*****
theAutos.forEach(function(theAutos){
var newAutomobile = new Car(theAutos);
newAutomobile.save(function (err) {
if (err) {
return (err);
}
});
});
//*****END 'FOR EACH' FUNCTION*****
//******THE 'GET' CODE*****
app.get('/carurl', function(req, res){
console.log(3);
Car.find({}).exec(function(err, car){
console.log(2);
if(err) {
return res.status(500).send(err);
}
return res.json(car);
});
});
//******END THE 'GET' CODE*****
//*****POST COMMAND CODE*****
app.post('/carurl', function(req, res){
var addAnAuto = new Car(req.body);
addAnAuto.save(function(err, car) {
if(err) {
return res.status(500).send(err);
}
return res.status(201).json(car);
});
});
//*****END POST COMMAND CODE*****
app.listen(8000, function(){
console.log('I be listening!');
});
At the beginning, the DB only has one entry; Ferrari. I've put this in a separate file called cardata.js and then I 'require' that file in the 3rd line of the above code (that's what the var theAutos = require('./cardata'); refers to. Here's the code for that file:
module.exports = [
{name: "Ferrari"}
]
As you can see, very simple database with only one entry. Now, here's where things get WEIRD!
I go to Postman and make a GET request. Postman comes back with Ferrari. So far so good. Then I go to make a POST request. I ask for a second car to be added to the database, in this case a Bugatti. I make a second GET request and I see:
{
"_id": "123etc...",
"name": "Ferrari",
"__v": 0
}
{
"_id": "xyzetc...",
"name": "Bugatti",
"__v": 0
}
So it's adding Bugatti to the database. That's great, right? It's doing what it's supposed to.
Wrong!
See, I need to make sure the addition is permanent, right? So I go to my terminal and restart the database by typing node index.js. I then go back to Postman and make yet another GET request. I'm expecting to see just Ferrari and Bugatti, right? However what I actually see, is:
{
"_id": "123etc...",
"name": "Ferrari",
"__v": 0
}
{
"_id": "xyzetc...",
"name": "Bugatti",
"__v": 0
}
{
"_id": "123etc...",
"name": "Ferrari",
"__v": 0
}
WTF?!? Where did that extra Ferrari come from? I certainly didn't want it there. It's like the DB is loading the DB with my POST request and then loading the original DB (which just had Ferrari in it) on top! Hence "Doubling"
Now, you might be thinking, "Shank, you fool! Just use a drop command like Car.collection.drop(); to refresh the DB when you reload it!"
Trouble is, when I try that I lose my Bugatti!
What I need is to figure out a way to (a) Add my Bugatti and other cars to the database and (b) do so in such a way that when I restart the database it doesn't "Double" and add another Ferrari in there.
It's no exaggeration to say I'm absolutely DESPERATE for help at this point. I've been grappling with this for days and I've read countless online tutorials and I've not come up with ANYTHING that can help me.
Any advice you could give would be massively appreciated.
Cheers,
Shank.
I've just started using hapi.js and have run into a problem when trying to defer the response for a route.
I successfully defer the response for the /query route using this code:
server.route([{
method: 'GET',
path: '/query',
config: {
handler: function(request, reply) {
var response = reply().hold();
db = request.server.plugins['hapi-mongodb'].db;
someFxn(callbackFxn, request, response);
}
}
}]);
var someFxn(cb, req, res){
var raw = {};
//... do lots of stuff that can take a long time
cb(req, res, raw);
}
var callbackFxn = function(request, response, data){
response.source = data;
response.send();
}
The problem I am having is that sometimes someFxn() takes a long time to execute and this seems to perhaps cause a timeout and the request is made again. How can I change the timeout value for the request so that it does not fire the request again?
I really appreciate any advice/leads anyone can give me.
You could be hitting the default Node.js socket timeout of 2 minutes. You can override it using the route config option config.timeout.socket:
From docs:
timeout - define timeouts for processing durations:
...
socket - by default, node
sockets automatically timeout after 2 minutes. Use this option to
override this behavior. Defaults to undefined which leaves the node
default unchanged. Set to false to disable socket timeouts.
Set it like this to disable timeouts entirely for the route:
server.route([{
method: 'GET',
path: '/query',
config: {
timeout: {
socket: false
},
handler: function(request, reply) {
...
}
}
}]);
I'm trying to organize my code, my code related to the get/post requests seem dirty/redundant.
On the client side, I have something like:
function DBManager()
{
this.getContactsList = function(cb)
{
$.post('/post/getContactsList', { data: data }, function (contacts)
{
cb(contacts);
});
}
// And a lot more methods similar to the above.
}
Then on the server side, I have something like:
app.post('/post/getContactsList', DBManager.getContactsList(pool, mysql));
// And of course a lot more like the above
Then in that DBManager.js route file, I have a lot of exports, like
exports.getContactsList = function(pool,mysql)
{
return function (req, res) {
// do something with req.body
}
}
// Again a lot more like the above
That seems redundant, especially passing the same data to the routes everytime such as the pool/mysql that we see.
Any recommendations or reading material?
Thanks