Created
February 11, 2014 22:23
-
-
Save techslides/8945495 to your computer and use it in GitHub Desktop.
Updating a post with authentication and user validation
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| //Update a post | |
| m.Put("/posts/:id", binding.Bind(Post{}), func(args martini.Params, post Post, r render.Render, authuser sessionauth.User) { | |
| //capture passed in parameters from Ajax call | |
| var newTitle = post.Title | |
| var newBody = post.Body | |
| //retrieve the post to retrieve original owner | |
| err = dbmap.SelectOne(&post, "select * from posts where post_id=?", args["id"]) | |
| //simple DB error check | |
| if err != nil { | |
| newmap := map[string]interface{}{"message":"Something went wrong."} | |
| r.JSON(400, newmap) | |
| } else { | |
| //owner check | |
| if(authuser.UniqueId() == post.UserId){ | |
| //assign new values to the retrieved post | |
| post.Title=newTitle | |
| post.Body=newBody | |
| //update the post | |
| count, err := dbmap.Update(&post) | |
| checkErr(err, "Update failed") | |
| if count == 1 { | |
| newmap := map[string]interface{}{"responseText":"success"} | |
| r.JSON(200, newmap) | |
| } else { | |
| newmap := map[string]interface{}{"responseText":"error"} | |
| r.JSON(400, newmap) | |
| } | |
| } else { | |
| newmap := map[string]interface{}{"responseText":"You are not allowed to modify this resource."} | |
| r.JSON(403, newmap) | |
| } | |
| } | |
| }) |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Learn more about this code here: http://techslides.com/martini-app-with-ajax-json-and-user-sessions/