isAuthenticated() function not working node.js passport

≡放荡痞女 提交于 2019-12-13 17:14:45

问题


I am creating online course application and I want only authenticated users to see the course details and course lecture. I am using local strategy of passport authentication for user authentication. I added isAuthenticated in my routes, however, still the unauthenticated users can view the video lectures. Here is my routes file. file name:- courses.server.routes.js

'use strict';

/**
* Module dependencies
*/
var coursesPolicy = require('../policies/courses.server.policy'),
courses = require('../controllers/courses.server.controller');
var passport = require('passport');

 var isAuthenticated = function(req, res, next) {
 // if user is authenticated in the session, call the next() to call the next request handler
 // Passport adds this method to request object. A middleware is allowed to add properties to
 // request and response objects
 if (req.isAuthenticated())
     return next();
 // if the user is not authenticated then redirect the user to the login page
 res.redirect('/');
};

module.exports = function (app) {
// Courses collection routes
app.route('/api/courses').all(coursesPolicy.isAllowed)
.get(courses.list)
.post(courses.create);

// Single course routes
app.route('/api/courses/:courseId', isAuthenticated).all(coursesPolicy.isAllowed)
.get(courses.read)
.put(courses.update)
.delete(courses.delete);

// Finish by binding the course middleware
app.param('courseId', courses.courseByID);
};

Here is my route controller file. file name:- courses.server.controller.js

'use strict';

/**
* Module dependencies
*/
var path = require('path'),
mongoose = require('mongoose'),
Course = mongoose.model('Course'),
errorHandler = require(path.resolve('./modules/core/server/controllers/errors.server.controller'));
var passport = require('passport');

/**
* Create an course
*/
exports.create = function (req, res) {
var course = new Course(req.body);
course.user = req.user;

course.save(function (err) {
if (err) {
  return res.status(422).send({
    message: errorHandler.getErrorMessage(err)
  });
} else {
  res.json(course);
}
});
};

/**
* Show the current course
*/
exports.read = function (req, res) {
// convert mongoose document to JSON
var course = req.course ? req.course.toJSON() : {};

// Add a custom field to the Course, for determining if the current User is the "owner".
// NOTE: This field is NOT persisted to the database, since it doesn't exist in the Course model.
course.isCurrentUserOwner = !!(req.user && course.user && course.user._id.toString() === req.user._id.toString());

console.log('course value is: ' + course);
console.log('video lecture embed value is: ' + course.courseLecture.lecture_video);

res.json(course);
};

/**
* Update an course
*/
exports.update = function (req, res) {
var course = req.course;

course.title = req.body.title;
course.content = req.body.content;
course.courseLecture.lecture_video =  req.body.courseLecture.lecture_video;
console.log('course lecture video url is: ' + req.body.courseLecture.lecture_video);
course.save(function (err) {
if (err) {
  return res.status(422).send({
    message: errorHandler.getErrorMessage(err)
  });
} else {
  res.json(course);
}
});
};

/**
* Delete an course
*/
exports.delete = function (req, res) {
var course = req.course;

course.remove(function (err) {
if (err) {
  return res.status(422).send({
    message: errorHandler.getErrorMessage(err)
  });
} else {
  res.json(course);
}
});
};

/**
* List of Courses
*/
exports.list = function (req, res) {
Course.find().sort('-created').populate('user',  'displayName').exec(function (err, courses) {
if (err) {
  return res.status(422).send({
    message: errorHandler.getErrorMessage(err)
  });
} else {
  res.json(courses);
}
});
};

/**
* Course middleware
*/
exports.courseByID = function (req, res, next, id) {

if (!mongoose.Types.ObjectId.isValid(id)) {
return res.status(400).send({
  message: 'Course is invalid'
});
}

Course.findById(id).populate('user', 'displayName').exec(function (err, course) {
if (err) {
  return next(err);
} else if (!course) {
  return res.status(404).send({
    message: 'No course with that identifier has been found'
  });
}
req.course = course;
next();
});
};

I'm not able to figure out, whats going wrong here.


回答1:


Call isAuthenticated function from http verb means from get, post, patch, delete

like:

app.route('/api/courses/:courseId')
 .get(isAuthenticated, courses.read)

also isAuthenticated can be write in another file and use it from your route

Can see this example



来源:https://stackoverflow.com/questions/41818146/isauthenticated-function-not-working-node-js-passport

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!