stars.go

88 lines
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 controllers

import (
	"crypto/sha256"
	"fmt"
	"net/http"
	"strings"
	"time"

	"congo.gg/pkg/application"
	"congo.gg/web/models"
)

func Stars() (string, *StarsController) {
	return "stars", &StarsController{}
}

type StarsController struct {
	application.BaseController
}

func (c *StarsController) Setup(app *application.App) {
	c.BaseController.Setup(app)
	http.Handle("POST /star", app.Method(c, "Create", nil))
}

func (c StarsController) Handle(r *http.Request) application.Controller {
	c.Request = r
	return &c
}

func (c *StarsController) Count() int {
	count, _ := models.Stars.Count("")
	return count
}

func (c *StarsController) Starred() bool {
	cookie, err := c.Request.Cookie("starred")
	return err == nil && cookie.Value == "1"
}

func (c *StarsController) Create(w http.ResponseWriter, r *http.Request) {
	// Check if already starred (cookie)
	if cookie, err := r.Cookie("starred"); err == nil && cookie.Value == "1" {
		c.Render(w, r, "star-success.html", nil)
		return
	}

	// Server-side dedup: hash the client IP
	ip := r.RemoteAddr
	if forwarded := r.Header.Get("X-Forwarded-For"); forwarded != "" {
		if i := strings.IndexByte(forwarded, ','); i > 0 {
			ip = strings.TrimSpace(forwarded[:i])
		} else {
			ip = forwarded
		}
	}
	hash := fmt.Sprintf("%x", sha256.Sum256([]byte(ip)))

	// Check if this IP already starred
	if count, _ := models.Stars.Count("WHERE IPHash = ?", hash); count > 0 {
		setStarCookie(w, r)
		c.Render(w, r, "star-success.html", nil)
		return
	}

	star := &models.Star{IPHash: hash}
	if _, err := models.Stars.Insert(star); err != nil {
		c.RenderError(w, r, err)
		return
	}

	setStarCookie(w, r)
	c.Render(w, r, "star-success.html", nil)
}

func setStarCookie(w http.ResponseWriter, r *http.Request) {
	secure := r.TLS != nil || r.Header.Get("X-Forwarded-Proto") == "https"
	http.SetCookie(w, &http.Cookie{
		Name:     "starred",
		Value:    "1",
		Path:     "/",
		MaxAge:   int(365 * 24 * time.Hour / time.Second),
		HttpOnly: true,
		Secure:   secure,
		SameSite: http.SameSiteLaxMode,
	})
}