Advertisement
Guest User

Untitled

a guest
Apr 18th, 2014
51
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.36 KB | None | 0 0
  1. authorizeOwnership(req, res)
  2. .then(function() {
  3. // do stuff
  4. res.send(200, "Yay");
  5. });
  6.  
  7. function confirmOwnership(resourceId, userId) {
  8. // SequelizeJS... returns a bluebird promise
  9. return Resource.find({
  10. where: {id: resourceId, userId: userId}
  11. })
  12. .then(function(resource) {
  13. if(!resource) {
  14. return null; // no match for this resource id + user id
  15. } else {
  16. return resource;
  17. }
  18. });
  19. }
  20.  
  21. function authorizeOwnership(req, res) {
  22. var rid = parseInt(req.params.rid, 10),
  23. userId = parseInt(req.authInfo.userid, 10);
  24.  
  25. return new Promise(function(resolve, reject) {
  26. confirmOwnership(rid, userId)
  27. .then(function(resource) {
  28. if(resource === null) {
  29. res.send(403, "Forbidden");
  30. // Note: we don't resolve; outer handler will not be called
  31. } else {
  32. resolve(resource);
  33. }
  34. })
  35. .catch(function(err) {
  36. console.log(err);
  37. res.send(500, "Server error");
  38. // Note: we don't resolve; outer handler will not be called
  39. });
  40. });
  41. }
  42.  
  43. // probably shouldn't send the response to authorizeOwnership but use it externally
  44. // to be fair, should probably not take req either, but rid and userid
  45. var authorizeOwnership = Promise.method(function(req) {
  46. var rid = Number(req.params.rid),
  47. userId = Number(req.authInfo.userid;
  48. return confirmOwnership(rid, userId); // return the promise
  49. });
  50. });
  51.  
  52. function ServerError(code,reason){
  53. this.name = "ServerError";
  54. this.message = reason;
  55. this.code = code;
  56. Error.captureStackTrace(this); // capture stack
  57. }
  58. var confirmOwnership = Promise.method(function(resourceId, userId) {
  59. // SequelizeJS... returns a bluebird promise
  60. return Resource.find({
  61. where: {id: resourceId, userId: userId}
  62. })
  63. .then(function(resource) {
  64. if(!resource) {
  65. throw new ServerError(403,"User not owner"); // promises are throw safe
  66. }
  67. return resource;
  68. });
  69. });
  70.  
  71. app.post("/foo",function(req,res){
  72. authorizeOwnership(req).then(function(){
  73. res.send(200, "Owner Yay!");
  74. }).catch(ServerError,function(e){
  75. if(e.code === 403) return res.send(403,e.message);
  76. return res.send(500,"Internal Server Error");
  77. });
  78. });
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement