Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- authorizeOwnership(req, res)
- .then(function() {
- // do stuff
- res.send(200, "Yay");
- });
- function confirmOwnership(resourceId, userId) {
- // SequelizeJS... returns a bluebird promise
- return Resource.find({
- where: {id: resourceId, userId: userId}
- })
- .then(function(resource) {
- if(!resource) {
- return null; // no match for this resource id + user id
- } else {
- return resource;
- }
- });
- }
- function authorizeOwnership(req, res) {
- var rid = parseInt(req.params.rid, 10),
- userId = parseInt(req.authInfo.userid, 10);
- return new Promise(function(resolve, reject) {
- confirmOwnership(rid, userId)
- .then(function(resource) {
- if(resource === null) {
- res.send(403, "Forbidden");
- // Note: we don't resolve; outer handler will not be called
- } else {
- resolve(resource);
- }
- })
- .catch(function(err) {
- console.log(err);
- res.send(500, "Server error");
- // Note: we don't resolve; outer handler will not be called
- });
- });
- }
- // probably shouldn't send the response to authorizeOwnership but use it externally
- // to be fair, should probably not take req either, but rid and userid
- var authorizeOwnership = Promise.method(function(req) {
- var rid = Number(req.params.rid),
- userId = Number(req.authInfo.userid;
- return confirmOwnership(rid, userId); // return the promise
- });
- });
- function ServerError(code,reason){
- this.name = "ServerError";
- this.message = reason;
- this.code = code;
- Error.captureStackTrace(this); // capture stack
- }
- var confirmOwnership = Promise.method(function(resourceId, userId) {
- // SequelizeJS... returns a bluebird promise
- return Resource.find({
- where: {id: resourceId, userId: userId}
- })
- .then(function(resource) {
- if(!resource) {
- throw new ServerError(403,"User not owner"); // promises are throw safe
- }
- return resource;
- });
- });
- app.post("/foo",function(req,res){
- authorizeOwnership(req).then(function(){
- res.send(200, "Owner Yay!");
- }).catch(ServerError,function(e){
- if(e.code === 403) return res.send(403,e.message);
- return res.send(500,"Internal Server Error");
- });
- });
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement