From a tutorial I set up my app to post to my endpoint on the click of a button in angularjs. In the tutorial it works, but for me it doesn't work.
if (!(req.body.username === 'john.doe' && req.body.password === 'foobar')) {
Is the problem line
serverapp.js
// LOAD ---- ---- ---- ----
var fs = require('fs');
var https = require('https');
var HTTPS_PORT = process.env.PORT || 3111;
var port = process.env.PORT || 3000;
var express = require('express');
var bodyParser = require('body-parser');
var Sequelize = require('sequelize');
var epilogue = require('epilogue');
var app = express();
var router = express.Router();
var morgan = require('morgan'); // log requests to the console (express4)
var bodyParser = require('body-parser'); // pull information from HTML POST (express4)
var methodOverride = require('method-override'); // simulate DELETE and PUT (express4)
var expressJwt = require('express-jwt'); //https://npmjs.org/package/express-jwt
var secret = 'this is the secret secret secret 12356';
var jwt = require('jsonwebtoken'); //https://npmjs.org/package/node-jsonwebtoken
// We are going to protect /api routes with JWT
app.use('/api', expressJwt({
secret: secret
}));
app.use('/', express.static(__dirname + '/'));
// if there's ever an unauth error, we redirect them
app.use(function(err, req, res, next) {
if (err.constructor.name === 'UnauthorizedError') {
res.status(401).send('Unauthorized :(');
}
});
app.post('/authenticate', function (req, res) {
//TODO validate req.body.username and req.body.password
//if is invalid, return 401
if (!(req.body.username === 'john.doe' && req.body.password === 'foobar')) {
res.status(401).send('Wrong user or password');
return;
}
var profile = {
first_name: 'John',
last_name: 'Doe',
email: 'john#doe.com',
id: 123
};
// We are sending the profile inside the token
var token = jwt.sign(profile, secret, { expiresInMinutes: 60*5 });
res.json({ token: token });
});
// ...MODELS, relations, rest endpoints and all that crap withheld from stack overflow
app.get('/api/restricted', function(req, res) {
console.log('user ' + req.body.username + ' is calling /api/restricted');
res.json({
name: 'foo'
});
});
clientapp.js
myApp.controller('userController', function ($scope, $http, $window) {
$scope.user = {username: 'thisshouldbeempty', password: 'thisshouldbeempty'};
$scope.isAuthenticated = false;
$scope.welcome = '';
$scope.message = '';
$scope.loginUser = function () {
$http
.post('/authenticate', $scope.user)
.success(function (data, status, headers, config) {
$window.sessionStorage.token = data.token;
$scope.isAuthenticated = true;
var encodedProfile = data.token.split('.')[1];
var profile = JSON.parse(url_base64_decode(encodedProfile));
$scope.welcome = 'Welcome ' + profile.first_name + ' ' + profile.last_name;
})
// etc....
html partial, login is invoked via button press
<button class="btn waves-effect waves-light" ng-click="loginUser()">Submit
<i class="material-icons right">send</i>
</button>
You must use bodyParser to access req.body:
var app = require('express')();
var bodyParser = require('body-parser');
var multer = require('multer'); // v1.0.5
var upload = multer(); // for parsing multipart/form-data
app.use(bodyParser.json()); // for parsing application/json
app.use(bodyParser.urlencoded({ extended: true })); // for parsing application/x-www-form-urlencoded
app.post('/profile', upload.array(), function (req, res, next) {
console.log(req.body);
res.json(req.body);
});
See http://expressjs.com/en/api.html
As per the comment in the code:
//TODO validate req.body.username and req.body.password
The code is lacking validation of input. You are getting the error Cannot read property 'username' of undefined for Angular Post Request because 'username' is undefined.
You need to check that the user has provided the inputs required for the post request, i.e.
if(!req.body.username || !req.body.password)
return; // should probably return some sort of error code
Elaboration: 'should probably return some sort of error code': send a JSON response with error code 404 and a relevant error message such as "No username specified." and "No password specified."
e.g.
if(!req.body.username) {
res.status(404).send('No username specified');
return;
}
if(!req.body.password) {
res.status(404).send('No password specified');
return;
}
Related
I tried mailchimp API to create a mailing list for newsletter but the response I'm getting is 404
I don't understand I checked everything again and again but still it showing 404
maybe the endpoint is incorrect but I got that from their documentation
endpoint: https://us7.api.mailchimp.com/3.0/
I already changed my server to us7 as API says
API: de5bbb37311bd90fe9264e991bc7c83f-us7
list id: 81937afd8f
[
const express = require("express");
const https = require("https");
const bodyparser = require("body-parser");
const request = require("request");
const app = express();
app.use(express.static("public"));
app.use(bodyparser.urlencoded({
extended: true
}));
app.get("/", function(req, res) {
res.sendFile(__dirname + "/signup.html");
});
app.post("/", function(req, res) {
var fname = req.body.firstname;
var lname = req.body.lastname;
var email = req.body.email;
const data = {
memebrs: [
{
email_address: email,
status: "subscribed",
merge_fields: {
FNAME: fname,
LNAME: lname,
}
}
]
}
const jsondata = JSON.stringify(data);
const url = "https://us7.api.mailchimp.com/3.0/81937afd8f";
const options = {
meathod: "POST",
auth: "rootacess3000:de5bbb37311bd90fe9264e991bc7c83f-us7"
}
const request = https.request(url,options,function(response){
response.on("data", function(data){
console.log(JSON.parse(data));
})
})
request.write(jsondata);
request.end();
});
app.listen(3000, function() {
console.log("sever is running on port 3000");
});
]1
okay so here's the correction:
your url = "https://us7.api.mailchimp.com/3.0/81937afd8f"; is wrong it should be url = "https://us7.api.mailchimp.com/3.0/lists/81937afd8f";
There's a typo in spelling of method, it's not "meathod" it's "method"
I am trying to use a middleware on my aplication to check on all routes if the token is passed, at the moment i want to test it just with the /users route, so i did this on my app file:
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var debug = require('debug')('express-sequelize');
var http = require('http');
var models = require('./models');
var jwt = require('./routes/jwt');
var app = express();
// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/',require('./routes/authentication'));
app.use('/users',jwt); // executa a verificacao do token em todas as rotas excepto o registo e login
// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
then in my jwt file i did this:
var express = require('express');
var User = require('../models').User;
var router = express.Router();
var jwt = require('jsonwebtoken');
// route middleware to verify a token
module.exports = function () {
return function (req, res, next) {
console.log("entered");
// check header or url parameters or post parameters for token
var token = req.body.token || req.query.token || req.headers['x-access-token'];
// decode token
if (token) {
// verifies secret and checks exp
jwt.verify(token, app.get('superSecret'), function (err, decoded) {
if (err) {
return res.json({ success: false, message: 'Failed to authenticate token.' });
} else {
// if everything is good, save to request for use in other routes
req.decoded = decoded;
next();
}
});
} else {
// if there is no token
// return an error
return res.status(403).send({
success: false,
message: 'No token provided.'
});
}
}
};
my jwt file is inside the routes folder that is at same level as the app file,
any sugestion? it doesn't hit the route
Your jwt file isn't set up correctly, change it to
var express = require('express');
var User = require('../models').User;
var router = express.Router();
var jwt = require('jsonwebtoken');
router.get('/', function(req, res, next) {
console.log("entered");
// check header or url parameters or post parameters for token
var token = req.body.token || req.query.token || req.headers['x-access-token'];
// decode token
if (token) {
// verifies secret and checks exp
jwt.verify(token, app.get('superSecret'), function (err, decoded) {
if (err) {
return res.json({ success: false, message: 'Failed to authenticate token.' });
} else {
// if everything is good, save to request for use in other routes
req.decoded = decoded;
next();
}
});
} else {
// if there is no token
// return an error
return res.status(403).send({
success: false,
message: 'No token provided.'
});
}
})
module.exports = router;
var search = 1 + req.url.indexOf('?'); throws an error saying the statement to my left is undefined. Im using passportjs to create a login/registration page on my angular frontend. trying to make a post request to nodejs results in the above error. Im entirely new to the mean stack and ive tried several different tutorials to get myself up and running but have had some road blocks. can someone point in the right direction?
I've played around with just about every file moving around code and trying different solutions but nothing works, or one problem is solved but another occurs.
server.js
// set up ========================
var DATABASE = "mongodb://localhost:27017/smartHomeDevices";
var express = require("express");
var mongoose = require("mongoose"); //require monogDB Driver
var morgan = require("morgan"); // log requests to the console (express4)
var bodyParser = require("body-parser"); // pull information from HTML POST (express4)
var methodOverride = require("method-override"); // simulate DELETE and PUT (express4)
var passport = require("passport");
//var _ = require("lodash");
var http = require('http');
//setup
//app.models =
require("./Models/moduleIndex");
// Bring in the Passport config after model is defined
require('./config/passport');
//registering routes
var routes = require("./routes");
//Create App
var app = express();
app.use(passport.initialize());
//Add Middleware for REST API
app.use(bodyParser.urlencoded({
extended: true
}));
app.use(bodyParser.json);
app.use(bodyParser.json({
type: 'application/vnd.api+json'
}));
app.use(methodOverride("X-HTTP-Method-Override"));
app.use(morgan("dev"));
//CORS Support, makes API Public
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Methods", "GET,PUT,POST,DELETE,");
res.header("Access-Control-Allow-Headers", "Content-Type,Authorization");
next();
});
app.use("/", routes);
// Connect to the db
mongoose.connect(DATABASE);
mongoose.connection.once("open", function() {
var serv = http.createServer(function(req, res) {
res.setHeader("Access-Control-Allow-Origin", "*");
res.setHeader("Access-Control-Allow-Methods", "GET,PUT,POST,DELETE");
res.setHeader("Access-Control-Allow-Headers", "Content-Type,Authorization");
res.writeHead(200, {
'Content-Type': 'text/plain'
});
res.end();
console.log(routes(req.method, req.url));
}).listen(3000);
//module.exports = app;
console.log("Listening on 3000");
});
routes.js
//setup
var express = require('express');
var router = express.Router();
var jwt = require('express-jwt');
var auth = jwt({
secret: 'MY_SECRET',
userProperty: 'payload'
});
var ctrlProfile = require('./Controllers/ProfileController');
var ctrlAuth = require('./Controllers/RegisterUserController');
// profile
router.get('/profile', auth, ctrlProfile.profileRead);
// authentication
router.post('/register', ctrlAuth.register);
router.post('/login', ctrlAuth.login);
module.exports = router;
/*module.exports = {
"/smartDevices" : require("./Controllers/SmartDeviceController"),
"/registeredUsers": require("./Controllers/RegisterUserController")
};*/
resgisteredUsersControllers.js
//setup
//var Resource = require("resourcejs");
var restful = require("node-restful");
var passport = require('passport');
var mongoose = require('mongoose');
var User = mongoose.model('registeredUserModel');
var sendJSONresponse = function(res, status, content) {
res.status(status);
res.json(content);
};
module.exports.register = function(req,res) {
console.log(req);
console.log("nw logging res");
console.log(res);
var user = new User();
user.name = req.body.name;
user.email = req.body.email;
user.username = req.body.username;
user.setPassword(req.body.password);
user.save(function(err) {
if(err)
console.log(err);
var token;
token = user.generateJwt();
res.status(200);
res.json({
"token" : token
});
});
next();
};
module.exports.login = function(req, res) {
passport.authenticate('local', function(err, user, info) {
var token;
// If Passport throws/catches an error
if (err) {
res.status(404).json(err);
return;
}
// If a user is found
if (user) {
token = user.generateJwt();
res.status(200);
res.json({
"token": token
});
} else {
// If user is not found
res.status(401).json(info);
}
})(req, res);
next();
};
/*module.exports = function(app, route) {
//setup controller for restful
// Resource(app,"",route,app.models.registeredUserModel).rest();
var rest = restful.model("registeredUserModel",
app.models.registeredUserModel
).methods(["get", "put", "post", "delete"]);
rest.register(app, route);
//return Middleware
return function(req, res, next) {
next();
};
};
*/
ProfileController.js
var mongoose = require('mongoose');
var User = mongoose.model('registeredUserModel');
module.exports.profileRead = function(req, res) {
// If no user ID exists in the JWT return a 401
if (!req.payload._id) {
res.status(401).json({
"message" : "UnauthorizedError: private profile"
});
} else {
// Otherwise continue
User
.findById(req.payload._id)
.exec(function(err, user) {
res.status(200).json(user);
});
}
};
Request object does not have url field.
i have the following method to auth my users:
app.all('/*', function(req, res, next) {
// CORS headers
res.header("Access-Control-Allow-Origin", "*"); // restrict it to the required domain
res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS');
// Set custom headers for CORS
res.header('Access-Control-Allow-Headers', 'Content-type,Accept,X-Access-Token,X-Key');
if (req.method == 'OPTIONS') {
res.status(200).end();
} else {
next();
}
});
var auth = require('./auth.js');
router.post('/login', auth.login);
app.all('/api/*', [require('./middlewares/validateRequest')]);
// If no route is matched by now, it must be a 404
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
And my Auth.js
var jwt = require('jwt-simple');
var auth = {
login: function(req, res) {
var username = req.body.username || '';
var password = req.body.password || '';
if (username == '' || password == '') {
res.status(401);
res.json({
"status": 401,
"message": "Invalid credentials"
});
return;
}
// Fire a query to your DB and check if the credentials are valid
var dbUserObj = auth.validate(username, password);
if (!dbUserObj) { // If authentication fails, we send a 401 back
res.status(401);
res.json({
"status": 401,
"message": "Invalid credentials"
});
return;
}
if (dbUserObj) {
// If authentication is success, we will generate a token
// and dispatch it to the client
res.json(genToken(dbUserObj));
}
},
validate: function(username, password) {
// spoofing the DB response for simplicity
var dbUserObj = { // spoofing a userobject from the DB.
name: 'arvind',
role: 'admin',
username: 'arvind#myapp.com'
};
return dbUserObj;
},
validateUser: function(username) {
// spoofing the DB response for simplicity
var dbUserObj = { // spoofing a userobject from the DB.
name: 'arvind',
role: 'admin',
username: 'arvind#myapp.com'
};
return dbUserObj;
}
}
// private method
function genToken(user) {
var expires = expiresIn(7); // 7 days
var token = jwt.encode({
exp: expires
}, require('../config/secret')());
return {
token: token,
expires: expires,
user: user
};
}
function expiresIn(numDays) {
var dateObj = new Date();
return dateObj.setDate(dateObj.getDate() + numDays);
}
module.exports = auth;
This server runs on port 8080.
So when i attempt to go to http://localhost:8080/login i get the following error message:
Error: Not Found
at app.use.bodyParser.urlencoded.extended (/var/www/example/backend/server.js:34:15)
at Layer.handle [as handle_request] (/var/www/example/backend/node_modules/express/lib/router/layer.js:82:5)
at trim_prefix (/var/www/example/backend/node_modules/express/lib/router/index.js:302:13)
at /var/www/example/backend/node_modules/express/lib/router/index.js:270:7
at Function.proto.process_params (/var/www/example/backend/node_modules/express/lib/router/index.js:321:12)
at next (/var/www/example/backend/node_modules/express/lib/router/index.js:261:10)
at next (/var/www/example/backend/node_modules/express/lib/router/route.js:100:14)
at next (/var/www/example/backend/node_modules/express/lib/router/route.js:104:14)
at next (/var/www/example/backend/node_modules/express/lib/router/route.js:104:14)
at next (/var/www/example/backend/node_modules/express/lib/router/route.js:104:14)
However it seems that the rest of my auth is working because if i go to:
http://localhost:8080/api/user
I get: {"status":401,"message":"Invalid Token or Key"}
Can anyone tell me why my login does not work?
Full server script:
// BASE SETUP
// =============================================================================
var express = require('express'),
bodyParser = require('body-parser');
var app = express();
var router = express.Router();
var es = require('express-sequelize');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: true
}));
// =============================================================================
//Secure
app.all('/*', function(req, res, next) {
// CORS headers
res.header("Access-Control-Allow-Origin", "*"); // restrict it to the required domain
res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS');
// Set custom headers for CORS
res.header('Access-Control-Allow-Headers', 'Content-type,Accept,X-Access-Token,X-Key');
if (req.method == 'OPTIONS') {
res.status(200).end();
} else {
next();
}
});
var auth = require('./auth.js');
router.post('/login', auth.login);
app.all('/api/*', [require('./middlewares/validateRequest')]);
// If no route is matched by now, it must be a 404
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
var env = app.get('env') == 'development' ? 'dev' : app.get('env');
var port = process.env.PORT || 8080;
var Sequelize = require('sequelize');
// db config
var env = "dev";
var config = require('./database.json')[env];
var password = config.password ? config.password : null;
// initialize database connection
var sequelize = new Sequelize(
config.database,
config.user,
config.password,
{
logging: console.log,
define: {
timestamps: false
}
}
);
//Init models
var division_model = require('./lb_models/division/division_model')(express,sequelize,router);
var user_model = require('./lb_models/user/user_model')(express,sequelize,router);
var team_model = require('./lb_models/Team')(express,sequelize,router);
app.use('/api', router);
app.use(division_model);
app.use(user_model);
app.use(team_model);
// START THE SERVER
app.listen(port);
console.log('Magic happens on port ' + port);
Try moving your app.use(bodyParser…) statements above the login route. The order of middleware matters. At the time login is called the req object hasn't run through the bodyParser middleware yet.
Also, your router instance is mounted at "/api" so the router methods will never get called for "/login". The following line should be place above your 404 catchall:
app.use('/', router);
Before, you had used app.use('/api', router), which means that your router routes will only be looked at for any request that starts with '/api'. Also, you had place the 'use' statement too far down.
When setting up middleware, the order in which you call app.use() is key. In your server.js, you're setting up your application routes before you set up body parser. Meaning, when the request comes in, is is not parsed before hitting your application logic. You need to move the app.use(bodyParser) parts to the top of your code.
var express = require('express'),
bodyParser = require('body-parser');
var app = express();
var router = express.Router();
var es = require('express-sequelize');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: true
}));
perphaps you have to move the
app.use("/", (req, res, next) => {
res.status("404").json({message: "Not found"})
})
to the bottom of your code, but before "app.listen()", The order you declare the routes in the router are important, so putting the "app.use" after you declare all theses routes, would search a match with all the previous route and if none is found then it will enter in that last one
Like this:
.
..
...
app.use('/api', router);
app.use(division_model);
app.use(user_model);
app.use(team_model);
app.use("/", (req, res, next) => {
res.status("404").json({message: "Not found"})
})
// START THE SERVER
app.listen(port);
console.log('Magic happens on port ' + port);
So I'm following the following Egghead.io guide:
https://egghead.io/lessons/angularjs-finalizing-jwt-authentication-with-angularjs
With a twist, I am trying to incorporate a MongoDB to retrieve my users. I have everything working so far, except the last part where he states that the /me route should just return req.user and it should be fine on refreshes. I don't get that. What I do get is blank user returned from my server.
My server code is setup like this:
var jwtSecret = 'fjkdlsajfoew239053/3uk';
app.use(cors());
app.use(bodyParser.json());
app.use(expressJwt({ secret: jwtSecret }).unless({ path: [ '/login' ]}));
app.use(compression());
app.use(express.static(__dirname + '/client'));
app.get('/', function(req, res){
res.render(__dirname + '/client/bundle.js');
});
app.get('/me', function (req, res) {
res.send(req.user);
});
... setup for user schema and other boring stuff ...
function authenticate(req, res, next) {
var body = req.body;
if (!body.username || !body.password) {
res.status(400).end('Must provide username or password');
}
//do salting, hashing, etc here yo
User.findOne({ username: body.username }, function(err, user){
if (user === null || body.password !== user.password) {
res.status(401).end('Username or password incorrect');
}else{
req.user = user;
next();
}
});
}
// ROUTES
app.post('/login', authenticate, function (req, res, next) {
var token = jwt.sign({
username: req.user.username
}, jwtSecret);
res.send({
token: token,
user: req.user
});
});
app.listen(process.env.PORT || 5000);
And my controller (Client-side) handling the basic authentication is:
module.exports = function($scope, $state, $modal, UserFactory) {
var vm = this;
$scope.$state = $state;
$scope.sign_in = false;
$scope.open = function () {
var $modalInstance = $modal.open({
templateUrl: 'suggestion-modal.html',
controller: 'modalCtrl'
});
};
// initialization
UserFactory.getUser().then(function success(response) {
vm.user = response.data;
});
function login(username, password) {
UserFactory.login(username, password).then(function success(response) {
vm.user = response.data.user;
}, handleError);
}
function logout() {
UserFactory.logout();
vm.user = null;
}
function handleError(response) {
alert('Error: ' + response.data);
}
vm.login = login;
vm.logout = logout;
};
Can anyone catch the bug I'm not seeing here? Basically I have a JWT on the client when I'm logged in but my initialization on the client controller is not recognizing that I'm logged in (it's not setting the user object to anything). It's kinda strange.
So my solution ended up taking into account Kent's help and a little brainstorming. It looked like the following. Note, apparently middleware ordering in express matters a lot since after changing when Express-jwt got loaded made a huge difference in whether or not the authentication headers were checked on initial directory load on the client (which if they were angular wouldn't load and the whole app broke). Cheers!
'use strict';
var faker = require('faker');
var cors = require('cors');
var bodyParser = require('body-parser');
var jwt = require('jsonwebtoken');
var expressJwt = require('express-jwt');
var compression = require('compression');
var express = require('express');
var bcrypt = require('bcrypt');
var connectLiveReload = require('connect-livereload');
var jwt = require('jsonwebtoken');
var app = express();
var jwtSecret = 'fjkdlsajfoew239053/3uk';
app.use(cors());
app.use(bodyParser.json());
app.use(compression());
app.use(express.static(__dirname + '/client'));
// app.get('/', function(req, res){
// res.render(__dirname + '/client/bundle.js');
// });
app.use(expressJwt({ secret: jwtSecret }).unless({ path: ['/login']}));
app.get('/me', function (req, res) {
res.send(req.user);
});
...schema stuff...
// UTIL FUNCTIONS
function authenticate(req, res, next) {
var body = req.body;
if (!body.username || !body.password) {
res.status(400).end('Must provide username or password');
}
//do salting, hashing, etc here yo
User.findOne({ username: body.username }, function(err, user){
if (user === null || body.password !== user.password) {
res.status(401).end('Username or password incorrect');
}else{
req.user = user;
next();
}
});
}
// ROUTES
app.post('/login', authenticate, function (req, res, next) {
var token = jwt.sign({
username: req.body.username
}, jwtSecret);
res.send({
token: token,
user: req.user
});
});
// app.use(connectLiveReload()); figure out whats wrong with this later and get livereload working
app.listen(process.env.PORT || 5000);