user.js 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. var models = require('../models');
  2. var User = models.User;
  3. var Note = models.Note;
  4. var userSafeParams = ['id', 'name', 'username', 'bio', 'twitter_handle', 'site'];
  5. module.exports = function(app){
  6. app.get('/users', function(req, res){
  7. models.sequelize.sync().on('success', function(){
  8. User.findAll({attributes: userSafeParams}).success(function(users){
  9. res.json(users);
  10. })
  11. });
  12. });
  13. app.put('/users', function(req, res){
  14. var param;
  15. var updateParams = {};
  16. var userId = parseInt(req.param('id'));
  17. // Return an 401 aunauthorized if a user tries to editor another user's profile
  18. if(!req.user || req.user.id !== userId) {
  19. res.status(401);
  20. res.json({error: "You are not authorized to edit this user"});
  21. return
  22. }
  23. models.sequelize.sync().on('success', function(){
  24. User.find({where: {id: userId}}).success(function(user){
  25. for(var i=0, l = userSafeParams.length; i < l; i++ ){
  26. param = userSafeParams[i];
  27. updateParams[param] = req.param(param);
  28. }
  29. user.updateAttributes(updateParams).success(function(){
  30. res.json(user)
  31. })
  32. });
  33. });
  34. });
  35. app.get('/users/:id', function(req, res){
  36. var userId = parseInt(req.params.id, 10);
  37. if(!userId) {
  38. res.json({});
  39. return;
  40. }
  41. models.sequelize.sync().on('success', function(){
  42. User.find({where: {id: userId}, attributes: userSafeParams, include: [Note]}).success(function(user){
  43. res.json(user);
  44. })
  45. });
  46. });
  47. };