summaryrefslogtreecommitdiff
path: root/api/guestbook.go
blob: ee3c79abc018f4f7d55c79542537cd9ee22972ea (plain)
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
package api

import (
	"log"
	"net/http"
	"strings"

	"git.hatecomputers.club/hatecomputers/hatecomputers.club/database"
	"git.hatecomputers.club/hatecomputers/hatecomputers.club/utils"
)

type HcaptchaArgs struct {
	SiteKey string
}

func validateGuestbookEntry(entry *database.GuestbookEntry) []string {
	errors := []string{}

	if entry.Name == "" {
		errors = append(errors, "name is required")
	}

	if entry.Message == "" {
		errors = append(errors, "message is required")
	}

	messageLength := len(entry.Message)
	if messageLength > 500 {
		errors = append(errors, "message cannot be longer than 500 characters")
	}

	newLines := strings.Count(entry.Message, "\n")
	if newLines > 10 {
		errors = append(errors, "message cannot contain more than 10 new lines")
	}

	return errors
}

func SignGuestbookContinuation(context *RequestContext, req *http.Request, resp http.ResponseWriter) ContinuationChain {
	return func(success Continuation, failure Continuation) ContinuationChain {
		name := req.FormValue("name")
		message := req.FormValue("message")

		formErrors := FormError{
			Errors: []string{},
		}

		entry := &database.GuestbookEntry{
			ID:      utils.RandomId(),
			Name:    name,
			Message: message,
		}
		formErrors.Errors = append(formErrors.Errors, validateGuestbookEntry(entry)...)

		if len(formErrors.Errors) == 0 {
			_, err := database.SaveGuestbookEntry(context.DBConn, entry)
			if err != nil {
				log.Println(err)
				formErrors.Errors = append(formErrors.Errors, "failed to save entry")
			}
		}

		if len(formErrors.Errors) > 0 {
			(*context.TemplateData)["FormError"] = formErrors
			(*context.TemplateData)["EntryForm"] = entry
			resp.WriteHeader(http.StatusBadRequest)

			return failure(context, req, resp)
		}

		return success(context, req, resp)
	}
}

func ListGuestbookContinuation(context *RequestContext, req *http.Request, resp http.ResponseWriter) ContinuationChain {
	return func(success Continuation, failure Continuation) ContinuationChain {
		entries, err := database.GetGuestbookEntries(context.DBConn)
		if err != nil {
			log.Println(err)
			resp.WriteHeader(http.StatusInternalServerError)
			return failure(context, req, resp)
		}

		(*context.TemplateData)["GuestbookEntries"] = entries
		return success(context, req, resp)
	}
}