I'm trying to get a "success" or "failure" response from my server to client. The server is being implemented in node.js in express framework and the client in angularjs.
Here is the server side node.js part:
connection.connect();
/* GET home page. */
router.get('/', function(req, res, next) {
res.sendFile(path.join(__dirname, '../', 'views', 'login.html'));
});
router.get('/login', function(req,res)
{
console.log("Username:"+req.query.username);
console.log("Password:"+req.query.password);
var user = req.query.username;
var pass = req.query.password
connection.query("select * from user where login_name = ?", user, function(err, rows, fields) {
if (!err){
if(user==rows[0].login_name && pass==rows[0].pass){
console.log("success");
res.json({status: 200});
}
}
else
console.log('Error while performing Query.', err);
});
and here is the angularjs part:
<form name="login">
<div class="login" ng-app="loginPage" ng-controller="loginController">
<input type="text" placeholder="username" ng-model="uname" name="userid"><br>
<input type="password" placeholder="password" ng-model="pword" name="pswrd"><br>
<!--<input type="button" ng-click="login();" onclick="check(this.form)" value="Login"/>-->
<button ng-click="login();">Login</button>
</div>
</form>
<script language="javascript">
var app = angular.module('loginPage', []);
app.controller('loginController', function($scope, $http) {
console.log("inside controller");
$scope.login = function() {
console.log("inside the login function");
console.log($scope.uname);
var verify = $http({
method: 'GET',
url: '/login' +
'',
params: { username: $scope.uname, password: $scope.pword }
}).then(
function successful(response) {
$scope.theResponse = response.data;
window.open("./team_list.html")
}, function unsuccessful(response) {
alert('Wrong username/password.');
$scope.theResponse = response.data;
});
}
})
</script>
I try to type in "test" for username and "test" for pw on the login page on the browser because that is what I have entered in my sql database. Specifically I'm not sure why the login page doesn't link to the team_list page that I have specified the path for.
I'm not really sure why it's not working. If I'm supposed to be using json differently, I would appreciate more help because I am not very familiar with it.
The order of the routing in the NodeJS side is wrong. The /login should come first. Else everything will be served by the '/' route.
router.get('/login', function(req, res) {
console.log("Username:" + req.query.username);
console.log("Password:" + req.query.password);
var user = req.query.username;
var pass = req.query.password
connection.query("select * from user where login_name = ?", user, function(err, rows, fields) {
if (!err) {
if (user == rows[0].login_name && pass == rows[0].pass) {
console.log("success");
res.json({
status: 200
});
}
} else
console.log('Error while performing Query.', err);
});
/* GET home page. */
router.get('/', function(req, res, next) {
res.sendFile(path.join(__dirname, '../', 'views', 'login.html'));
});
Check your console you can even figure out the problem from there.
Shortcuts for console
shortcut keys for opening different browsers's Console
do it like this :
connection.query("select * from user where login_name = ?", user, function(err, rows, fields) {
if (!err){
if(user==rows[0].login_name && pass==rows[0].pass){
console.log("success");
res.send(200);
}
}
else{
console.log('Error while performing Query.', err);
res.send(401);
}
});
Actually, you should send Error or Success code like 200 or 401.
And use
res.send(ErrorCode) or res.sendStatus(ErrorCode) and it'll autmatically do it for you at client side like below :
<script language="javascript">
var app = angular.module('loginPage', []);
app.controller('loginController', function($scope, $http, $window) {
console.log("inside controller");
$scope.login = function() {
console.log("inside the login function");
console.log($scope.uname);
$http.get('/login').then(function (success) {
$window.alert('Success');
}, function (error) {
$window.alert('Wrong username/password.');
});
}
});
</script>
Related
I saw a demo of an authentication using angular js and JWS auth02 metodologĂa and I refocterd it a little...
I am using express (node js) on the server side to define myApp.
my question is this - on the client side I am doing this http GET call:
$http({url: '/api/restricted', method: 'GET'})
.success(function (data, status, headers, config) {
$scope.message = $scope.message + ' ' + data.name;
})
.error(function (data, status, headers, config) {
alert(data);
});
on the server side I am getting the id from the http GET request:
app.get('/api/restricted', function (req, res) {
res.json({
name: req.user.id
});
});
and it is working.. the only problem is that I don't see where I defined a GET request with a user entity... all I see is that the GET http request get a method and a url:
$http({url: '/api/restricted', method: 'GET'})
so where is this magic name: req.user.id
is coming from?
Thanks...
more of the code (may be relavent...):
index. html
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<title>Angular Authentication</title>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.5.8/angular.min.js"></script>
<script src="./auth.client.js"></script>
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/angularjs/1.5.8/angular-cookies.js"></script>
</head>
<body ng-app="myApp">
<div ng-controller="UserCtrl">
<span ng-show="isAuthenticated">{{welcome}}</span>
<form ng-show="!isAuthenticated" ng-submit="submit()">
<input ng-model="user.username" type="text" name="user" placeholder="Username" />
<input ng-model="user.password" type="password" name="pass" placeholder="Password" />
<input type="submit" value="Login" />
</form>
<div>{{error}}</div>
<div ng-show="isAuthenticated">
<a ng-click="callRestricted()" href="">Shh, this is private!</a>
<br>
<div>{{message}}</div>
<a ng-click="logout()" href="">Logout</a>
</div>
</div>
</body>
</html>
client side
myApp.controller('UserCtrl', ["$scope", "$http","$window","$cookies", function ($scope, $http, $window,$cookies) {
$scope.callRestricted = function () {
$http({url: '/api/restricted', method: 'GET'})
.success(function (data, status, headers, config) {
$scope.message = $scope.message + ' ' + data.name;
})
.error(function (data, status, headers, config) {
alert(data);
});
};
myApp.factory('authInterceptor',["$rootScope", "$q","$cookies",
function ($rootScope, $q,$cookies) {
return {
request: function (config) {
config.headers = config.headers || {};
if ($cookies.get('token')) {
config.headers.Authorization = 'Bearer ' + $cookies.get('token');
}
return config;
},
responseError: function (rejection) {
if (rejection.status === 401) {
// handle the case where the user is not authenticated
}
return $q.reject(rejection);
}
};
}]);
myApp.config(function ($httpProvider) {
$httpProvider.interceptors.push('authInterceptor');
});
and this code on the server side:
var express = require('express');
var bodyParser = require('body-parser');
var jwt = require('jsonwebtoken');
var expressJwt = require('express-jwt');
var secret = 'ssasDSA223Sasdas2sdsa23123dvxcgyew231';
var app = express();
// We are going to protect /api routes with JWT
app.use('/api', expressJwt({secret: secret}));
app.use(bodyParser.json());
app.use('/', express.static(__dirname + '/'));
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#gmail.com',
id: 333333333
};
// We are sending the profile inside the token
var token = jwt.sign(profile, secret, { expiresInMinutes: 60*5 });
res.json({ token: token });
});
app.get('/api/restricted', function (req, res) {
res.json({
name: req.user.id
});
});
app.listen(8080, function () {
console.log('listening on http://127.0.0.1:8080');
});
It appears that you are using the express-jwt library. Per the documentation, the express-jwt library is Middleware that validates JsonWebTokens and sets req.user.
This occurs when the middleware is invoked on this line: app.use('/api', expressJwt({secret: secret}));
Common way to set Authorization data "accessToken" in angular is on setting http headers like
$http.defaults.headers.common['Token'] = token
find this in app.run method on angular app
And the server side recognize the user by the access token provided in the headers of he request
I am trying to retrieve the current user session then send the data to the view but in the view there is nothing showing i event check the database and there is an active session with all the info. I tried logging the user out and started afresh. Here is my code.
Login works well
router.post('/', jsonParser, function (req, res) {
if (!req.body || req.body.length === 0) {
console.log('request body not found');
return res.sendStatus(400);
}
var username = req.body.username;
var password = req.body.password;
Parse.User.logIn(username, password, {
success: function (user) {
res.redirect('/');
console.log(JSON.stringify(user));
},
error: function (user, error) {
}
});
});
Retrieve current user in the index.js
var username;
/* GET home page. */
router.get('/', function (req, res, next) {
var currentUser = Parse.User.current();
if (currentUser){
currentUser.fetch().then(function (fetchedUser) {
this.username = fetchedUser.getUsername();
}, function (error) {
console.log(error.message);
});
}
res.render('index', {title: 'Home', user: this.username});
});
module.exports = router;
When i try to display the username h1=user there is nothing shown.
You can use arrow functions for access to outer context(this):
currentUser.fetch().then(fetchedUser => {
this.username = fetchedUser.getUsername();
}, error => console.error(error));
But, it can't to help you, because you tried to render before user was fetched. You need to wait while fetch finished.
if (currentUser) {
currentUser.fetch().then(function(fetchedUser) {
res.render('index', {title: 'Home', user: fetchedUser.getUsername()});
}).catch(function(err) {
console.error(err);
// may be render something with err.message here
});
} else {
// render without user
res.render('index', {title: 'Home', user: null});
}
Not sure whether you are getting value for this.username
/* GET home page. */
router.get('/', function (req, res, next) {
var currentUser = Parse.User.current();
var that = this;
if (currentUser){
currentUser.fetch().then(function (fetchedUser) {
that.username = fetchedUser.getUsername();
}, function (error) {
console.log(error.message);
});
}
res.render('index', {title: 'Home', user: that.username});
});
module.exports = router;
Store a reference of this and then try to display it using res.render
I am currently trying to set up an admin role in order to access a simple admin page using the following documentation provided via : connect-roles
I ave been banging my head against it for a while and am still lost on how to set a role E.G As of right now am pulling a admin value out of the DB and storing it in a global var for the time being but I have no idea how to use that with connect-roles say to only allow access to my admin page for a specific user.
Can anyone clarify or show an example on how to do this/some guidance as I documentation didn't help me to ensure access to a web page only if the user is an admin?
Ave posted some of the code kinda showing what it looks like at the moment.
Code
var admin = 'Admin';
var mysql = require('mysql');
var connection = mysql.createConnection({
host : 'localhost',
user : 'root',
password : '',
database : 'test'
});
var passport = require('passport');
var ConnectRoles = require('connect-roles');
var roles = new ConnectRoles();
var passportLocal = require('passport-local');
app.use(passport.initialize());
app.use(passport.session());
app.use(roles.middleware());
passport.use(new passportLocal.Strategy(function (username, password, done) {
connection.query({
sql : 'SELECT * from `userman_users` WHERE `username`= ?AND`password` = sha1(?)',
timeout : 40000, // 40s
values : [username, password]
}, function (error, results, rows) {
if (results.length > 0) {
response = "Success";
} else {
console.log('Error while performing Query.');
response = "Failed";
}
if (response === "Success") {
done(null, {
id : username
});
} else if (response === "Failed") {
done(null, null);
}
});
})
);
passport.serializeUser(function (user, done) {
done(null, user.id);
});
passport.deserializeUser(function (id, done) {
done(null, {
id : id
});
});
roles.use(function (req, action) {
if (!req.isAuthenticated()) return action === 'access home page';
})
roles.use(function (req) {
if (req.user.role === 'admin') {
return true;
}
});
app.get('/', redirectToIndexIfLoggedIn, function (req, res) {
res.render('login');
});
app.get('/index', checkLoggedIn, function (req, res) {
res.render('index', {
isAuthenticated : req.isAuthenticated(),
user : req.user
});
});
app.get('/admin', user.can('access admin page'), function (req, res) {
res.render('admin');
});
function checkLoggedIn(req, res, next) {
if (req.isAuthenticated())
return next();
res.redirect('/');
}
this is an example:
var express = require('express');
...
var passport = require('passport');
var LocalStrategy = require('passport-local');
var ConnectRoles = require('connect-roles');
...
var app = express();
//===============PASSPORT=================
// Passport session setup.
passport.serializeUser(function(user, done) {
console.log("serializing " + user.username);
done(null, user);
});
passport.deserializeUser(function(obj, done) {
console.log("deserializing " + obj);
// simulate an admin user
obj.role = obj.username == 'admin' ? 'admin' : 'user';
done(null, obj);
});
...
//===============CONNECTION RULES=================
var user = new ConnectRoles({
failureHandler: function (req, res, action) {
// optional function to customise code that runs when
// user fails authorisation
var accept = req.headers.accept || '';
res.status(403);
if (~accept.indexOf('html')) {
res.render('access-denied', {action: action});
} else {
res.send('Access Denied - You don\'t have permission to: ' + action);
}
}
});
...
app.use(passport.initialize());
app.use(passport.session());
app.use(user.middleware());
//anonymous users can only access the home page
//returning false stops any more rules from being
//considered
user.use(function (req, action) {
if (!req.isAuthenticated()) return action === 'access home page';
});
//users logged can access to public pages
user.use(function(req, action){
if(req.isAuthenticated() && action != 'access private page' && action != 'access admin page')
return true;
});
//moderator users can access private page, but
//they might not be the only ones so we don't return
//false if the user isn't a moderator
user.use('access private page', function (req) {
console.log('access private page');
if (req.user.role === 'moderator') {
return true;
}
});
//admin users can access all pages
user.use(function (req) {
if (req.user.role === 'admin') {
return true;
}
});
...
/* GET home page. */
app.get('/', user.can('access home page'), function(req, res, next) {
res.render('index', { title: 'Express' });
});
//displays our signup page
app.get('/signin', function(req, res){
res.render('signin');
});
//sends the request through our local signup strategy, and if successful takes user to homepage, otherwise returns then to signin page
app.post('/local-reg', passport.authenticate('local-signup', {
successRedirect: '/',
failureRedirect: '/signin'
})
);
//sends the request through our local login/signin strategy, and if successful takes user to homepage, otherwise returns then to signin page
app.post('/login', passport.authenticate('local-signin', {
successRedirect: '/',
failureRedirect: '/signin'
})
);
// Simple route middleware to ensure user is authenticated.
app.use(function(req, res, next) {
if (req.isAuthenticated()) { return next(); }
req.session.error = 'Please sign in!';
res.redirect('/signin');
});
//logs user out of site, deleting them from the session, and returns to homepage
app.get('/logout', function(req, res){
var name = req.user.username;
console.log("LOGGIN OUT " + req.user.username)
req.logout();
res.redirect('/');
req.session.notice = "You have successfully been logged out " + name + "!";
});
app.get('/private', user.can('access private page'), function (req, res) {
res.render('private');
});
app.get('/admin', user.can('access admin page'), function (req, res) {
res.render('admin');
});
app.use('/users', users);
....
module.exports = app;
With connect-rules you define the rules do you want to use (user.use in this case). If you pass an action as first parameter the strategy is only used if the action passed in the function is equal to it. Then you trigger the rules in the routes with user.can passing the action. In this example I define an extra filter strategy to grant access to users that are logged and request routes that are not marked with admin or moderator privileges e.g
/* GET home page. */
app.get('/', user.can('access home page'), function(req, res, next) {
res.render('index', { title: 'Express' });
});
After the user is logged, we need to have another strategy in case the user isn't admin or moderator.
U can use framework like sailsJS and npm module sails-generate-auth
And after setup, use your own middleware to block routes
//allow admin only localhost:PORT/admin at policies.js
'admin': ['passport', 'sessionAuth', 'isAdmin'],
'*': ['passport', 'sessionAuth'],
//isAdmin policy
module.exports = function(req, res, next) {
// User is allowed, proceed to the next policy,
// or if this is the last policy, the controller
if (req.user.role == 'admin') {
return next();
}
// User is not allowed
return res.forbidden('You are not permitted to perform this action.');
};
Using the following logic I was able to have admin functionality based on value within the DB:
app.get('/admin', function (req, res) {
connection.query({
sql : 'SELECT role from `auth_users` WHERE `username`= ?',
timeout : 40000, // 40s
values : [req.user['id']]
}, function (error, results, rows) {
if (results[0]['role'] === "admin") {
admin = (results[0]['role']);
res.render('admin', {
isAuthenticated : req.isAuthenticated(),
user : req.user
});
} else {
admin = "";
res.redirect('/index');
}
})
});
I've just started with meanjs. When I've taken a look at it server side module user profile controller, I find that mongoose model User is available in req object.
From where it has got added in req object?
Refer the code below, I wants to understand var user = req.user;, How user is added in req object?
'use strict';
/**
* Module dependencies.
*/
var _ = require('lodash'),
errorHandler = require('../errors.server.controller.js'),
mongoose = require('mongoose'),
passport = require('passport'),
User = mongoose.model('User');
/**
* Update user details
*/
exports.update = function(req, res) {
// Init Variables
var user = req.user;
var message = null;
// For security measurement we remove the roles from the req.body object
delete req.body.roles;
if (user) {
// Merge existing user
user = _.extend(user, req.body);
user.updated = Date.now();
user.displayName = user.firstName + ' ' + user.lastName;
user.save(function(err) {
if (err) {
return res.status(400).send({
message: errorHandler.getErrorMessage(err)
});
} else {
req.login(user, function(err) {
if (err) {
res.status(400).send(err);
} else {
res.json(user);
}
});
}
});
} else {
res.status(400).send({
message: 'User is not signed in'
});
}
};
/**
* Send User
*/
exports.me = function(req, res) {
res.json(req.user || null);
};
In meanjs app.param([name], callback) is used, whenever a route with some id like articeId in parameter is accessed, app.param([name], callback) middleware is triggered. In meanjs it sets req.article like this.
app.param('articleId', articles.articleByID);
and in articleByID
exports.articleByID = function(req, res, next, id) {
if (!mongoose.Types.ObjectId.isValid(id)) {
return res.status(400).send({
message: 'Article is invalid'
});
}
Article.findById(id).populate('user', 'displayName').exec(function(err, article) {
if (err) return next(err);
if (!article) {
return res.status(404).send({
message: errorHandler.getErrorMessage(err)
});
}
req.article = article;
next();
});
};
more on app.param see http://expressjs.com/api.html#app.param
Passport’s authentication middleware sets req.user upon successful login.
See http://passportjs.org/guide/authenticate/.
I'm working on creating a CRUD todo app using AngularJS, Node, Express, and MongoDB. I've got all parts figured out except for update part. I'm not really sure how to implement that or what the code might look like. Particularly the AngularJS stuff (express routing isn't so bad). I'd like it if I could update by ID. Was hoping to get some input.
function mainController($scope, $http) {
$scope.formData = {};
// when landing on the page, get all todos and show them
$http.get('/api/todos')
.success(function(data) {
$scope.todos = data;
})
.error(function(data) {
console.log('Error: ' + data);
});
// when submitting the add form, send the text to the node API
$scope.createTodo = function() {
$http.post('/api/todos', $scope.formData)
.success(function(data) {
$('input').val('');
$scope.todos = data;
})
.error(function(data) {
console.log('Error: ' + data);
});
};
// delete a todo after checking it
$scope.deleteTodo = function(id) {
$http.delete('/api/todos/' + id)
.success(function(data) {
$scope.todos = data;
})
.error(function(data) {
console.log('Error: ' + data);
});
};
Here are the routes just in case that matters.
app.get('/api/todos', function(req, res) {
// use mongoose to get all todos in the database
Todo.find(function(err, todos) {
// if there is an error retrieving, send the error. nothing after res.send(err) will execute
if (err)
res.send(err)
res.json(todos); // return all todos in JSON format
});
});
// create todo and send back all todos after creation
app.post('/api/todos', function(req, res) {
// create a todo, information comes from AJAX request from Angular
Todo.create({
text : req.body.text,
done : false
}, function(err, todo) {
if (err)
res.send(err);
// get and return all the todos after you create another
Todo.find(function(err, todos) {
if (err)
res.send(err)
res.json(todos);
});
});
});
// delete a todo
app.delete('/api/todos/:todo_id', function(req, res) {
Todo.remove({
_id : req.params.todo_id
}, function(err, todo) {
if (err)
res.send(err);
// get and return all the todos after you create another
Todo.find(function(err, todos) {
if (err)
res.send(err)
res.json(todos);
});
});
});
// application -------------------------------------------------------------
app.get('*', function(req, res) {
res.sendfile('./public/index.html'); // load the single view file (angular will handle the page changes on the front-end)
});
};
There are 2 ways - you can use $http.put bu you can also use $resource. I hope that this will help you
index.html
<!DOCTYPE html>
<html ng-app="myApp">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.1/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.1/angular-resource.min.js"></script>
<script type="text/javascript" src="angularjs_app.js"></script>
</head>
<body>
<div ng-controller="MainController">
<form name="todoForm" novalidate>
<label>Id</label>
<input type="text" name="_id" ng-model="editTodo._id">
<br/>
<label>Subject</label>
<input type="text" name="subject" ng-model="editTodo.subject">
<br/>
<label>Description</label>
<input type="text" name="desc" ng-model="editTodo.desc">
<br/>
<button ng-click="updateTodo()">Update Todo</button>
</form>
</div>
</body>
</html>
angularjs_app.js (1 Way)
var myApp = angular.module('myApp', []);
myApp.controller('MainController', ['$scope',
function($scope) {
$scope.updateTodo = function() {
$http.put('/api/todos/' + $scope.editTodo._id, $scope.editTodo).success(function() {
alert('Todo updated');
});
// Or you can try
// $http.put('/api/todos/' + $scope.editTodo._id, {"todo": $scope.editTodo})
// .success(function(data, status, headers, config){
// $scope.editTodo = data.todo;
// })
// .error(function(data, status, headers, config){
// alert(data.error_message);
// });
};
}]);
angularjs_app.js (2 Way)
var myApp = angular.module('myApp', ['ngResource', 'myAppServices']);
myApp.controller('MainController', ['$scope', 'TodoFactory',
function($scope, TodoFactory) {
$scope.updateTodo = function() {
TodoFactory.update($scope.editTodo, function() {
alert('Todo updated');
});
};
}]);
var myAppServices = angular.module('myAppServices', ['ngResource']);
myAppServices.factory('TodoFactory', ['$resource',
function($resource) {
return $resource('/api/todos/:todoId', {}, {
update: {method:'PUT', params: {todoId: '#_id'}}
});
}
]);
nodejs_server.js
var express = require('express');
var path = require('path');
var http = require('http');
var todos = require('./routes_todos');
var app = express();
app.configure(function() {
app.set('port', process.env.PORT || 3000);
app.use(express.logger('dev')); /* 'default', 'short', 'tiny', 'dev' */
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(express.static(path.join(__dirname, 'public')));
});
app.get('/api/todos', todos.findAll);
app.get('/api/todos/:id', todos.findById);
app.post('/api/todos', todos.add);
app.put('/api/todos/:id', todos.update);
app.delete('/api/todos/:id', todos.remove);
http.createServer(app).listen(app.get('port'), function() {
console.log("Express server listening on port " + app.get('port'));
});
routes_todos.js
var mongo = require('mongodb');
var Server = mongo.Server;
var Db = mongo.Db;
var BSON = mongo.BSONPure;
var server = new Server('localhost', 27017, {auto_reconnect: true});
db = new Db('todosdb', server);
db.open(function(err, db) {
if (!err) {
console.log("Connected to 'todosdb' database");
db.collection('todos', {strict: true}, function(err, collection) {
if (err) {
console.log("Error todos does not exist");
}
});
}
});
exports.findAll = function(req, res) {
db.collection('todos', function(err, collection) {
collection.find().toArray(function(err, items) {
console.log('todos send from DB');
res.send(items);
});
});
};
exports.findById = function(req, res) {
var id = req.params.id;
console.log('Retrieving todo: ' + id);
db.collection('todos', function(err, collection) {
collection.findOne({'_id': new BSON.ObjectID(id)}, function(err, item) {
res.send(item);
});
});
};
exports.add = function(req, res) {
var todo = req.body;
console.log('Adding todo: ' + JSON.stringify(todo));
db.collection('todos', function(err, collection) {
collection.insert(todo, {safe: true}, function(err, result) {
if (err) {
res.send({'error': 'An error has occurred'});
} else {
console.log('Success: ' + JSON.stringify(result[0]));
res.send(result[0]);
}
});
});
};
exports.update = function(req, res) {
var id = req.params.id;
var todo = req.body;
console.log('Updating todo: ' + id);
console.log(JSON.stringify(todo));
delete todo._id;
db.collection('todos', function(err, collection) {
collection.update({'_id': new BSON.ObjectID(id)}, todo, {safe: true}, function(err, result) {
if (err) {
console.log('Error updating todo: ' + err);
res.send({'error': 'An error has occurred'});
} else {
console.log('' + result + ' document(s) updated');
res.send(todo);
}
});
});
};
exports.remove = function(req, res) {
var id = req.params.id;
console.log('Removing todo: ' + id);
db.collection('todos', function(err, collection) {
collection.remove({'_id': new BSON.ObjectID(id)}, {safe: true}, function(err, result) {
if (err) {
res.send({'error': 'An error has occurred - ' + err});
} else {
console.log('' + result + ' document(s) removed');
res.send(req.body);
}
});
});
};