I'm new to Node.js. Trying to set up user account creation and log in using Passport. I can't ge it work. I am getting Unauthorized message although I am logging in with an existing user and pass. My code so far:
var express = require('express');
var http = require('http');
var path = require('path');
var request = require('request');
var app = express();
var passport = require('passport');
var LocalStrategy = require('passport-local').Strategy;
var MongoClient = require('mongodb').MongoClient;
app.set('port', process.env.PORT || 3000);
app.set('views', path.join(__dirname, 'views'));
app.engine('html', require('ejs').renderFile);
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.json());
app.use(express.urlencoded());
app.use(express.methodOverride());
app.use(passport.initialize());
app.use(passport.session());
app.use(app.router);
app.use(express.static(path.join(__dirname, 'public')));
app.use(express.bodyParser());
app.use(app.router);
app.enable('trust proxy');
if ('development' == app.get('env')) {
}
var httpserver = http.createServer(app).listen(app.get('port'), function(){
console.log('Express server listening on port ' + app.get('port'));
});
var mongoose = require('mongoose'),
Schema = mongoose.Schema,
passportLocalMongoose = require('passport-local-mongoose');
/* Database has _id field but i guess i don't need to add anything here?*/
var Accoun = new Schema({
username: String,
password: String
});
/* Database collection is called 'users'*/
Accoun.plugin(passportLocalMongoose);
var Account = mongoose.model('users', Accoun);
passport.use(new LocalStrategy(Account.authenticate()));
passport.serializeUser(Account.serializeUser());
passport.deserializeUser(Account.deserializeUser());
mongoose.connect('xxxmyconnectionstring');
app.get('/', function(req, res) {
res.render('login.html');
});
app.post('/login', passport.authenticate('local'), function(req, res) {
res.redirect('/myteam.html');
});
I need some expert help...
Regards,
I believe you need a successRedirect and failureRedirect in your app.post.
Related
Working with Registration in a Site. For the register Form,Validation is done using mongoose models and trying to Use Flash to display the error message in the Form.
But struct at this error
TypeError: res.flash is not a function
at /home/work/first-node-app/firstnode/routes/index.js:35:11
My Code snippets Follows below
App.js
var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var mongoose = require('mongoose');
var passport = require('passport');
var session = require('express-session');
var flash = require('connect-flash');
var indexRouter = require('./routes/index');
var commonKeys = require('./config/config');
var app = express();
//connect mongoDb
mongoose.connect('mongodb://localhost:27017/db', { useNewUrlParser: true });
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'pug');
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
// required for passport session
app.use(session({
secret: 'secrettexthere',
saveUninitialized: true,
resave: true,
// using store session on MongoDB using express-session + connect
}));
app.use(flash());
app.use(passport.initialize());
app.use(passport.session());
app.use('/', indexRouter);
module.exports = app;
Index.js
var express = require('express');
var router = express.Router();
var passport = require('passport');
var User = require('../models/user-model');
var Local = require('../config/passport-local');
router.get('/register', function(req, res){
res.render('public/register',{title:'Register'});
});
router.post('/register', function(req,res,next){
User.create({name:req.body.name, password:req.body.password, email : req.body.email}, function(err, user){
if (err) {
console.log('Error Inserting New Data');
if (err.name == 'ValidationError') {
for (field in err.errors) {
res.flash(field, err.errors[field].message);
}
res.render('public/register');
}
}
if(user) {
res.send('user registered');
}
})
});
module.exports = router;
Can anyone point out the error in this code snippets, as am new to Nodejs and Trying to work out the Form validation. The validation Works fine and the console displays the error but i can't pass that using flash. Can anyone Help me? And its much appreciated if you confirm my approach to code Nodejs is in correct way.
Use req.flash() in place of res.flash. Refer here for more clarification.
I'm trying to load /users/(username) for specific user profile pages, however I'm getting a Cannot GET /users/test error. I had it working at one point but then I added a function and it's broken again (I'm thinking the problem may be there in the route). Here's the relevant files. Any help would be greatly appreciated. Thank you!
app.js:
const fs = require('fs');
const _ = require('lodash');
const express = require('express');
const path = require('path');
const cookieParser = require('cookie-parser');
const bodyParser = require('body-parser');
const exphbs = require('express-handlebars');
const expressValidator = require('express-validator');
const flash = require('connect-flash');
const session = require('express-session');
const passport = require('passport');
const LocalStrategy = require('passport-local').Strategy;
const mongo = require('mongodb');
const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/tipcup');
var db = mongoose.connection;
const routes = require('./routes/index');
const users = require('./routes/users');
const user = require('./routes/user');
// Init App
var app = express();
// View Engine
app.set('views', path.join(__dirname, 'views'));
app.engine('handlebars', exphbs({defaultLayout: 'layout'}));
app.set('view engine', 'handlebars');
// BodyParser middleware
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false}));
app.use(cookieParser());
// Set Static Folder
app.use(express.static(path.join(__dirname, 'public')));
// Express Session
app.use(session({
secret: 'secret',
saveUninitialized: true,
resave: true
}));
// Passport Init
app.use(passport.initialize());
app.use(passport.session());
// Express Validator
app.use(expressValidator ({
errorFormatter: function(param, msg, value) {
var namespace = param.split('.')
, root = namespace.shift()
, formParam = root;
while(namespace.length){
formParam += '[' + namespace.shift() + ']';
}
return {
param: formParam,
msg: msg,
value: value
};
}
}));
// Connect Flash
app.use(flash());
// Global Vars
app.use(function (req, res, next){
res.locals.success_msg = req.flash('success_msg');
res.locals.error_msg = req.flash('error_msg');
res.locals.error = req.flash('error');
res.locals.user = req.user || null;
next();
});
app.use('/', routes);
app.use('/users', users);
app.use('/user/:username', user);
// Set Port
app.set('port', (process.env.PORT || 3000));
app.listen(app.get('port'), function(){
console.log('Server started on port '+app.get('port'));
});
user.js route:
var express = require('express');
var router = express.Router();
var User = require('../models/user');
// GET user by username
router.get('/:username', function(req, res) {
//var username = req.params.username;
User.getUserByUsername(function(err, user) {
if(err) {
res.send('error');
next();
}
const vm = user;
res.render('user', vm);
});
//res.render('user');
});
module.exports = router;
Its looks like you are defining the User Id twice
In app.js you are mounting the users routes /user/:username with the line
app.use('/user/:username', user);
Then in user.js you are declaring the get to /:username with the line
router.get('/:username', function(req, res) {
I would think this would produce a route with the signature /user/:username/:username
I would suggest remove the /:username one of the files
router.get('/:username', function(req, res) {
var username = req.params.username;
User.getUserByUsername(username).then(function(err, user){
res.json(user);
});
for mongoose you can do this:
router.get('/:username', function(req, res) {
var username = req.params.username;
User.getUserByUsername(username,function(err, user){
res.json(user);
});
});
I'm very new to node.js and passport.js. I was trying to learn how to make an authentication app using this video, but I keep getting this error after reaching 31:04 in the video.
"TypeError: Cannot read property 'name' of undefined at
Authenticator.use"
This is my app.js file:
var express = require('express');
var bodyParser = require('body-parser');
var cookieParser = require('cookie-parser');
var expressSession = require('express-session');
var passport = require('passport');
var passportLocal = require('passport-local');
var app = express();
app.set('view engine', 'ejs');
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
secret: process.env.SESSION_SECRET
app.use(expressSession({ || 'secret',
resave: false,
saveUninitialized: false
}));
app.use(passport.initialize());
app.use(passport.session());
passport.use(passportLocal.Strategy(function(username, password, done){
//connect to a real db here
if(username===password){
done(null,{id: username, name: username});
//these actually have to bbe pulled from the db
}
else{
done(null,null);
}
}));
app.get('/', function(req, res){
res.render('index',{
isAuthenticated: req.isAuthenticated(),
user: req.user
});
});
app.get('/login', function(req, res){
res.render('login');
});
app.post('/login', passport.authenticate('local' , function(req,res){
res.redirect('/');
}));
var port = process.env.PORT || 1337;
app.listen(port, function(err,res){
if(err)
console.log(err);
else
console.log('server started on localhost:'+ port +' /');
});
You have to call the new operator:
passport.use(new passportLocal.Strategy(function(username, password, done){
//connect to a real db here
if(username===password){
done(null,{id: username, name: username});
//these actually have to bbe pulled from the db
}
else{
done(null,null);
}
}));
I believe this is your problem.
I have the follow - Generated initially by the Visual Studio Node Tools, uses Express and Jade as the client
/**
* Module dependencies.
*/
var express = require('express');
var fs = require('fs');
var routes = require('./routes');
var user = require('./routes/user');
var http = require('http');
var https = require('https');
var path = require('path');
var passport = require('passport');
var googleStrategy = require('passport-google-oauth').OAuth2Strategy;
var loginHandler = require('./routes/Login.js');
var auth = require('./config/auth.js');
var googleSupport = require('./googleSupport.js');
var googleAuthority = auth.googleAuth;
var googleScopes = '';
// retrieve google scopes
googleScopes = googleSupport.discoverServiceScopes(auth.googleAuth);
// set up passport
passport.serializeUser(function (user,done) {
done(null, user);
});
passport.deserializeUser(function (obj, done) {
done(null, obj);
});
passport.use(new googleStrategy({
clientID: googleAuthority.clientId,
clientSecret: googleAuthority.clientSecret,
callbackURL: googleAuthority.callbackUrl
},
function (accessToken, refreshToken, profile, done) {
return done(null, profile);
}
));
var request = require('request');
var app = express();
// all environments
app.set('port', process.env.PORT || 3000);
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.json());
app.use(express.urlencoded());
app.use(express.methodOverride());
app.use(app.router);
app.use(require('stylus').middleware(path.join(__dirname, 'public')));
app.use(express.static(path.join(__dirname, 'public')));
// development only
if ('development' == app.get('env')) {
app.use(express.errorHandler());
}
console.log('extracting service scopes');
app.get(passport.initialize());
app.get(passport.session());
app.get('/', routes.index);
app.get('/index', routes.index);
// google login support
// go to login page.
app.get('/googleLogin', passport.authenticate('google', { scope: [googleScopes] }),
function (req, res) {
res.redirect('/');
}
);
app.get('/AuthorizeGoogle', passport.authenticate('google', { failureRedirect: '/'}),
function (req, res) {
res.redirect('/');
});
http.createServer(app).listen(app.get('port'), function () {
console.log('Express server listening on port ' + app.get('port'));
});
The thing is when it validates the user I get the following
500 Error: passport.initialize() middleware not in use
at IncomingMessage.req.login.req.logIn (C:\Node\YourLivesN\YourLivesN\node_modules\passport\lib\http\request.js:44:34)
at Strategy.module.exports.strategy.success (C:\Node\YourLivesN\YourLivesN\node_modules\passport\lib\middleware\authenticate.js:228:13)
at verified (C:\Node\YourLivesN\YourLivesN\node_modules\passport-oauth\node_modules\passport-oauth2\lib\strategy.js:179:18)
at Strategy._verify (C:\Node\YourLivesN\YourLivesN\app.js:41:12)
at C:\Node\YourLivesN\YourLivesN\node_modules\passport-oauth\node_modules\passport-oauth2\lib\strategy.js:195:22
at C:\Node\YourLivesN\YourLivesN\node_modules\passport-google-oauth\lib\passport-google-oauth\oauth2.js:115:7
at passBackControl (C:\Node\YourLivesN\YourLivesN\node_modules\passport-oauth\node_modules\passport-oauth2\node_modules\oauth\lib\oauth2.js:125:9)
at IncomingMessage. (C:\Node\YourLivesN\YourLivesN\node_modules\passport-oauth\node_modules\passport-oauth2\node_modules\oauth\lib\oauth2.js:143:7)
at IncomingMessage.emit (events.js:129:20)
at _stream_readable.js:908:16
Now I am assuming this is the same cause as this question passport.js passport.initialize() middleware not in use but cannot see what order the calls should be in my code.
So can anyone tell me what order to place the various parts of the code.
Thanks
Try changing this part
app.get(passport.initialize());
app.get(passport.session());
to
app.use(passport.initialize());
app.use(passport.session());
further reading on subject : Difference between app.use and app.get in express.js
, and I would suggest you separate passport configuration in a stand alone file and require it on paths that need authentication. Example tutorial : https://www.youtube.com/watch?v=zbfet_-Z5UQ&index=12&list=PLZm85UZQLd2Q946FgnllFFMa0mfQLrYDL
How do I get posted data from my api. I am using express 3.4.4
I am doing a resful api to accept posted data using node js and express
exports.mypost = function(req, res) {
console.log(req.body);
console.log(req.body.username);
console.log(req.body.name);
var user = new UserInfo({name:"dsd", username:"dsdsds"})
user.save();
res.send("user created");
}
and I post data use
curl --data "username=dsds&name=dsd" http://localhost:3000/mypost
I can see prints
{ username: 'dsds', name: 'dsd' }
dsds
dsd
But If I use
curl --form "username=dsds&name=dsd" http://localhost:3000/mypost
I see
{}
undefined
undefined
which means I didn't catch username and name from
req.body
How do I get the data from
curl --form "username=dsds&name=dsd" http://localhost:3000/mypost
I am posting my app.js:
/**
* Module dependencies.
*/
var express = require('express');
var routes = require('./routes');
var user = require('./routes/user');
var http = require('http');
var path = require('path');
var express = require('express');
var mongoose = require('mongoose');
var app = express();
// all environments
app.set('port', process.env.PORT || 3000);
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.json());
app.use(express.urlencoded());
app.use(express.methodOverride());
app.use(express.cookieParser('your secret here'));
app.use(express.session());
app.use(app.router);
app.use(require('stylus').middleware(path.join(__dirname, 'public')));
app.use(express.static(path.join(__dirname, 'public')));
app.use(express.bodyParser());
mongoose.connect('mongodb://localhost/data');
// development only
if ('development' == app.get('env')) {
app.use(express.errorHandler());
}
app.get('/', routes.index);
app.get('/users', user.list);
var api = require('./controllers/api.js');
app.post('/mypost', api.mypost);
http.createServer(app).listen(app.get('port'), function(){
console.log('Express server listening on port ' + app.get('port'));
});
Add this:
App.use(express.bodyParser());
Make sure its set before all your routes.
You can use bodyParser method to get the data from a post request
// Configure server
app.configure(function() {
app.use(express.bodyParser());
}