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