-
Notifications
You must be signed in to change notification settings - Fork 2
/
submissions_handler.go
90 lines (73 loc) · 2.29 KB
/
submissions_handler.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
87
88
89
90
package main
import (
"encoding/json"
"fmt"
"net/http"
"strconv"
"github.com/flosch/pongo2"
"github.com/gorilla/mux"
"github.com/haisum/recaptcha"
"github.com/plentiform/plentiform/mailers"
"github.com/plentiform/plentiform/models"
repo "github.com/plentiform/plentiform/repositories"
)
func (app *Application) SubmissionsCreateHandler(w http.ResponseWriter, r *http.Request) {
uuid := mux.Vars(r)["uuid"]
r.ParseForm()
form, err := repo.NewFormsRepository(app.db).FindByUuid(uuid)
if err != nil {
http.Error(w, err.Error(), 500)
return
}
// Process Recaptcha if enabled
if form.RecaptchaSecretKey != nil {
recaptchaClient := recaptcha.R{
Secret: *form.RecaptchaSecretKey,
}
ok := recaptchaClient.Verify(*r)
if !ok {
http.Error(w, "Recaptcha Verification failed", 403)
return
}
}
r.Form.Del("g-recaptcha-response")
json, err := json.MarshalIndent(r.Form, "", " ")
if err != nil {
http.Error(w, err.Error(), 500)
return
}
_, err = repo.NewSubmissionsRepository(app.db).Create(form.Id, string(json))
if err != nil {
http.Error(w, err.Error(), 500)
return
}
user, _ := repo.NewUsersRepository(app.db).FindById(form.UserId)
mailers.SendSubmissionNotification(app.emailClient, user, form, json)
http.Redirect(w, r, r.Referer(), 302)
}
func (app *Application) SubmissionsDestroyHandler(w http.ResponseWriter, r *http.Request, currentUser *models.User) {
session, _ := app.GetSession(r)
formId, _ := strconv.Atoi(mux.Vars(r)["formId"])
submissionId, _ := strconv.Atoi(mux.Vars(r)["submissionId"])
form, _ := repo.NewFormsRepository(app.db).FindById(formId)
submissions, _ := repo.NewSubmissionsRepository(app.db).FindByFormId(form.Id)
if !currentUser.CanDelete(form) {
session.AddFlash("You are not authorized to access this resource.")
session.Save(r, w)
http.Redirect(w, r, fmt.Sprintf("/forms/%d", form.Id), 302)
return
}
_, err := repo.NewSubmissionsRepository(app.db).Delete(submissionId)
if err != nil {
session.AddFlash("An error occured while deleting this submission")
session.Save(r, w)
app.Render(w, r, "forms/show", pongo2.Context{
"form": form,
"submissions": submissions,
})
return
}
session.AddFlash("Successfully deleted submission!")
session.Save(r, w)
http.Redirect(w, r, fmt.Sprintf("/forms/%d", form.Id), 302)
}