github.com/bitcubate/cryptojournal@v1.2.5-0.20171102134152-f578b3d788ab/src/comments/actions/update.go (about) 1 package commentactions 2 3 import ( 4 "net/http" 5 6 "github.com/fragmenta/auth/can" 7 "github.com/fragmenta/mux" 8 "github.com/fragmenta/server" 9 "github.com/fragmenta/view" 10 11 "github.com/bitcubate/cryptojournal/src/comments" 12 "github.com/bitcubate/cryptojournal/src/lib/session" 13 ) 14 15 // HandleUpdateShow renders the form to update a comment. 16 func HandleUpdateShow(w http.ResponseWriter, r *http.Request) error { 17 18 // Fetch the params 19 params, err := mux.Params(r) 20 if err != nil { 21 return server.InternalError(err) 22 } 23 24 // Find the comment 25 comment, err := comments.Find(params.GetInt(comments.KeyName)) 26 if err != nil { 27 return server.NotFoundError(err) 28 } 29 30 // Authorise update comment 31 currentUser := session.CurrentUser(w, r) 32 err = can.Update(comment, currentUser) 33 if err != nil { 34 return server.NotAuthorizedError(err) 35 } 36 37 // Render the template 38 view := view.NewRenderer(w, r) 39 view.AddKey("currentUser", currentUser) 40 view.AddKey("comment", comment) 41 return view.Render() 42 } 43 44 // HandleUpdate handles the POST of the form to update a comment 45 func HandleUpdate(w http.ResponseWriter, r *http.Request) error { 46 47 // Fetch the params 48 params, err := mux.Params(r) 49 if err != nil { 50 return server.InternalError(err) 51 } 52 53 // Find the comment 54 comment, err := comments.Find(params.GetInt(comments.KeyName)) 55 if err != nil { 56 return server.NotFoundError(err) 57 } 58 59 // Check the authenticity token 60 err = session.CheckAuthenticity(w, r) 61 if err != nil { 62 return err 63 } 64 65 // Authorise update comment 66 currentUser := session.CurrentUser(w, r) 67 err = can.Update(comment, currentUser) 68 if err != nil { 69 return server.NotAuthorizedError(err) 70 } 71 72 // Clean params according to role 73 accepted := comments.AllowedParams() 74 if currentUser.Admin() { 75 accepted = comments.AllowedParamsAdmin() 76 } 77 commentParams := comment.ValidateParams(params.Map(), accepted) 78 79 err = comment.Update(commentParams) 80 if err != nil { 81 return server.InternalError(err) 82 } 83 84 // Redirect to comment 85 return server.Redirect(w, r, comment.ShowURL()) 86 }