~evanj/cms

ref: 7092668b038fb5c831981d303f6553b94b9c0bf8 cms/internal/c/c.go -rw-r--r-- 4.4 KiB
7092668bEvan M Jones Fix(rate limiting): Don't rely on MySQL time zone for rate limit 1 year, 2 months ago
                                                                                
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
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
package c

import (
	"bytes"
	"encoding/json"
	"errors"
	"fmt"
	"html/template"
	"io"
	"log"
	"net/http"
	"strings"

	"git.sr.ht/~evanj/cms/internal/m/user"
	"git.sr.ht/~evanj/cms/internal/s/rl"
	"github.com/google/uuid"
)

type KeyCookie = string

var (
	KeyUserLogin KeyCookie = "KeyUserLogin"

	ErrNoLogin  = errors.New("must be logged in")
	ErrNoAccess = errors.New("you don't have access to that feature")
)

type Controller struct {
	log *log.Logger
	db  dber

	analytics bool // Signifies if analytics/tracking should be on/off (goatcounter).
}

type dber interface {
	UserGet(username, password string) (user.User, error)
	UserGetFromToken(token string) (user.User, error)
}

func New(log *log.Logger, db dber, analytics bool) *Controller {
	return &Controller{
		log,
		db,
		analytics,
	}
}

func wrapUserErr(err error) error {
	if errors.Is(err, rl.ErrHitLimit) {
		return err
	}
	return ErrNoLogin
}

// TODO: You know why this is bad, change it.
func (c *Controller) GetCookieUser2(w http.ResponseWriter, r *http.Request) (user.User, error) {
	cookie, err := r.Cookie(KeyUserLogin)
	if err != nil {
		return nil, wrapUserErr(err)
	}

	user, err := c.db.UserGetFromToken(cookie.Value)
	if err != nil {
		return nil, wrapUserErr(err)
	}

	return user, nil
}

func (c *Controller) GetCookieUser(w http.ResponseWriter, r *http.Request) (user.User, error) {
	user, err := c.GetCookieUser2(w, r)
	if errors.Is(err, rl.ErrHitLimit) {
		return nil, err
	}
	if err != nil {
		// No user in cookie, lets check in basic auth.

		u, p, ok := r.BasicAuth()
		if !ok {
			return nil, ErrNoLogin
		}

		user, err = c.db.UserGet(u, p)
		if err != nil {
			return nil, err
		}
	}

	return user, nil
}

func (c *Controller) SetCookieUser(w http.ResponseWriter, r *http.Request, user user.User) {
	var tok string
	if user != nil {
		tok = user.Token()
	}

	http.SetCookie(w, &http.Cookie{
		Name:     KeyUserLogin,
		Value:    tok,
		HttpOnly: true,
		MaxAge:   50000,
		Path:     "/",
	})
}

func (c *Controller) String(w http.ResponseWriter, r *http.Request, str string) {
	w.Header().Add("Content-Type", "text/plain")
	w.WriteHeader(http.StatusOK)
	fmt.Fprintf(w, str)
}

// TODO: Refactor the usage of these three functions and remove Error2.

func (c *Controller) ErrorString(w http.ResponseWriter, r *http.Request, code int, str string) {
	w.Header().Add("Content-Type", "text/plain")
	w.WriteHeader(code)
	fmt.Fprintf(w, str)
}

func (c *Controller) Error(w http.ResponseWriter, r *http.Request, code int, str string) {
	c.ErrorString(w, r, code, str)
}

func (c *Controller) Error2(w http.ResponseWriter, r *http.Request, code int, err error) {
	w.Header().Add("Content-Type", "text/plain")
	w.WriteHeader(code)
	fmt.Fprintf(w, err.Error())
}

// TODO: You know why this is bad, change it.
func (c *Controller) HTML(w http.ResponseWriter, r *http.Request, tmpl *template.Template, data map[string]interface{}) {
	// Check JSON wanted.
	if !strings.Contains(r.Header.Get("Accept"), "text/html") {
		c.JSON(w, r, data)
		return
	}

	buf := bytes.Buffer{}

	if c.analytics {
		data["A"] = map[string]interface{}{
			"Path":     template.URL(r.URL.Path),
			"Referrer": template.URL(r.Referer()),
			"RND":      uuid.New().String(),
		}
	}

	if err := tmpl.Execute(&buf, data); err != nil {
		c.log.Println(err)
		c.Error(w, r, http.StatusInternalServerError, "failed to build html response")
		return
	}

	w.Header().Add("Cache-Control", "no-cache, no-store, must-revalidate, max-age=0")
	w.Header().Add("Content-Type", "text/html")
	w.Header().Add("Pragma", "no-cache")
	w.Header().Add("Expires", "Sat, 26 Jul 1997 05:00:00 GMT")
	w.WriteHeader(http.StatusOK)
	io.Copy(w, &buf)
}

// TODO: You know why this is bad, change it.
func (c *Controller) JSON(w http.ResponseWriter, r *http.Request, data interface{}) {
	bytes, err := json.Marshal(data)
	if err != nil {
		c.log.Println(err)
		c.Error(w, r, http.StatusInternalServerError, "failed to build json response")
		return
	}

	w.Header().Add("Content-Type", "application/json")
	w.WriteHeader(http.StatusOK)
	w.Write(bytes)
}

func (c *Controller) Method(r *http.Request) string {
	fv := r.FormValue("method")
	if fv != "" {
		return fv
	}
	return r.Method
}

func (c *Controller) Redirect(w http.ResponseWriter, r *http.Request, to string) {
	// Check if we should just spit out URL we're redirecting the user to (useful
	// for cURL users).
	if !strings.Contains(r.Header.Get("Accept"), "text/html") {
		c.JSON(w, r, to)
		return
	}
	http.Redirect(w, r, to, http.StatusFound)
}