Cannot GET / node.js error - javascript

im making a simple todo list app , but am getting an error Cannot GET /
I think it has something to do with not creating a home route , also there might be a bug in index.ejs , but not sure exactly what it is. Any help is greatly appreciated ! thanks !!
app.js
// Dependencies
var express = require('express'),
path = require('path'),
bodyParser = require('body-parser'),
mongoose = require('mongoose'),
cookieParser = require('cookie-parser'),
expressSession = require('express-session'),
passport = require('passport'),
passportLocal = require('passport-local');
// MongoDB
mongoose.connect('mongodb://localhost/todos');
// Express
var app = express();
// Configuration
app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json());
// app.use(cookieParser);
app.use(expressSession({
secret: 'secret-key',
resave: false,
saveUninitialized: false
}));
app.use(passport.initialize());
app.use(passport.session());
app.use(express.static(path.join(__dirname, 'bower_components')));
app.set('view engine', 'ejs');
app.set('views', path.join(__dirname, 'views'));
// Route
app.use('/todo', require('./routes/todo'));
app.use('/', require('./routes/user'));
// Start Server
app.listen(3000);
console.log('TODO app is running...');
routes/user.js
var express = require('express');
var mongoose = require('mongoose');
var router = express.Router(),
cookieParser = require('cookie-parser'),
expressSession = require('express-session'),
passport = require('passport'),
passportLocal = require('passport-local');
require('../models/user');
var User = mongoose.model('user');
passport.use( new passportLocal.Strategy(function(username, password, done){
User.findOne({ username: username }, function (err, user) {
console.log(user);
if (err) { return done(err); }
if (!user) {
return done(null, false, { message: 'Incorrect username.' });
}
if (user.password != password) {
return done(null, false, { message: 'Incorrect password.' });
}
return done(null, user);
});
}));
passport.serializeUser(function(user, done) {
done(null, user.id);
});
passport.deserializeUser(function(id, done) {
User.findById(id, function(err, user) {
done(err, user);
});
});
router.get('/login', function(req, res){
if(req.isAuthenticated()){
res.redirect('/todo');
}
res.render('login', { message: req.session.messages });
});
router.post('/login', loginPost);//passport.authenticate('local'), function(req, res){
// res.redirect('/todo');
// });
function loginPost(req, res, next) {
passport.authenticate('local', function(err, user, info) {
if (err) {
return next(err);
}
if (!user) {
req.session.messages = info.message;
return res.redirect('/login');
}
req.logIn(user, function(err) {
if (err) {
req.session.messages = "Error";
return next(err);
}
// set the message
return res.redirect('/todo');
});
})(req, res, next);
}
router.get('/logout', function(req, res){
req.logout();
req.session.messages = "";
res.redirect('/login');
});
router.get('/signup', function(req, res){
if(req.isAuthenticated()){
res.redirect('/todo');
}
res.render('signup');
});
router.post('/signup', function(req, res){
new User({username: req.body.username, password: req.body.password}).save(function(err, doc){
if(err) res.json(err);
else res.redirect('/login');
});
});
module.exports = router;
routes/todo.js
var express = require('express');
var mongoose = require('mongoose');
var router = express.Router();
require('../models/todo');
require('../models/user');
var todo = mongoose.model('todo');
function isAuthenticated(req, res, next) {
// CHECK THE USER STORED IN SESSION FOR A CUSTOM VARIABLE
// you can do this however you want with whatever variables you set up
if (req.isAuthenticated())
return next();
// IF A USER ISN'T LOGGED IN, THEN REDIRECT THEM SOMEWHERE
res.redirect('/login');
}
router.get('/', isAuthenticated, function(req, res){
console.log(req.session.passport.user);
var User = mongoose.model('user'), userData;
User.find({ _id: req.session.passport.user}, function(err, user){
console.log(user);
userData = user; return true;
}).limit(1);
console.log(userData);
todo.find({user: req.session.passport.user}, function(err, todos){
res.render('index', {items:todos, userData:userData});
});
});
router.post('/add', function(req, res){
new todo({task: req.body.task, user: req.session.passport.user}).save(function(err, doc){
if(err) res.json(err);
else res.redirect('/todo');
});
});
router.get('/delete/:id', function(req, res){
todo.remove({_id: req.params.id}, function(err){
res.redirect('/todo');
});
});
router.post('/update', function(req, res){
todo.where({_id: req.body.id}).update({status: req.body.status}, function(err, doc){
if(err) res.json(err);
else res.send(200);
});
});
module.exports = router;
views/index.ejs
<!DOCTYPE html>
<html>
<head>
<title>EHad Todo App</title>
<link rel="stylesheet" type="text/css" href="bootstrap/dist/css/bootstrap.css">
<link rel="stylesheet" type="text/css" href="todo.css">
</head>
<body>
<div class="container">
<div class="row">
<div class=".col-md-6 .col-md-offset-3">
<section class="panel tasks-widget">
<header class="panel-heading">
<p class="bg-primary"><%= userData[0].username %> Todo list</p>
</header>
<div class="panel-body">
<div class="task-content">
<ul class="task-list">
<% for (var i = 0; i < items.length; i++) { %>
<li class="task-<%= items[i].status %>">
<div class="task-checkbox">
<input type="checkbox" class="task-list-check" value="<%= items[i]._id %>" <% if(items[i].status == 'done'){ %> checked <% }%> >
</div>
<div class="task-title">
<span class="task-title-sp"><%= items[i].task %></span><sub class="date"><%= items[i].date.toDateString() %></sub>
<div class="pull-right hidden-phone">
<button class="btn btn-danger btn-xs">x</i></button>
</div>
</div>
</li>
<% } %>
</ul>
</div>
<div class=" add-task-row">
<form action="todo/add" method="post">
<div class="form-group">
<input type="text" class="form-control" name="task" placeholder="ADD Task">
</div>
<button type="submit" class="btn btn-success btn-sm pull-right">Add New Tasks</button>
</form>
</div>
<span style="font-size:12px">Logout</span>
<div><p class="bg-info">copyright By #emranulhadi 2015</p></div>
</div>
</section>
</div>
</div>
</div>
<script type="text/javascript" src="jquery/dist/jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$(".btn-danger").on("click", function(e){
var r = confirm("Are You Sure? You want to DELETE!!!");
if (r == true) {
return true;
} else {
e.preventDefault();
return false;
}
});
$('.task-list-check').click(function() {
var taskStatus = "done";
if($(this).is(":checked")){
$(this).parent().parent().addClass('task-done');
} else {
$(this).parent().parent().removeClass('task-done');
taskStatus = "new";
}
$.post( "todo/update", {id: $(this).val(), status: taskStatus}, function( data ) {
console.log(data);
return true;
});
});
});
</script>
</body>
</html>

In your routes/user.js file, define another route definition for /, and render whatever view you want for the index route.
router.get('/', (req, res){
res.render("/path/to/view/file");
});

Related

how to make a page only accessible when logged in with express & ejs

Currently I'm working on a little project for a dummy login/register page and now I want to add a page that is only accessible when you're logged in. So the question is how do I make a session or cookie and retrieve them? And how do I block not logged in users.
I'm currently using this code for the 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 expressSession = require('express-session');
var passport = require('passport');
var LocalStrategy = require('passport-local').Strategy;
var AuthTokenStrategy = require('passport-auth-token').Strategy;
require('./models');
var User = mongoose.model('User')
mongoose.connect('mongodb://localhost:27017/my-data', { useNewUrlParser: true, useUnifiedTopology: true })
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
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')));
passport.use(new LocalStrategy({
usernameField: "key"
}, function(key, next) {
User.findOne({
key: key
}, function(err, user) {
if (err) return next(err);
if (!user) {
return next({message: 'Key incorrect'})
}
next(null, user);
})
}));
passport.serializeUser(function (user, next) {
next(null, user._id)
})
passport.deserializeUser(function (id, next){
User.findById(id, function (err, user) {
next(err, user);
});
});
app.use(passport.initialize());
app.use(passport.session());
app.use(expressSession({
secret: 'aksndklajsdjicpwoemcklnaiohdandascopkqpowdmklasmdiojqwndjkasndosiqjwdklnasaksndklajsdjicpwoemcklnaiohdandascopkqpowdmklasmdiojqwndjkasndosiqjwdklnas'
}))
app.get('/', function(req, res, next){
res.render('index', {title: 'MySite'})
});
app.get('/main', function(req, res, next){
res.render('main')
});
app.get('/login', function(req, res, next){
res.render('login')
});
app.post('/signup', function(req, res, next){
User.findOne({
key: req.body.key
}, function (err, user) {
if (err) return next(err)
if (user) return next({message: 'This client exists'})
let newUser = new User({
key: req.body.key
});
newUser.save(function(err) {
if (err) return next(err);
res.redirect('/main');
});
console.log(req.body)
});
});
app.post('/login', async (req, res, next) => {
const key = req.body.key;
//const ip = req.header('x-forwarded-for') || req.connection.remoteAddress;
//console.log(ip);
if (!key) return res.status(401).json({ err: 'Key not provided' });
const User = mongoose.model('User');
const user = await User.findOne({ key }).exec();
if (!user) return res.status(401).json({ err: 'Invalid Key' });
res.redirect('/main');
});
// error handler
app.use(function(err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
// render the error page
res.status(err.status || 500);
res.render('error');
});
module.exports = app;
Try do add this middleware to protected route:
function isAuthenticated(req,res,next){
if(req.isAuthenticated()){ // will return true if user is logged in
next();
} else{
res.redirect("/login");
}
}
app.get('/protectedPath',isAuthenticated, function(req,res) {
//protected content
);

Cannot read property 'totalQty' of undefined

I've created a cart object, which can store the products in a cart. The problem is before an item is put into the cart it is undefined. How do I make the cart defined even when nothing is in it during the session? I'm using ejs.
Here is my Error
/home/ubuntu/workspace/views/partials/header.ejs:37
35| </li>
36| <li>
>> 37| <a href="cart" class="navport"><span
class="badge"><%= session.cart.totalQty || 0%></span></a>
38| </li>
39| </ul>
40|
Cannot read property 'totalQty' of undefined
App.js
var express = require("express");
var app = express();
var mongoose = require("mongoose"),
User = require("./models/user"),
bodyParser = require("body-parser"),
ejs = require("ejs"),
passport = require("passport"),
LocalStrategy = require("passport-local"),
localMongoose = require("passport-local-mongoose"),
session = require("express-session"),
MongoStore = require("connect-mongo")(session),
Cart = require("./models/cart"),
Clothes = require("./models/clothes");
mongoose.connect("mongodb://localhost/bitchinvintage");
app.set("view engine", "ejs");
app.use(express.static(__dirname + "/public"));
app.use(bodyParser.urlencoded({ extended: true }));
app.use(session({
secret: "random dogga",
resave: false,
saveUninitialized: false,
store: new MongoStore({mongooseConnection: mongoose.connection}),
cookie: {maxAge: 180 * 60 * 1000}
}));
app.use(passport.initialize());
app.use(passport.session());
passport.use(new LocalStrategy(User.authenticate()));
passport.serializeUser(User.serializeUser());
passport.deserializeUser(User.deserializeUser());
app.use(function (req, res, next) {
res.locals.login = req.isAuthenticated();
res.locals.session = req.session;
next();
});
app.get("/", function(req, res){
res.render("landing");
});
// Clothes Routes
app.get("/clothes", function(req, res){
// Get all campgrounds from DB
Clothes.find({}, function(err, clothes){
if(err){
console.log(err);
} else {
res.render("clothes",{clothes:clothes});
}
});
});
app.get("/clothes/new", function(req, res){
res.render("new");
});
app.post("/clothes", function(req, res){
var name = req.body.name;
var overlay = req.body.overlay;
var price = req.body.price;
var image = req.body.image;
var newClothes = {name: name, image: image, price: price, overlay: overlay}
Clothes.create(newClothes, function(err, newlyCreated){
if(err){
console.log(err);
} else{
res.redirect("/clothes");
}
});
});
// ------------------
// Register Routes
app.get("/register", function(req, res){
res.render("register");
});
app.post("/register", function(req, res){
var newUser = new User({username: req.body.username});
User.register(newUser, req.body.password, function(err, user){
if (err){
console.log(err);
return res.render("register");
}
passport.authenticate("local")(req, res, function(){
res.redirect("/");
})
})
});
// -----------
// Login Routes
app.post("/login", passport.authenticate("local", {
successRedirect: "/",
failureRedirect: "/register"
}), function(req, req){
});
// Cart Routes
app.get("/add-to-cart/:id", function(req, res, next){
var productId = req.params.id;
var cart = new Cart(req.session.cart ? req.session.cart : {});
console.log("works");
Clothes.findById(productId, function(err, clothes){
if(err){
return res.redirect("/");
}
cart.add(clothes, productId);
req.session.cart = cart;
console.log(req.session.cart);
res.redirect("/clothes");
});
});
// ------------
app.get("/account", isLoggedIn, function(req, res){
});
app.get("/*", function(req, res){
res.render("error");
});
app.listen(process.env.PORT, process.env.IP, function(){
console.log("Vintage server Starting...")
});
function isLoggedIn(req, res, next) {
if (req.user) {
next();
} else {
res.redirect("/account");
}
}
models/cart.js
This is the cart Object
module.exports = function Cart(oldCart) {
this.items = oldCart.items || {};
this.totalQty = oldCart.totalQty || 0;
this.totalPrice = oldCart.totalPrice || 0;
this.add = function(item, id) {
var storedItem = this.items[id];
if (!storedItem){
storedItem = this.items[id] = {item: item, qty: 0, price: 0}
}
storedItem.qty++;
storedItem.price = storedItem.item.price * storedItem.qty;
this.totalQty++;
this.totalPrice += storedItem.price;
}
this.generateArray = function() {
var arr = [];
for (var id in this.items) {
arr.push(this.items[id]);
}
return arr;
}
};
header.ejs
This is the HTML where I'm trying to list the total amount in the cart on the navbar
<li>
<a href="cart" class="navport"><span class="badge"><%=
session.cart.totalQty || 0%></span></a>
</li>
</ul>
var Cart = require('../models/cart');
(path for cart model)
did you include this line in your route ? because of that you are getting cart it is undefined error. please make sure that you have included above line in your route file. when you create a cart object this line will help you refer the cart model.
I've faced the same issue while loading the index template. Can you check if session.cart is available before rendering shopping-cart quantity? I added simple if condition like below and it worked for me.
<% if(session.cart) { %>
<span class="badge"><%= session.cart.totalQty %></span>
<% } %>

Route separation in express routing with passing passport instance

I'm trying to add user-login module to an existing app in node. It is using separate route files for each module and one main route file to use all the child routes which is ultimately used in server.js
When I try to pass passport instance to the user route, it gives me error as passport is not defined. Here is my app code and structure:
app
views
user
index.ejs
login.ejs
signup.ejs
profile.ejs
routes
docs
index.js
user
index.js
index.js
config
passport.js
server.js
server.js
const express = require('express')
const app = express()
const path = require('path')
const bodyParser = require('body-parser')
const cookieParser = require('cookie-parser')
const passport = require('passport')
const flash = require('connect-flash')
const session = require('express-session')
const routes = require('./routes/')
const port = process.env.PORT || 3000;
app.use(express.static(path.join(__dirname, 'public')));
require('./config/passport')(passport);
app.use(bodyParser.urlencoded({
extended: true
}));
app.use(cookieParser());
app.use(bodyParser.json());
app.set('view engine', 'ejs');
app.set('views', path.join(__dirname, 'views'));
app.use(session({ secret: '********' }));
app.use(passport.initialize());
app.use(passport.session());
app.use(flash());
app.use('/', routes)(app,passport);
const server = app.listen(port, function(){
console.log('Server listening on port '+port);
});
config/passport.js
var LocalStrategy = require('passport-local').Strategy;
const sql = require('mssql')
const bcrypt = require('bcrypt-nodejs')
module.exports = function(passport) {
passport.serializeUser(function(user, done) {
done(null, user);
});
passport.deserializeUser(function (username, done) {
done(null,username);
});
passport.use('local-signup', new LocalStrategy({
usernameField : 'email',
passwordField : 'password',
passReqToCallback : true
},
function(req, email, password, done) {
process.nextTick(function() {
var strSQL = "SELECT count(id) as uCount FROM <tbl> WHERE username = '"+email+"'";
var cb1 = function(err,recordset){
if(recordset[0].uCount>0){
return done(null, false, req.flash('signupMessage', 'That email is already taken.'));
} else{
var strSQL1 = "INSERT INTO <tbl>(username, password) VALUES('"+email+"','"+generateHash(password)+"')";
var cb2 = function(err,recordset){
return done(null, recordset,req.flash('signupMessage', 'Email registered successfully.'));
};
executeQuery(strSQL1,'INSERTION','<tbl>',cb2);
}
};
executeSelection(strSQL,'SELECTION','<tbl>',cb1);
});
}));
passport.use('local-login', new LocalStrategy({
usernameField : 'email',
passwordField : 'password',
passReqToCallback : true
},
function(req, email, password, done) {
var strSQL = "SELECT a.count, id, username, password FROM <tbl> c , (SELECT COUNT(dbid) count FROM <tbl> b WHERE b.username = '"+email+"' ) a WHERE c.username = '"+email+"'";
var cb1 = function(err,recordset){
if(recordset[0].uCount <= 0){
return done(null, false, req.flash('loginMessage', 'No user found.'));
}
if (!validPassword(password,recordset[0].password))
return done(null, false, req.flash('loginMessage', 'Oops! Wrong password.'));
return done(null, recordset[0]);
};
executeSelection(strSQL,'SELECTION','<tbl>',cb1);
}));
};
executeSelection = function(strSQL, operationType, tableName, cb){
var request = new sql.Request(connection);
request.query(strSQL,function(err,recordset) {
if(err){
logger.error('ERROR in '+operationType+' ON '+tableName+': '+err);
}
logger.info(operationType+' ON '+tableName+' successful!');
cb(err,recordset);
});
};
executeQuery = function(strSQL, operationType, tableName, cb,validateClient) {
var request = new sql.Request(connection);
request.query(strSQL,function(err, recordset) {
if(err){
logger.error('ERROR in '+operationType+' ON '+tableName+': '+err);
}
logger.info(operationType+' ON '+tableName+' successful!');
if(cb){
cb(validateClient);
}
});
};
generatePasswordHash = function(password) {
return bcrypt.hashSync(password, bcrypt.genSaltSync(8), null);
};
validatePassword = function(curPass, dbPass) {
return bcrypt.compareSync(curPass, dbPass);
};
routes/index.js
const mainroute = require('express').Router()
/* ---- other existing routes included ---- */
const r_docs = require('./docs')
const r_user = require('./user') /*my custom route*/
/* ---- all other routes ---- */
mainroute.use('/docs', r_docs);
mainroute.use('/user', r_user)(app, passport); /*my custom route*/
mainroute.get('/', function(req, res){
res.render('home');
});
module.exports = function(app, passport){
mainroute;
}
routes/user/index.js
const express = require('express')
const router = express.Router()
router.get('/', function(req, res) {
res.render('user/index.ejs');
});
router.get('/login', function(req, res) {
res.render('user/login.ejs', { message: req.flash('loginMessage') });
});
// process the login form
router.post('/login', passport.authenticate('local-login', {
successRedirect : '/profile',
failureRedirect : '/login',
failureFlash : true
}));
router.get('/signup', function(req, res) {
res.render('user/signup.ejs', { message: req.flash('signupMessage') });
});
router.post('/signup', passport.authenticate('local-signup', {
successRedirect : '/profile',
failureRedirect : '/signup',
failureFlash : true
}));
router.get('/profile', isLoggedIn, function(req, res) {
res.render('user/profile.ejs', {
user : req.user
});
});
router.get('/logout', function(req, res) {
req.logout();
res.redirect('/');
});
function isLoggedIn(req, res, next) {
if (req.isAuthenticated())
return next();
res.redirect('/');
}
module.exports = function(app, passport) {
router;
}
Please suggest what am I doing wrong here. Thanks
You should wrap your main and user routes to run their logic when you call them and at end return prepared route:
routes/index.js
module.exports = function(app, passport) {
const mainroute = require('express').Router()
/* ---- other existing routes included ---- */
const r_docs = require('./docs');
const r_user = require('./user'); /*my custom route*/
/* ---- all other routes ---- */
mainroute.use('/docs', r_docs);
mainroute.use('/user', r_user)(app, passport); /*my custom route*/
mainroute.get('/', function(req, res) {
res.render('home');
});
return mainroute;
};
routes/user/index.js
module.exports = function(app, passport) {
const express = require('express');
const router = express.Router();
router.get('/', function(req, res) {
res.render('user/index.ejs');
});
router.get('/login', function(req, res) {
res.render('user/login.ejs', {
message: req.flash('loginMessage')
});
});
// process the login form
router.post('/login', passport.authenticate('local-login', {
successRedirect: '/profile',
failureRedirect: '/login',
failureFlash: true
}));
router.get('/signup', function(req, res) {
res.render('user/signup.ejs', {
message: req.flash('signupMessage')
});
});
router.post('/signup', passport.authenticate('local-signup', {
successRedirect: '/profile',
failureRedirect: '/signup',
failureFlash: true
}));
router.get('/profile', isLoggedIn, function(req, res) {
res.render('user/profile.ejs', {
user: req.user
});
});
router.get('/logout', function(req, res) {
req.logout();
res.redirect('/');
});
function isLoggedIn(req, res, next) {
if (req.isAuthenticated())
return next();
res.redirect('/');
}
return router;
};
You need to require it at the top of your user/index.js. Simply:
var passport = require('passport');
Then to make sure the user is authenticated:
router.get('/some/path', isLoggedIn, function(req, res) {
var user = req.user;
});
function isLoggedIn(req, res, next) {
if (req.isAuthenticated())
return next();
res.redirect('/');
}

Data is not delete in mongodb with angularJS

Server side code:
var User = require("./models/user");
var express = require('express'),
app = express(),
Account = require("./models/account"),
mongoose = require('mongoose'),
passport = require("passport"),
basicAuth = require('basic-auth'),
bodyParser = require("body-parser"),
LocalStrategy = require("passport-local"),
passportLocalMongoose = require("passport-local-mongoose"); //libraries
mongoose.connect("mongodb://localhost/test");
app.set('view engine', 'ejs'); //using engine of ejs file
app.use(bodyParser.urlencoded({extended: true}));
app.use(require("express-session")({
secret: "kiss my ass",
resave: false,
saveUninitialized: false
}));
app.use(passport.initialize());
app.use(passport.session());
passport.use(new LocalStrategy(Account.authenticate()));
passport.serializeUser(Account.serializeUser());
passport.deserializeUser(Account.deserializeUser());
// AUTH Routes
//create account success
app.get('/success', function (req, res) {
res.render('success');
});
// deleteUser form
app.get("/delete", function(req, res, next) {
res.render("deleteuser");
});
app.get("/viewall", function(req, res, next) {
res.render("viewall");
});
//view all User form
app.get('/view', function (req, res) {
console.log('getting all user');
Account.find({})
.exec(function(err, results) {
if(err) {
res.send('error has occured');
}else{
console.log(results);
res.json(results);
}
});
});
app.get('/viewall/:id', function (req, res) {
console.log('getting one user');
Account.findOne({
_id:req.params.id
})
.exec(function(err, account) {
if(err) {
res.send('error occured');
}else{
console.log(account);
res.json(account);
}
})
})
// LOGIN for user
// render login form
app.get("/", function(req, res) {
res.render("login");
});
//login for user
//middleware
app.post("/login", passport.authenticate("local", {
successRedirect: "http://localhost:8082/viewImage.html",
failureRedirect: "http://localhost:8081/error"
}), function(req, res) {
});
//logout from basicauth
app.get('/logout', function (req, res) {
res.set('WWW-Authenticate', 'Basic realm=Authenticate Required');
return res.sendStatus(401);
// res.send("<a href='/login'>Show Users</a>");
});
//basicauth for admin login
var auth = function (req, res, next) {
function unauthorized(res) {
res.set('WWW-Authenticate', 'Basic realm=Authenticate Required');
return res.send(401);
};
var user = basicAuth(req);
if (!user || !user.name || !user.pass) {
return unauthorized(res);
};
if (user.name === 'admin' && user.pass === 'admin123') {
return next();
} else {
return unauthorized(res);
};
};
//LOGIN for admin
//render login form
app.get("/register", auth, function(req, res) {
res.render("register");
});
// register post
app.post("/register", function(req,res){
Account.register(new Account({username: req.body.username}), req.body.password, function(err, user){
if(err){
console.log(err);
return res.render('/register');
}
passport.authenticate("local")(req, res, function(){
res.redirect("/success");
});
});
});
app.listen(8081, function () {
console.log('ImageViewer listening on port 8081!');
});
JS code:
$scope.delete = function (data) {
if (confirm('Do you really want to delete?')){
$window.location.reload();
$http['delete']('/viewall/' + data._id).success(function() {
$scope.users.splice($scope.users.indexOf(data), 1);
});
}
};
html code:
<tr ng-repeat="user in users | filter:searchBox | orderBy:'+username'">
<td>{{user._id}}</td>
<td>{{user.username}}</td>
<td><button class="btn btn-primary" ng-click="delete(user)">Delete</button></td>
This is the error i got:
DELETE
XHR
http://localhost:8081/viewall/5784919136ccb93d0ba78d4b [HTTP/1.1 404 Not Found 8ms]
But when i run the url of http://localhost:8081/viewall/5784919136ccb93d0ba78d4b and it does give me the data:
{"_id":"5784919136ccb93d0ba78d4b","username":"qs","__v":0}
Anybody can help me? don't know what's with the error404 when i'm able to get the data.
You have no route for '/viewall/:id' with DELETE verb. So you should add route with DELETE verb. like
app.delete('/viewall/:id',function(req,res){
// rest of code here
// assume your model name Account
Account.remove({ _id: req.params.id },function(err,doc) {
if(err) {
return res.status(400).send({msg: 'Error occurred during delete account'});
}
return res.status(200).send({msg: 'Successfully deleted'});
});
}
and you should reload after success in your angular controller. like
$http['delete']('/viewall/' + data._id).then(function(response) {
$scope.users.splice($scope.users.indexOf(data), 1);
$window.location.reload();
});

Passport.js throwing "undefined is not a function" with LocalStrategy

I am implementing local authentication using Passport.js. I have already implemented Github Oauth, which is fine but for some reason the local strategy is failing with the above error. I cannot find any source of the issue so far. I have read other posts but the usual answer is that you should change the require statement to:
var LocalStrategy = require('passport-local').Strategy;
However, I have already done this. Any help would be much appreciated. Here are my files as it stands. I have omitted the github strategy code to focus on the problem strategy:
signin.html:
<div class="signin-bg">
<!-- <div class="modal fade" id="login-modal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true" style="display: none;"> -->
<div class="modal-dialog">
<div class="loginmodal-container">
<h1>Login using Github</h1><br>
<i class="icon-github-sign"></i>
<h3>Or Use your Email</h3>
<form action="/signin" method="post">
<input type="text" name="username" placeholder="Email">
<input type="password" name="password" placeholder="Password">
<input type="submit" name="login" class="login loginmodal-submit" value="Login">
</form>
<div class="login-help">
Register - Forgot Password
</div>
</div>
</div>
routes.js:
var User = require('./models/userModel');
var passport = require('passport');
var authStore = require('./config/authStore');
module.exports = function(app){
app.get('/signin', function(req, res, next){
res.render('signin', { message: req.flash('signinMessage') });
});
app.post('/signin', passport.authenticate('local', {
successRedirect: '/storyBoard',
failureRedirect: '/signin',
failureFlash: true
}));
app.get('/signup', function(req, res){
res.render('signup', { message: req.flash('signupMessage') });
});
app.post('/signup', passport.authenticate('local', {
successRedirect: '/signin',
failureRedirect: '/signup',
failureFlash: true
}));
function isLoggedIn(req, res, next) {
if(req.isAuthenticated()){
return next();
}
res.redirect('/#/signin');
}
};
passport.js
var User = require('../models/userModel.js');
var passport = require('passport');
var GithubStrategy = require('passport-github').Strategy;
var LocalStrategy = require('passport-local').Strategy;
var bcrypt = require('bcrypt');
module.exports = function(passport) {
passport.serializeUser(function(user, done) {
done(null, user.id);
});
passport.deserializeUser(function(id, done) {
User.findUserByGithubId(id, function(err, user) {
user ? done(null, user) : done(err, null);
});
});
passport.use('local', new LocalStrategy({
usernameField: 'email',
passwordField: 'password',
passReqToCallback: true
},
function(req, email, password, done){
process.nextTick(function(){
User.findLocalUser(req.email, function(err, user){
if(err)
return done(err);
if(!user)
return done(null, false, req.flash('signinMessage', 'No user found'));
if(!User.generateHash(password)){
return done(null, false, req.flash('signinMessage', 'Invalid password'));
}
return done(null, user);
});
});
}
));
Well, i'm not sure what you are doing wrong exactly since you not paste all your code, but here is a express silly working sample with passport and connect flash, good luck.
var express = require('express');
var passport = require('passport');
var LocalStrategy = require('passport-local').Strategy;
var flash = require('connect-flash');
// You need session to use connect flash
var session = require('express-session');
var bodyParser = require('body-parser');
var app = express();
app.use(bodyParser.urlencoded({extended: true}));
app.use( session({
saveUninitialized : true,
secret : 'Some Secret' ,
resave : true,
}));
app.use( passport.initialize());
app.use( passport.session());
app.use(flash());
// Authentication
passport.use(
new LocalStrategy(
{},
function(username, password, done) {
// Fake user definition, just a sample.
var user = {name: 'fake', password: 'fake'};
// Here you can put your async authentication method from db
if(user.name === username && user.password === password) {
return done(null, {
username: username
});
}
else {
return done(null, false,{});
}
})
);
passport.serializeUser( function(user, done) {
return done(null, user);
});
passport.deserializeUser( function(user, done) {
return done(null, user);
});
app.get('/', function(req, res) {
var htmlToSend = '';
var error = req.flash('error')[0];
if(error)
htmlToSend += '<div style="background-color:red; width:30%;">' + error + '</div>';
htmlToSend += '<form action="/login" method="post"> \
<input name="username"/> \
<input type="password" name="password"/> \
<button> send \
</form>';
res.send(htmlToSend);
});
app.post('/login', passport.authenticate('local', {
failureRedirect: '/',
successFlash: 'Welcome!',
failureFlash: 'User/Password Invalid!'
}),
function(req, res) {
res.send('Loged In as '+ req.user.username);
});
app.listen(3000, function() {
console.log('started');
});

Categories

Resources