Compare commits

..

No commits in common. "b5dfb135df50a68193cc8dc6b0ede1fb9f4f092e" and "86c1e4fea32ecf49ee5e71038ab77ee94b6827a7" have entirely different histories.

54 changed files with 752 additions and 1433 deletions

View File

@ -1,5 +0,0 @@
module lishwist/assert
go 1.23.0
toolchain go1.23.3

View File

@ -1,88 +0,0 @@
package assert
import (
"bytes"
"encoding/json"
"encoding/xml"
"errors"
"fmt"
"os"
"testing"
)
func pathExists(path string) bool {
_, err := os.Stat(path)
return !errors.Is(err, os.ErrNotExist)
}
var newline = []byte("\n")
func ensureSuffix(s, suffix []byte) []byte {
if !bytes.HasSuffix(s, suffix) {
s = append(s, suffix...)
}
return s
}
func writeSnapshot(t *testing.T, path string, actual []byte) {
f, err := os.Create(path)
if err != nil {
t.Fatalf("Failed to create snapshot file: %s", err)
}
_, err = f.Write(actual)
if err != nil {
t.Fatalf("Failed to write to snapshot file: %s", err)
}
err = f.Close()
if err != nil {
t.Fatalf("Failed to close snapshot file: %s", err)
}
}
func snapshot(t *testing.T, path string, actual []byte) {
if !pathExists(path) {
writeSnapshot(t, path, actual)
t.Errorf("Snapshot file created: %s", path)
return
}
actual = ensureSuffix(actual, newline)
expected, err := os.ReadFile(path)
if err != nil {
t.Fatalf("Failed to read snapshot file: %s", err)
}
expected = ensureSuffix(expected, newline)
if !bytes.Equal(expected, actual) {
t.Errorf("Value doesn't match snapshot %s:\n\nExpected:\n%s\n\nActual:\n%s\n", path, string(expected), string(actual))
}
if os.Getenv("UPDATE_SNAPSHOTS") == "" {
return
}
writeSnapshot(t, path, actual)
t.Logf("Snapshot file %s updated\n", path)
}
func SnapshotText(t *testing.T, actual string) {
snapshot(t, fmt.Sprintf("%s.snap.txt", t.Name()), []byte(actual))
}
func SnapshotJson(t *testing.T, actual any) {
data, err := json.MarshalIndent(actual, "", " ")
if err != nil {
t.Fatalf("Snapshot failed to serialize actual to JSON: %s", err)
}
snapshot(t, fmt.Sprintf("%s.snap.json", t.Name()), data)
}
func SnapshotXml(t *testing.T, actual any) {
data, err := xml.MarshalIndent(actual, "", " ")
if err != nil {
t.Fatalf("Snapshot failed to serialize actual to XML: %s", err)
}
snapshot(t, fmt.Sprintf("%s.snap.xml", t.Name()), data)
}

View File

@ -0,0 +1,62 @@
package assert
import (
"encoding/json"
"errors"
"fmt"
"os"
"testing"
)
func pathExists(path string) bool {
_, err := os.Stat(path)
return !errors.Is(err, os.ErrNotExist)
}
func writeSnapshot(t *testing.T, path, actual string) {
f, err := os.Create(path)
if err != nil {
t.Fatalf("Failed to create snapshot file: %s", err)
}
_, err = f.Write([]byte(actual))
if err != nil {
t.Fatalf("Failed to write to snapshot file: %s", err)
}
err = f.Close()
if err != nil {
t.Fatalf("Failed to close snapshot file: %s", err)
}
}
func TextSnapshot(t *testing.T, path, actual string) {
if !pathExists(path) {
writeSnapshot(t, path, actual)
t.Errorf("Snapshot file created: %s", path)
return
}
content, err := os.ReadFile(path)
if err != nil {
t.Fatalf("Failed to read snapshot file: %s", err)
}
expected := string(content)
if expected != actual {
t.Errorf("Value doesn't match snapshot %s:\n%s", path, actual)
}
if os.Getenv("UPDATE_SNAPSHOTS") == "" {
return
}
writeSnapshot(t, path, actual)
fmt.Printf("Snapshot file %s updated\n", path)
}
func JsonSnapshot(t *testing.T, path string, actual any) {
data, err := json.MarshalIndent(actual, "", " ")
if err != nil {
t.Fatalf("Snapshot failed to serialize actual to JSON: %s", err)
}
TextSnapshot(t, path, string(data))
}

View File

@ -3,7 +3,7 @@ package lishwist_test
import ( import (
"testing" "testing"
"lishwist/assert" "lishwist/core/internal/assert"
"lishwist/core/internal/fixtures" "lishwist/core/internal/fixtures"
) )

View File

@ -1,7 +1,6 @@
go 1.25.5 go 1.24.5
use ( use (
./assert
./core ./core
./http ./http
) )

43
http/api/login.go Normal file
View File

@ -0,0 +1,43 @@
package api
import (
"lishwist/http/templates"
)
type LoginProps struct {
GeneralError string `json:",omitempty"`
SuccessfulRegistration bool `json:",omitempty"`
SuccessfulSetPassword bool `json:",omitempty"`
Username templates.InputProps
Password templates.InputProps
}
func NewLoginProps(username, password string) *LoginProps {
return &LoginProps{
Username: templates.InputProps{
Name: "username",
Required: true,
Value: username,
},
Password: templates.InputProps{
Name: "password",
Type: "password",
Required: true,
Value: password,
},
}
}
func (p *LoginProps) Validate() (valid bool) {
valid = true
if !p.Username.Validate() {
valid = false
}
if !p.Password.Validate() {
valid = false
}
return
}

97
http/api/register.go Normal file
View File

@ -0,0 +1,97 @@
package api
import (
"lishwist/http/templates"
)
type RegisterProps struct {
Navbar templates.NavCollapse
GeneralError string `json:",omitempty"`
Username templates.InputProps
Password templates.InputProps
ConfirmPassword templates.InputProps
}
func (p *RegisterProps) Validate() (valid bool) {
valid = true
if p.Password.Value != p.ConfirmPassword.Value {
p.ConfirmPassword.Error = "Passwords didn't match"
valid = false
}
if !p.Username.Validate() {
valid = false
}
if !p.Password.Validate() {
valid = false
}
if !p.ConfirmPassword.Validate() {
valid = false
}
return
}
func NewRegisterProps(usernameVal, passwordVal, confirmPassVal string) *RegisterProps {
return &RegisterProps{
Navbar: templates.DefaultNavCollapse(),
GeneralError: "",
Username: templates.InputProps{
Name: "username",
Required: true,
MinLength: 4,
Value: usernameVal,
},
Password: templates.InputProps{
Type: "password",
Name: "newPassword",
Required: true,
MinLength: 5,
Value: passwordVal,
},
ConfirmPassword: templates.InputProps{
Type: "password",
Name: "confirmPassword",
Required: true,
Value: confirmPassVal,
},
}
}
// func Register(username, newPassword, confirmPassword string) *RegisterProps {
// props := NewRegisterProps(username, newPassword, confirmPassword)
// valid := props.Validate()
// props.Password.Value = ""
// props.ConfirmPassword.Value = ""
// if !valid {
// log.Printf("Invalid props: %#v\n", props)
// return props
// }
// existingUser, _ := db.GetUserByName(username)
// if existingUser != nil {
// log.Printf("Username is taken: %q\n", existingUser.NormalName)
// props.Username.Error = "Username is taken"
// return props
// }
// hashedPasswordBytes, err := bcrypt.GenerateFromPassword([]byte(newPassword), bcrypt.MinCost)
// if err != nil {
// log.Printf("Failed to hash password: %s\n", err)
// props.GeneralError = "Something went wrong. Error code: Aang"
// return props
// }
// _, err = db.CreateUser(username, hashedPasswordBytes)
// if err != nil {
// log.Printf("Failed to create user: %s\n", err)
// props.GeneralError = "Something went wrong. Error code: Ozai"
// return props
// }
// return nil
// }

View File

@ -2,4 +2,4 @@ top_level=$(git rev-parse --show-toplevel)
git_version=$($top_level/scripts/git-version) git_version=$($top_level/scripts/git-version)
go generate ../core/internal/db go generate ../core/internal/db
../scripts/withenv .env .env.local .env.dev .env.dev.local -- go run -ldflags=-X=lishwist/http/env.GitVersion=$git_version main.go go run -ldflags=-X=lishwist/http/env.GitVersion=$git_version main.go

View File

@ -1,14 +0,0 @@
package file
import (
"net/http"
"path/filepath"
"strings"
)
func NameAtPathValue(r *http.Request, pathValueName string) (stem string, ext string) {
filename := r.PathValue(pathValueName)
ext = filepath.Ext(filename)
stem = strings.TrimSuffix(filename, ext)
return
}

View File

@ -1,17 +1,16 @@
module lishwist/http module lishwist/http
go 1.25.5 go 1.23.3
toolchain go1.24.5
require ( require (
github.com/Teajey/rsvp v0.19.0-rc.2 github.com/Teajey/rsvp v0.13.1
github.com/gorilla/sessions v1.4.0 github.com/gorilla/sessions v1.4.0
golang.org/x/crypto v0.39.0 golang.org/x/crypto v0.39.0
) )
require ( require github.com/gorilla/securecookie v1.1.2
github.com/Teajey/hmc v0.6.0-rc.12
github.com/gorilla/securecookie v1.1.2
)
require ( require (
github.com/vmihailenco/msgpack/v5 v5.4.1 // indirect github.com/vmihailenco/msgpack/v5 v5.4.1 // indirect

View File

@ -1,7 +1,5 @@
github.com/Teajey/hmc v0.6.0-rc.12 h1:Vkx6mJa3pfMlYx4vyI9LfVLHa8fNyl8LikMvXBfDGZk= github.com/Teajey/rsvp v0.13.1 h1:0lw+JosaWmdjSmXoKQYBRS9nptSZPInm60Y5GQ3llEU=
github.com/Teajey/hmc v0.6.0-rc.12/go.mod h1:9K7SL4RyybNLHooqsZcyFoL6QGqqa2zPgIBidw4qWQY= github.com/Teajey/rsvp v0.13.1/go.mod h1:z0L20VphVg+Ec2+hnpLFTG2MZTrWYFprav1kpxDba0Q=
github.com/Teajey/rsvp v0.19.0-rc.2 h1:h4V7c3uGlSKajkWKt3fldFV+XTMEI8A4o05PMY8xv9A=
github.com/Teajey/rsvp v0.19.0-rc.2/go.mod h1:z0L20VphVg+Ec2+hnpLFTG2MZTrWYFprav1kpxDba0Q=
github.com/davecgh/go-spew v1.1.0 h1:ZDRjVQ15GmhC3fiQ8ni8+OwkZQO4DARzQgrnXU1Liz8= github.com/davecgh/go-spew v1.1.0 h1:ZDRjVQ15GmhC3fiQ8ni8+OwkZQO4DARzQgrnXU1Liz8=
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/google/gofuzz v1.2.0 h1:xRy4A+RhZaiKjJ1bPfwQ8sedCA+YS2YcCHW6ec7JMi0= github.com/google/gofuzz v1.2.0 h1:xRy4A+RhZaiKjJ1bPfwQ8sedCA+YS2YcCHW6ec7JMi0=

View File

@ -1,20 +0,0 @@
package handler
import (
"net/http"
"github.com/Teajey/rsvp"
lishwist "lishwist/core"
"lishwist/http/session"
)
type Private interface {
ServeHTTP(*lishwist.Session, *session.Session, rsvp.ResponseWriter, *http.Request) rsvp.Body
}
type PrivateFunc func(*lishwist.Session, *session.Session, rsvp.ResponseWriter, *http.Request) rsvp.Body
func (f PrivateFunc) ServeHTTP(app *lishwist.Session, s *session.Session, w rsvp.ResponseWriter, r *http.Request) rsvp.Body {
return f(app, s, w, r)
}

View File

@ -1,19 +0,0 @@
package handler
import (
"net/http"
"github.com/Teajey/rsvp"
"lishwist/http/session"
)
type Public interface {
ServeHTTP(*session.Session, rsvp.ResponseWriter, *http.Request) rsvp.Body
}
type PublicFunc func(*session.Session, rsvp.ResponseWriter, *http.Request) rsvp.Body
func (f PublicFunc) ServeHTTP(s *session.Session, w rsvp.ResponseWriter, r *http.Request) rsvp.Body {
return f(s, w, r)
}

View File

@ -1,22 +0,0 @@
package middleware
import (
"net/http"
"strings"
"github.com/Teajey/rsvp"
)
func PrefixMovedPermanently(before, after string) rsvp.HandlerFunc {
return func(w rsvp.ResponseWriter, r *http.Request) rsvp.Body {
suffix := strings.TrimPrefix(r.RequestURI, before)
return rsvp.Blank().StatusMovedPermanently(after + suffix)
}
}
func PrefixPermanentRedirect(before, after string) rsvp.HandlerFunc {
return func(w rsvp.ResponseWriter, r *http.Request) rsvp.Body {
suffix := strings.TrimPrefix(r.RequestURI, before)
return rsvp.Blank().StatusPermanentRedirect(after + suffix)
}
}

View File

@ -1,104 +0,0 @@
package mux
import (
"log"
"net/http"
"github.com/Teajey/rsvp"
lishwist "lishwist/core"
"lishwist/http/handler"
"lishwist/http/response"
"lishwist/http/session"
)
type Private struct {
inner *http.ServeMux
store *session.Store
rsvp rsvp.Config
}
func (m *Private) GetSession(r *http.Request) *session.Session {
innerSession, _ := m.store.Get(r, "lishwist_user")
return session.New(innerSession)
}
func newPrivate(store *session.Store, cfg rsvp.Config) Private {
mux := http.NewServeMux()
return Private{
inner: mux,
store: store,
rsvp: cfg,
}
}
func (m *Private) ServeHTTP(w http.ResponseWriter, r *http.Request) {
m.inner.ServeHTTP(w, r)
}
func expectAppSession(next handler.Private) handler.PublicFunc {
return func(session *session.Session, w rsvp.ResponseWriter, r *http.Request) rsvp.Body {
sessionKey, ok := session.GetString("sessionKey")
if !ok {
log.Printf("Failed to get key from session\n")
return response.Error("Something went wrong.").StatusInternalServerError()
}
appSession, err := lishwist.SessionFromKey(sessionKey)
if err != nil {
log.Printf("Failed to get session by key %v: %s\n", sessionKey, err)
return response.Error("Something went wrong.").StatusInternalServerError()
}
if appSession == nil {
log.Printf("Session not found under key: %s\n", sessionKey)
return response.Error("Something went wrong.").StatusInternalServerError()
}
return next.ServeHTTP(appSession, session, w, r)
}
}
type sessionResponseWriter struct {
http.ResponseWriter
s *session.Session
r *http.Request
}
func (w sessionResponseWriter) WriteHeader(statusCode int) {
if w.s.WasWritten() {
err := w.s.Save(w.r, w)
if err != nil {
log.Printf("Failed to save session: %s", err)
}
}
w.ResponseWriter.WriteHeader(statusCode)
}
func (m *Private) handleWithSession(pattern string, next handler.PublicFunc) {
getSessionMiddleware := func(w http.ResponseWriter, r *http.Request) {
s := m.GetSession(r)
rw := sessionResponseWriter{
ResponseWriter: w,
s: s,
r: r,
}
err := rsvp.Write(rw, m.rsvp, r, func(w rsvp.ResponseWriter, r *http.Request) rsvp.Body {
return next(s, w, r)
})
if err != nil {
log.Printf("rsvp failed to write a response: %s", err)
}
}
m.inner.HandleFunc(pattern, getSessionMiddleware)
}
func (m *Private) Handle(pattern string, handler handler.Private) {
m.handleWithSession(pattern, expectAppSession(handler))
}
func (m *Private) HandleFunc(pattern string, handler handler.PrivateFunc) {
m.Handle(pattern, handler)
}

View File

@ -1,26 +0,0 @@
package mux
import (
"lishwist/http/handler"
"lishwist/http/session"
"github.com/Teajey/rsvp"
)
type Public struct {
Private
}
func newPublic(store *session.Store, cfg rsvp.Config) Public {
return Public{
newPrivate(store, cfg),
}
}
func (m *Public) Handle(pattern string, handler handler.Public) {
m.handleWithSession(pattern, handler.ServeHTTP)
}
func (m *Public) HandleFunc(pattern string, handler handler.PublicFunc) {
m.Handle(pattern, handler)
}

View File

@ -1,76 +0,0 @@
package mux
import (
"log"
"net/http"
"github.com/Teajey/rsvp"
lishwist "lishwist/core"
"lishwist/http/routing"
"lishwist/http/session"
"lishwist/http/templates"
"lishwist/http/templates/text"
)
type Serve struct {
store *session.Store
rsvpCfg rsvp.Config
Public Public
Private Private
}
func (m *Serve) GetSession(r *http.Request) *session.Session {
innerSession, _ := m.store.Get(r, "lishwist_user")
return session.New(innerSession)
}
func (m *Serve) ServeHTTP(w http.ResponseWriter, r *http.Request) {
innerSession, _ := m.store.Get(r, "lishwist_user")
s := session.New(innerSession)
_, inSession := s.GetString("sessionKey")
if inSession {
m.Private.ServeHTTP(w, r)
return
}
username, password, ok := r.BasicAuth()
if ok {
loggedIn := nil == routing.LoginMiddle(username, password, s, r)
if s.WasWritten() {
err := s.Save(r, w)
if err != nil {
log.Printf("Failed to save session: %s", err)
}
}
if loggedIn {
m.Private.ServeHTTP(w, r)
return
}
}
m.Public.ServeHTTP(w, r)
}
func New(store *session.Store) *Serve {
cfg := rsvp.Config{}
cfg.HtmlTemplate = templates.Template
cfg.TextTemplate = text.Template
sv := Serve{
store: store,
rsvpCfg: cfg,
Public: newPublic(store, cfg),
Private: newPrivate(store, cfg),
}
return &sv
}
func (m *Serve) HandleFunc(pattern string, hnd rsvp.HandlerFunc) {
m.Public.HandleFunc(pattern, func(s *session.Session, w rsvp.ResponseWriter, r *http.Request) rsvp.Body {
return hnd(w, r)
})
m.Private.HandleFunc(pattern, func(app *lishwist.Session, s *session.Session, w rsvp.ResponseWriter, r *http.Request) rsvp.Body {
return hnd(w, r)
})
}

View File

@ -1,37 +0,0 @@
package props
import "github.com/Teajey/hmc"
type Login struct {
GeneralError string `json:",omitempty" xml:",omitempty"`
SuccessfulRegistration bool `json:",omitempty" xml:",omitempty"`
SuccessfulSetPassword bool `json:",omitempty" xml:",omitempty"`
Username hmc.Input
Password hmc.Input
}
func NewLogin(username, password string) Login {
return Login{
Username: hmc.Input{
Label: "Username",
Name: "username",
Required: true,
Value: username,
},
Password: hmc.Input{
Label: "Password",
Name: "password",
Type: "password",
Required: true,
Value: password,
},
}
}
func (p *Login) Validate() (valid bool) {
_ = p.Username.Validate()
_ = p.Password.Validate()
return p.Username.Error == "" && p.Password.Error == ""
}

View File

@ -1,85 +0,0 @@
package props
import (
"html/template"
"github.com/Teajey/hmc"
"lishwist/http/templates"
)
type RegisterForm struct {
Username hmc.Input
Password hmc.Input
ConfirmPassword hmc.Input
}
type Register struct {
hmc.Namespace
Nav templates.NavCollapse
Error string `json:",omitempty" xml:",omitempty"`
Warning template.HTML `json:",omitempty" xml:",omitempty"`
Form hmc.Form[RegisterForm]
}
func (p *RegisterForm) Validate() (valid bool) {
valid = true
if p.Password.Value != p.ConfirmPassword.Value {
p.ConfirmPassword.Error = "Passwords didn't match"
valid = false
}
_ = p.Username.Validate()
_ = p.Password.Validate()
_ = p.ConfirmPassword.Validate()
if valid {
valid = p.Username.Error == "" && p.Password.Error == "" && p.ConfirmPassword.Error == ""
}
return
}
func NewRegister(usernameVal, passwordVal, confirmPassVal string) Register {
return Register{
Namespace: hmc.NS(),
Nav: templates.NavCollapse{
Links: []hmc.Link{{
Label: "Login",
Href: "/",
}},
},
Error: "",
Warning: template.HTML(`<p>Your password will be stored in a safe, responsible manner; but don't trust my programming skills!</p><p class="mb-0">Maybe use a password here that you don't use for important things...</p>`),
Form: hmc.Form[RegisterForm]{
Method: "POST",
Elements: RegisterForm{
Username: hmc.Input{
Label: "Username",
Name: "username",
Required: true,
MinLength: 4,
Value: usernameVal,
},
Password: hmc.Input{
Label: "Password",
Type: "password",
Name: "newPassword",
Required: true,
MinLength: 5,
Value: passwordVal,
},
ConfirmPassword: hmc.Input{
Label: "Confirm password",
Type: "password",
Name: "confirmPassword",
Required: true,
Value: confirmPassVal,
},
},
},
}
}

View File

@ -1,179 +0,0 @@
package resources
import (
lishwist "lishwist/core"
"lishwist/http/templates"
"net/url"
"github.com/Teajey/hmc"
)
type LinksList struct {
Label string `json:"label" xml:",chardata"`
Links []hmc.Link `json:"links" xml:"Link"`
}
type HomeProps struct {
hmc.Namespace
Error string
Warning string
Navbar templates.NavCollapse `json:"-"`
Wishlist Wishlist `json:"wishlist"`
Todo Wishlist `json:"todo"`
GroupsList LinksList `json:"groups" xml:"LinksList"`
}
type Wish struct {
Input hmc.Input `json:"input"`
Recipient *hmc.Link `json:"recipient,omitempty" xml:",omitempty"`
Sent bool `json:"sent" xml:"sent,attr"`
}
type Wishes struct {
Items []Wish `json:"items"`
Select hmc.Select
Intent hmc.Select
}
type Wishlist struct {
Label string `json:"label" xml:",chardata"`
Wishes hmc.Form[Wishes] `json:"wishes"`
NewWish *hmc.Form[hmc.Input] `json:"new_wish"`
}
func InitialWishlist(currentUserId string, wishes []lishwist.Wish) Wishlist {
wishInputs := make([]hmc.Option, len(wishes))
items := make([]Wish, len(wishes))
for i, w := range wishes {
wsh := hmc.Option{
Label: w.Name,
Value: w.Id,
}
wishInputs[i] = wsh
items[i] = Wish{
Input: hmc.Input{
Label: w.Name,
Value: w.Id,
Type: "checkbox",
Name: "wish",
},
}
}
return Wishlist{
Label: "Your wishlist",
Wishes: hmc.Form[Wishes]{
Method: "POST",
Elements: Wishes{
Items: items,
Select: hmc.Select{
Label: "Wishes",
Multiple: true,
Name: "wish",
Required: true,
Options: wishInputs,
},
Intent: hmc.Select{
Label: "Intent",
Required: true,
Name: "intent",
Options: []hmc.Option{{
Label: "Delete",
Value: "delete",
}},
},
},
},
NewWish: &hmc.Form[hmc.Input]{
Method: "POST",
Elements: hmc.Input{
Label: "Add gift idea",
Name: "gift_name",
},
},
}
}
func InitialTodo(todo []lishwist.Wish) Wishlist {
wishInputs := make([]Wish, len(todo))
options := make([]hmc.Option, len(todo))
for i, w := range todo {
wsh := Wish{
Input: hmc.Input{
Label: w.Name,
Type: "checkbox",
},
Recipient: &hmc.Link{
Label: w.RecipientName,
Href: "/lists/" + w.RecipientRef,
},
Sent: w.Sent,
}
opt := hmc.Option{
Label: w.Name,
Value: w.Id,
}
if w.Sent {
wsh.Input.Disabled = true
opt.Disabled = true
} else {
wsh.Input.Name = "todo"
wsh.Input.Value = w.Id
}
wishInputs[i] = wsh
options[i] = opt
}
return Wishlist{
Label: "Your todo list",
Wishes: hmc.Form[Wishes]{
Method: "POST",
Elements: Wishes{
Items: wishInputs,
Select: hmc.Select{
Label: "Todos",
Multiple: true,
Name: "todo",
Required: true,
Options: options,
},
Intent: hmc.Select{
Label: "Intent",
Required: true,
Name: "intent",
Options: []hmc.Option{
{
Label: "Unclaim",
Value: "unclaim_todo",
},
{
Label: "Complete",
Value: "complete_todo",
},
},
},
},
},
}
}
func (w Wishlist) ExtractFormValues(form url.Values) {
if w.NewWish != nil {
w.NewWish.Elements.ExtractFormValue(form)
}
err := w.Wishes.Elements.Select.ExtractFormValue(form)
if err != nil {
w.Wishes.Elements.Select.Error = err.Error()
}
err = w.Wishes.Elements.Intent.ExtractFormValue(form)
if err != nil {
w.Wishes.Elements.Intent.Error = err.Error()
}
}

58
http/response/handler.go Normal file
View File

@ -0,0 +1,58 @@
package response
import (
"log"
"net/http"
"lishwist/http/session"
"lishwist/http/templates"
"lishwist/http/templates/text"
"github.com/Teajey/rsvp"
)
type ServeMux struct {
inner *rsvp.ServeMux
store *session.Store
}
func NewServeMux(store *session.Store) *ServeMux {
mux := rsvp.NewServeMux()
mux.Config.HtmlTemplate = templates.Template
mux.Config.TextTemplate = text.Template
return &ServeMux{
inner: mux,
store: store,
}
}
func (m *ServeMux) ServeHTTP(w http.ResponseWriter, r *http.Request) {
m.inner.ServeHTTP(w, r)
}
type Handler interface {
ServeHTTP(*Session, http.Header, *http.Request) rsvp.Response
}
type HandlerFunc func(*Session, http.Header, *http.Request) rsvp.Response
func (m *ServeMux) HandleFunc(pattern string, handler HandlerFunc) {
m.inner.MiddleHandleFunc(pattern, func(w http.ResponseWriter, r *http.Request) rsvp.Response {
session := m.GetSession(r)
response := handler(session, w.Header(), r)
if session.written {
err := session.inner.Save(r, w)
if err != nil {
log.Printf("Failed to save session: %s\n", err)
}
}
return response
})
}
func (m *ServeMux) Handle(pattern string, handler Handler) {
m.HandleFunc(pattern, handler.ServeHTTP)
}

10
http/response/request.go Normal file
View File

@ -0,0 +1,10 @@
package response
import (
"net/http"
)
func (m *ServeMux) GetSession(r *http.Request) *Session {
session, _ := m.store.Get(r, "lishwist_user")
return &Session{inner: session}
}

View File

@ -3,12 +3,13 @@ package response
import ( import (
"fmt" "fmt"
"lishwist/http/templates" "lishwist/http/templates"
"net/http"
"github.com/Teajey/rsvp" "github.com/Teajey/rsvp"
) )
func NotFound() rsvp.Body { func NotFound() rsvp.Response {
return Error("Page not found").StatusNotFound() return Error(http.StatusNotFound, "Page not found")
} }
type errorProps struct { type errorProps struct {
@ -16,19 +17,20 @@ type errorProps struct {
Message string Message string
} }
func Error(format string, a ...any) rsvp.Body { func Error(status int, format string, a ...any) rsvp.Response {
return rsvp.Body{ return rsvp.Response{
Data: errorProps{ Body: errorProps{
Message: fmt.Sprintf(format, a...), Message: fmt.Sprintf(format, a...),
Navbar: templates.DefaultNavCollapse(), Navbar: templates.DefaultNavCollapse(),
}, },
Status: status,
TemplateName: "error_page.gotmpl", TemplateName: "error_page.gotmpl",
} }
} }
func Data(templateName string, body any) rsvp.Body { func Data(templateName string, body any) rsvp.Response {
return rsvp.Body{ return rsvp.Response{
Data: body, Body: body,
TemplateName: templateName, TemplateName: templateName,
} }
} }

View File

@ -1,8 +1,6 @@
package session package response
import ( import (
"net/http"
"github.com/gorilla/sessions" "github.com/gorilla/sessions"
) )
@ -11,10 +9,6 @@ type Session struct {
written bool written bool
} }
func New(inner *sessions.Session) *Session {
return &Session{inner: inner}
}
const flashKey = "_flash" const flashKey = "_flash"
func (s *Session) FlashGet() any { func (s *Session) FlashGet() any {
@ -55,18 +49,8 @@ func (s *Session) RemoveValue(key any) {
s.written = true s.written = true
} }
func (s *Session) GetValue(key any) (any, bool) { func (s *Session) GetValue(key any) any {
val, ok := s.inner.Values[key] return s.inner.Values[key]
return val, ok
}
func (s *Session) GetString(key any) (string, bool) {
val, ok := s.GetValue(key)
if !ok {
return "", false
}
str, ok := val.(string)
return str, ok
} }
func (s *Session) ClearValues() { func (s *Session) ClearValues() {
@ -77,11 +61,3 @@ func (s *Session) ClearValues() {
func (s *Session) Options() *sessions.Options { func (s *Session) Options() *sessions.Options {
return s.inner.Options return s.inner.Options
} }
func (s *Session) WasWritten() bool {
return s.written
}
func (s *Session) Save(r *http.Request, w http.ResponseWriter) error {
return s.inner.Save(r, w)
}

38
http/router/router.go Normal file
View File

@ -0,0 +1,38 @@
package router
import (
"net/http"
"lishwist/http/response"
"lishwist/http/session"
)
type VisibilityRouter struct {
store *session.Store
Public *response.ServeMux
Private *response.ServeMux
}
func (s *VisibilityRouter) ServeHTTP(w http.ResponseWriter, r *http.Request) {
session, _ := s.store.Get(r, "lishwist_user")
_, inSession := session.Values["sessionKey"]
if inSession {
s.Private.ServeHTTP(w, r)
} else {
s.Public.ServeHTTP(w, r)
}
}
func New(store *session.Store) *VisibilityRouter {
return &VisibilityRouter{
store: store,
Public: response.NewServeMux(store),
Private: response.NewServeMux(store),
}
}
func (r *VisibilityRouter) HandleFunc(pattern string, handler response.HandlerFunc) {
r.Public.HandleFunc(pattern, handler)
r.Private.HandleFunc(pattern, handler)
}

View File

@ -1,17 +1,14 @@
package routing package routing
import ( import (
"fmt"
"log" "log"
"net/http" "net/http"
lishwist "lishwist/core" lishwist "lishwist/core"
"lishwist/http/props" "lishwist/http/api"
"lishwist/http/response" "lishwist/http/response"
"lishwist/http/session"
"lishwist/http/templates" "lishwist/http/templates"
"github.com/Teajey/hmc"
"github.com/Teajey/rsvp" "github.com/Teajey/rsvp"
) )
@ -19,8 +16,8 @@ type AccountProps struct {
Navbar templates.NavCollapse Navbar templates.NavCollapse
GeneralError string `json:",omitempty"` GeneralError string `json:",omitempty"`
PasswordFromAdmin bool `json:",omitempty"` PasswordFromAdmin bool `json:",omitempty"`
Password hmc.Input Password templates.InputProps
ConfirmPassword hmc.Input ConfirmPassword templates.InputProps
} }
func (p *AccountProps) Validate() (valid bool) { func (p *AccountProps) Validate() (valid bool) {
@ -31,12 +28,12 @@ func (p *AccountProps) Validate() (valid bool) {
valid = false valid = false
} }
_ = p.Password.Validate() if !p.Password.Validate() {
valid = false
}
_ = p.ConfirmPassword.Validate() if !p.ConfirmPassword.Validate() {
valid = false
if valid {
valid = p.Password.Error == "" && p.ConfirmPassword.Error == ""
} }
return return
@ -45,28 +42,18 @@ func (p *AccountProps) Validate() (valid bool) {
func NewAccountProps(username string, passwordFromAdmin bool, passwordVal, confirmPassVal string) *AccountProps { func NewAccountProps(username string, passwordFromAdmin bool, passwordVal, confirmPassVal string) *AccountProps {
return &AccountProps{ return &AccountProps{
Navbar: templates.NavCollapse{ Navbar: templates.NavCollapse{
Links: []hmc.Link{{Href: "/", Label: "Home"}}, Links: []templates.Link{{Href: "/", Name: "Home"}},
User: &templates.NavUser{ User: &templates.User{Name: username},
Label: fmt.Sprintf("Logged in as '%s'", username),
Logout: hmc.Form[hmc.Input]{
Method: "POST",
Action: "/logout",
Elements: hmc.Input{
Label: "Logout",
Type: "submit",
},
},
},
}, },
PasswordFromAdmin: passwordFromAdmin, PasswordFromAdmin: passwordFromAdmin,
Password: hmc.Input{ Password: templates.InputProps{
Type: "password", Type: "password",
Name: "new_password", Name: "new_password",
Required: true, Required: true,
MinLength: 5, MinLength: 5,
Value: passwordVal, Value: passwordVal,
}, },
ConfirmPassword: hmc.Input{ ConfirmPassword: templates.InputProps{
Type: "password", Type: "password",
Name: "confirm_password", Name: "confirm_password",
Required: true, Required: true,
@ -75,7 +62,7 @@ func NewAccountProps(username string, passwordFromAdmin bool, passwordVal, confi
} }
} }
func Account(app *lishwist.Session, session *session.Session, w rsvp.ResponseWriter, r *http.Request) rsvp.Body { func Account(app *lishwist.Session, session *response.Session, h http.Header, r *http.Request) rsvp.Response {
user := app.User() user := app.User()
props := NewAccountProps(user.Name, user.PasswordFromAdmin, "", "") props := NewAccountProps(user.Name, user.PasswordFromAdmin, "", "")
@ -90,43 +77,43 @@ func Account(app *lishwist.Session, session *session.Session, w rsvp.ResponseWri
return response.Data("account.gotmpl", props) return response.Data("account.gotmpl", props)
} }
func AccountPost(app *lishwist.Session, session *session.Session, w rsvp.ResponseWriter, r *http.Request) rsvp.Body { func AccountPost(app *lishwist.Session, session *response.Session, h http.Header, r *http.Request) rsvp.Response {
user := app.User() user := app.User()
err := r.ParseForm() err := r.ParseForm()
if err != nil { if err != nil {
return response.Error("Failed to parse form").StatusBadRequest() return response.Error(http.StatusBadRequest, "Failed to parse form")
} }
intent := r.Form.Get("intent") intent := r.Form.Get("intent")
if intent != "set_password" { if intent != "set_password" {
return response.Error("Invalid intent %q", intent).StatusBadRequest() return response.Error(http.StatusBadRequest, "Invalid intent %q", intent)
} }
newPassword := r.Form.Get("new_password") newPassword := r.Form.Get("new_password")
confirmPassword := r.Form.Get("confirm_password") confirmPassword := r.Form.Get("confirm_password")
account := NewAccountProps(user.Name, user.PasswordFromAdmin, newPassword, confirmPassword) props := NewAccountProps(user.Name, user.PasswordFromAdmin, newPassword, confirmPassword)
valid := account.Validate() valid := props.Validate()
account.Password.Value = "" props.Password.Value = ""
account.ConfirmPassword.Value = "" props.ConfirmPassword.Value = ""
if !valid { if !valid {
log.Printf("Invalid account submission: %#v\n", account) log.Printf("Invalid account props: %#v\n", props)
session.FlashSet(&account) session.FlashSet(&props)
return rsvp.Data(account).StatusSeeOther("/account") return rsvp.SeeOther("/account", props)
} }
err = user.SetPassword(newPassword) err = user.SetPassword(newPassword)
if err != nil { if err != nil {
account.GeneralError = "Something went wrong." props.GeneralError = "Something went wrong."
log.Printf("Set password failed: %s\n", err) log.Printf("Set password failed: %s\n", err)
session.FlashSet(&account) session.FlashSet(&props)
return rsvp.Data(account).StatusSeeOther("/account") return rsvp.SeeOther("/account", props)
} }
session.RemoveValue("sessionKey") session.RemoveValue("sessionKey")
session.FlashSet(&props.Login{SuccessfulSetPassword: true}) session.FlashSet(&api.LoginProps{SuccessfulSetPassword: true})
return rsvp.Data("Set password successful!").StatusSeeOther("/") return rsvp.SeeOther("/", "Set password successful!")
} }

View File

@ -3,7 +3,7 @@ package routing
import ( import (
lishwist "lishwist/core" lishwist "lishwist/core"
"lishwist/http/env" "lishwist/http/env"
"lishwist/http/session" "lishwist/http/response"
"net/http" "net/http"
"github.com/Teajey/rsvp" "github.com/Teajey/rsvp"
@ -14,12 +14,12 @@ type HealthProps struct {
Config env.Config Config env.Config
} }
func Health(app *lishwist.Session, session *session.Session, w rsvp.ResponseWriter, r *http.Request) rsvp.Body { func Health(app *lishwist.Session, session *response.Session, h http.Header, r *http.Request) rsvp.Response {
if app.Admin() == nil { if app.Admin() == nil {
return rsvp.Blank() return rsvp.Ok()
} }
return rsvp.Body{Data: HealthProps{ return rsvp.Response{Body: HealthProps{
GitVersion: env.GitVersion, GitVersion: env.GitVersion,
Config: env.Configuration, Config: env.Configuration,
}} }}

View File

@ -1 +1,34 @@
package routing package routing
import (
"log"
"net/http"
lishwist "lishwist/core"
"lishwist/http/response"
"github.com/Teajey/rsvp"
)
func ExpectAppSession(next func(*lishwist.Session, *response.Session, http.Header, *http.Request) rsvp.Response) response.HandlerFunc {
return func(session *response.Session, h http.Header, r *http.Request) rsvp.Response {
sessionKey, ok := session.GetValue("sessionKey").(string)
if !ok {
log.Printf("Failed to get key from session\n")
return response.Error(http.StatusInternalServerError, "Something went wrong.")
}
appSession, err := lishwist.SessionFromKey(sessionKey)
if err != nil {
log.Printf("Failed to get session by key %v: %s\n", sessionKey, err)
return response.Error(http.StatusInternalServerError, "Something went wrong.")
}
if appSession == nil {
log.Printf("Session not found under key: %s\n", sessionKey)
return response.Error(http.StatusInternalServerError, "Something went wrong.")
}
return next(appSession, session, h, r)
}
}

View File

@ -3,7 +3,6 @@ package routing
import ( import (
lishwist "lishwist/core" lishwist "lishwist/core"
"lishwist/http/response" "lishwist/http/response"
"lishwist/http/session"
"log" "log"
"net/http" "net/http"
@ -14,7 +13,7 @@ type Events struct {
Events []lishwist.Event `xml:"Event"` Events []lishwist.Event `xml:"Event"`
} }
func EventList(app *lishwist.Session, session *session.Session, w rsvp.ResponseWriter, r *http.Request) rsvp.Body { func EventList(app *lishwist.Session, session *response.Session, h http.Header, r *http.Request) rsvp.Response {
admin := app.Admin() admin := app.Admin()
if admin == nil { if admin == nil {
log.Println("Attempt to access EventList by non-admin. Responding 404 Not Found.") log.Println("Attempt to access EventList by non-admin. Responding 404 Not Found.")
@ -24,7 +23,7 @@ func EventList(app *lishwist.Session, session *session.Session, w rsvp.ResponseW
events, err := admin.ListEvents() events, err := admin.ListEvents()
if err != nil { if err != nil {
log.Printf("Admin failed to ListEvents: %s\n", err) log.Printf("Admin failed to ListEvents: %s\n", err)
return response.Error("Failed to get events: %s", err).StatusInternalServerError() return response.Error(http.StatusInternalServerError, "Failed to get events: %s", err)
} }
return response.Data("", Events{Events: events}) return response.Data("", Events{Events: events})

View File

@ -2,9 +2,7 @@ package routing
import ( import (
lishwist "lishwist/core" lishwist "lishwist/core"
"lishwist/http/file"
"lishwist/http/response" "lishwist/http/response"
"lishwist/http/session"
"lishwist/http/templates" "lishwist/http/templates"
"log" "log"
"net/http" "net/http"
@ -20,26 +18,26 @@ type foreignWishlistProps struct {
Gifts []lishwist.Wish Gifts []lishwist.Wish
} }
func ForeignWishlist(app *lishwist.Session, session *session.Session, w rsvp.ResponseWriter, r *http.Request) rsvp.Body { func ForeignWishlist(app *lishwist.Session, session *response.Session, h http.Header, r *http.Request) rsvp.Response {
userReference, _ := file.NameAtPathValue(r, "userReference") userReference := r.PathValue("userReference")
user := app.User() user := app.User()
if user.Reference == userReference { if user.Reference == userReference {
return rsvp.Data("You're not allowed to view your own wishlist!").StatusFound("/") return rsvp.Found("/", "You're not allowed to view your own wishlist!")
} }
otherUser, err := lishwist.GetUserByReference(userReference) otherUser, err := lishwist.GetUserByReference(userReference)
if err != nil { if err != nil {
log.Printf("Couldn't get user by reference %q: %s\n", userReference, err) log.Printf("Couldn't get user by reference %q: %s\n", userReference, err)
return response.Error("An error occurred while fetching this user :(").StatusInternalServerError() return response.Error(http.StatusInternalServerError, "An error occurred while fetching this user :(")
} }
if otherUser == nil { if otherUser == nil {
return response.Error("User not found").StatusInternalServerError() return response.Error(http.StatusInternalServerError, "User not found")
} }
wishes, err := app.GetOthersWishes(userReference) wishes, err := app.GetOthersWishes(userReference)
if err != nil { if err != nil {
log.Printf("%q couldn't get wishes of other user %q: %s\n", user.Name, otherUser.Name, err) log.Printf("%q couldn't get wishes of other user %q: %s\n", user.Name, otherUser.Name, err)
return response.Error("An error occurred while fetching this user :(").StatusInternalServerError() return response.Error(http.StatusInternalServerError, "An error occurred while fetching this user :(")
} }
p := foreignWishlistProps{Navbar: templates.UserNavCollapse(user.Name, user.Reference, user.PasswordFromAdmin), CurrentUserId: user.Id, Username: otherUser.Name, Gifts: wishes} p := foreignWishlistProps{Navbar: templates.UserNavCollapse(user.Name, user.PasswordFromAdmin), CurrentUserId: user.Id, Username: otherUser.Name, Gifts: wishes}
return response.Data("foreign_wishlist.gotmpl", p) return response.Data("foreign_wishlist.gotmpl", p)
} }
@ -47,24 +45,23 @@ type publicWishlistProps struct {
Navbar templates.NavCollapse Navbar templates.NavCollapse
Username string Username string
GiftCount int GiftCount int
Referrer string
} }
func PublicWishlist(s *session.Session, w rsvp.ResponseWriter, r *http.Request) rsvp.Body { func PublicWishlist(s *response.Session, h http.Header, r *http.Request) rsvp.Response {
userReference, _ := file.NameAtPathValue(r, "userReference") userReference := r.PathValue("userReference")
otherUser, err := lishwist.GetUserByReference(userReference) otherUser, err := lishwist.GetUserByReference(userReference)
if err != nil { if err != nil {
log.Printf("Couldn't get user by reference %q on public wishlist: %s\n", userReference, err) log.Printf("Couldn't get user by reference %q on public wishlist: %s\n", userReference, err)
return response.Error("An error occurred while fetching this user :(").StatusInternalServerError() return response.Error(http.StatusInternalServerError, "An error occurred while fetching this user :(")
} }
if otherUser == nil { if otherUser == nil {
return response.Error("User not found").StatusInternalServerError() return response.Error(http.StatusInternalServerError, "User not found")
} }
giftCount, err := otherUser.WishCount() giftCount, err := otherUser.WishCount()
if err != nil { if err != nil {
log.Printf("Couldn't get wishes of user %q on public wishlist: %s\n", otherUser.Name, err) log.Printf("Couldn't get wishes of user %q on public wishlist: %s\n", otherUser.Name, err)
return response.Error("An error occurred while fetching this user :(").StatusInternalServerError() return response.Error(http.StatusInternalServerError, "An error occurred while fetching this user :(")
} }
p := publicWishlistProps{Navbar: templates.DefaultNavCollapse(), Username: otherUser.Name, GiftCount: giftCount, Referrer: r.URL.Path} p := publicWishlistProps{Navbar: templates.DefaultNavCollapse(), Username: otherUser.Name, GiftCount: giftCount}
return response.Data("public_foreign_wishlist.gotmpl", p) return response.Data("public_foreign_wishlist.gotmpl", p)
} }

View File

@ -7,28 +7,25 @@ import (
"slices" "slices"
lishwist "lishwist/core" lishwist "lishwist/core"
"lishwist/http/file"
"lishwist/http/response" "lishwist/http/response"
"lishwist/http/session"
"lishwist/http/templates" "lishwist/http/templates"
"github.com/Teajey/rsvp" "github.com/Teajey/rsvp"
) )
type GroupProps struct { type GroupProps struct {
Navbar templates.NavCollapse Navbar templates.NavCollapse
Group *lishwist.Group Group *lishwist.Group
Referrer string
} }
func AdminGroup(app *lishwist.Session, w rsvp.ResponseWriter, r *http.Request) rsvp.Body { func AdminGroup(app *lishwist.Session, h http.Header, r *http.Request) rsvp.Response {
reference, _ := file.NameAtPathValue(r, "groupReference") reference := r.PathValue("groupReference")
group, err := lishwist.GetGroupByReference(reference) group, err := lishwist.GetGroupByReference(reference)
if err != nil { if err != nil {
return response.Error("Couldn't get group: %s", err).StatusInternalServerError() return response.Error(http.StatusInternalServerError, "Couldn't get group: %s", err)
} }
if group == nil { if group == nil {
return response.Error("Group not found").StatusNotFound() return response.Error(http.StatusNotFound, "Group not found")
} }
user := app.User() user := app.User()
if !user.IsAdmin { if !user.IsAdmin {
@ -36,54 +33,53 @@ func AdminGroup(app *lishwist.Session, w rsvp.ResponseWriter, r *http.Request) r
group.Members = slices.Delete(group.Members, index, index+1) group.Members = slices.Delete(group.Members, index, index+1)
} }
p := GroupProps{ p := GroupProps{
Navbar: templates.UserNavCollapse(user.Name, user.Reference, user.PasswordFromAdmin), Navbar: templates.UserNavCollapse(user.Name, user.PasswordFromAdmin),
Group: group, Group: group,
} }
return response.Data("group_page.gotmpl", p) return response.Data("group_page.gotmpl", p)
} }
func Group(app *lishwist.Session, session *session.Session, w rsvp.ResponseWriter, r *http.Request) rsvp.Body { func Group(app *lishwist.Session, session *response.Session, h http.Header, r *http.Request) rsvp.Response {
user := app.User() user := app.User()
if user.IsAdmin { if user.IsAdmin {
return AdminGroup(app, w, r) return AdminGroup(app, h, r)
} }
groupReference, _ := file.NameAtPathValue(r, "groupReference") groupReference := r.PathValue("groupReference")
group, err := app.GetGroupByReference(groupReference) group, err := app.GetGroupByReference(groupReference)
if err != nil { if err != nil {
log.Printf("Couldn't get group: %s\n", err) log.Printf("Couldn't get group: %s\n", err)
return response.Error("An error occurred while fetching this group :(").StatusInternalServerError() return response.Error(http.StatusInternalServerError, "An error occurred while fetching this group :(")
} }
if group == nil { if group == nil {
return response.Error("Group not found. (It might be because you're not a member)").StatusNotFound() return response.Error(http.StatusNotFound, "Group not found. (It might be because you're not a member)")
} }
index := group.MemberIndex(user.Id) index := group.MemberIndex(user.Id)
group.Members = slices.Delete(group.Members, index, index+1) group.Members = slices.Delete(group.Members, index, index+1)
p := GroupProps{ p := GroupProps{
Navbar: templates.UserNavCollapse(user.Name, user.Reference, user.PasswordFromAdmin), Navbar: templates.UserNavCollapse(user.Name, user.PasswordFromAdmin),
Group: group, Group: group,
} }
return response.Data("group_page.gotmpl", p) return response.Data("group_page.gotmpl", p)
} }
func PublicGroup(s *session.Session, w rsvp.ResponseWriter, r *http.Request) rsvp.Body { func PublicGroup(s *response.Session, h http.Header, r *http.Request) rsvp.Response {
groupReference, _ := file.NameAtPathValue(r, "groupReference") groupReference := r.PathValue("groupReference")
group, err := lishwist.GetGroupByReference(groupReference) group, err := lishwist.GetGroupByReference(groupReference)
if err != nil { if err != nil {
log.Printf("Couldn't get group: %s\n", err) log.Printf("Couldn't get group: %s\n", err)
return response.Error("An error occurred while fetching this group :(").StatusInternalServerError() return response.Error(http.StatusInternalServerError, "An error occurred while fetching this group :(")
} }
if group == nil { if group == nil {
return response.Error("Group not found").StatusNotFound() return response.Error(http.StatusNotFound, "Group not found")
} }
p := GroupProps{ p := GroupProps{
Navbar: templates.DefaultNavCollapse(), Navbar: templates.DefaultNavCollapse(),
Group: group, Group: group,
Referrer: r.URL.Path,
} }
return response.Data("public_group_page.gotmpl", p) return response.Data("public_group_page.gotmpl", p)
} }
func GroupPost(app *lishwist.Session, session *session.Session, w rsvp.ResponseWriter, r *http.Request) rsvp.Body { func GroupPost(app *lishwist.Session, session *response.Session, h http.Header, r *http.Request) rsvp.Response {
admin := app.Admin() admin := app.Admin()
if admin == nil { if admin == nil {
return response.NotFound() return response.NotFound()
@ -91,12 +87,12 @@ func GroupPost(app *lishwist.Session, session *session.Session, w rsvp.ResponseW
err := r.ParseForm() err := r.ParseForm()
if err != nil { if err != nil {
return response.Error("Failed to parse form").StatusBadRequest() return response.Error(http.StatusBadRequest, "Failed to parse form")
} }
var group *lishwist.Group var group *lishwist.Group
reference, _ := file.NameAtPathValue(r, "groupReference") reference := r.PathValue("groupReference")
name := r.Form.Get("name") name := r.Form.Get("name")
addUsers := r.Form["addUser"] addUsers := r.Form["addUser"]
removeUsers := r.Form["removeUser"] removeUsers := r.Form["removeUser"]
@ -104,27 +100,27 @@ func GroupPost(app *lishwist.Session, session *session.Session, w rsvp.ResponseW
if name != "" { if name != "" {
createdGroup, err := admin.CreateGroup(name, reference) createdGroup, err := admin.CreateGroup(name, reference)
if err != nil { if err != nil {
return response.Error("Failed to create group: %s", err).StatusInternalServerError() return response.Error(http.StatusInternalServerError, "Failed to create group: %s", err)
} }
group = createdGroup group = createdGroup
} else { } else {
existingGroup, err := lishwist.GetGroupByReference(reference) existingGroup, err := lishwist.GetGroupByReference(reference)
if err != nil { if err != nil {
return response.Error("Failed to get group: %s", err).StatusInternalServerError() return response.Error(http.StatusInternalServerError, "Failed to get group: %s", err)
} }
if existingGroup == nil { if existingGroup == nil {
return response.Error("Group not found: %s", err).StatusNotFound() return response.Error(http.StatusNotFound, "Group not found: %s", err)
} }
group = existingGroup group = existingGroup
for _, userId := range removeUsers { for _, userId := range removeUsers {
index := group.MemberIndex(userId) index := group.MemberIndex(userId)
if index == -1 { if index == -1 {
return response.Error("Group %q does not contain a user with id %s", reference, userId).StatusBadRequest() return response.Error(http.StatusBadRequest, "Group %q does not contain a user with id %s", reference, userId)
} }
err = admin.RemoveUserFromGroup(userId, group.Id) err = admin.RemoveUserFromGroup(userId, group.Id)
if err != nil { if err != nil {
return response.Error("On group %q failed to remove user with id %s: %s", reference, userId, err).StatusInternalServerError() return response.Error(http.StatusInternalServerError, "On group %q failed to remove user with id %s: %s", reference, userId, err)
} }
group.Members = slices.Delete(group.Members, index, index+1) group.Members = slices.Delete(group.Members, index, index+1)
} }
@ -133,14 +129,14 @@ func GroupPost(app *lishwist.Session, session *session.Session, w rsvp.ResponseW
for _, userId := range addUsers { for _, userId := range addUsers {
user, err := admin.GetUser(userId) user, err := admin.GetUser(userId)
if err != nil { if err != nil {
return response.Error("Groups exists, but a user with id %s could not be fetched: %s", userId, err).StatusInternalServerError() return response.Error(http.StatusInternalServerError, "Groups exists, but a user with id %s could not be fetched: %s", userId, err)
} }
if user == nil { if user == nil {
return response.Error("Groups exists, but a user with id %s does not exist", userId).StatusInternalServerError() return response.Error(http.StatusInternalServerError, "Groups exists, but a user with id %s does not exist", userId)
} }
err = admin.AddUserToGroup(user.Id, group.Id) err = admin.AddUserToGroup(user.Id, group.Id)
if err != nil { if err != nil {
return response.Error("Groups exists, but failed to add user with id %s: %s", userId, err).StatusInternalServerError() return response.Error(http.StatusInternalServerError, "Groups exists, but failed to add user with id %s: %s", userId, err)
} }
group.Members = append(group.Members, *user) group.Members = append(group.Members, *user)
} }
@ -153,7 +149,7 @@ type GroupList struct {
Groups []lishwist.Group `xml:"Group"` Groups []lishwist.Group `xml:"Group"`
} }
func Groups(app *lishwist.Session, session *session.Session, w rsvp.ResponseWriter, r *http.Request) rsvp.Body { func Groups(app *lishwist.Session, session *response.Session, h http.Header, r *http.Request) rsvp.Response {
admin := app.Admin() admin := app.Admin()
if admin == nil { if admin == nil {
return response.NotFound() return response.NotFound()
@ -161,7 +157,7 @@ func Groups(app *lishwist.Session, session *session.Session, w rsvp.ResponseWrit
groups, err := admin.ListGroups() groups, err := admin.ListGroups()
if err != nil { if err != nil {
return response.Error("Failed to get groups: %s", err).StatusInternalServerError() return response.Error(http.StatusInternalServerError, "Failed to get groups: %s", err)
} }
return response.Data("", GroupList{Groups: groups}) return response.Data("", GroupList{Groups: groups})

View File

@ -1,131 +1,60 @@
package routing package routing
import ( import (
"fmt"
"log" "log"
"maps"
"net/http" "net/http"
"slices"
lishwist "lishwist/core" lishwist "lishwist/core"
"lishwist/http/resources" "lishwist/http/env"
"lishwist/http/response" "lishwist/http/response"
"lishwist/http/session"
"lishwist/http/templates" "lishwist/http/templates"
"github.com/Teajey/hmc"
"github.com/Teajey/rsvp" "github.com/Teajey/rsvp"
) )
func mapKeysIntersect(a, b map[string][]string) []string { type HomeProps struct {
var out []string Navbar templates.NavCollapse
for k := range a { Gifts []lishwist.Wish
if _, ok := b[k]; ok { Todo []lishwist.Wish
out = append(out, k) Groups []lishwist.Group
}
}
return out
} }
func Home(app *lishwist.Session, session *session.Session, w rsvp.ResponseWriter, r *http.Request) rsvp.Body { func Home(app *lishwist.Session, session *response.Session, h http.Header, r *http.Request) rsvp.Response {
w.DefaultTemplateName("home.gotmpl")
gifts, err := app.GetWishes() gifts, err := app.GetWishes()
if err != nil { if err != nil {
log.Printf("Failed to get gifts: %s\n", err) log.Printf("Failed to get gifts: %s\n", err)
return response.Error("An error occurred while fetching your wishlist :(").StatusInternalServerError() return response.Error(http.StatusInternalServerError, "An error occurred while fetching your wishlist :(")
} }
user := app.User() user := app.User()
todo, err := user.GetTodo() todo, err := user.GetTodo()
if err != nil { if err != nil {
log.Printf("Failed to get todo: %s\n", err) log.Printf("Failed to get todo: %s\n", err)
return response.Error("An error occurred while fetching your wishlist :(").StatusInternalServerError() return response.Error(http.StatusInternalServerError, "An error occurred while fetching your wishlist :(")
} }
groups, err := app.GetGroups() groups, err := app.GetGroups()
if err != nil { if err != nil {
log.Printf("Failed to get groups: %s\n", err) log.Printf("Failed to get groups: %s\n", err)
return response.Error("An error occurred while fetching your wishlist :(").StatusInternalServerError() return response.Error(http.StatusInternalServerError, "An error occurred while fetching your wishlist :(")
}
p := HomeProps{Navbar: templates.NavCollapse{
User: &templates.User{Name: user.Name, CopyList: &templates.CopyList{Domain: env.Configuration.HostUrl, Reference: user.Reference}},
AccountLink: &templates.AccountLink{Alert: user.PasswordFromAdmin},
}, Gifts: gifts, Todo: todo, Groups: groups}
return response.Data("home.gotmpl", p)
}
func HomePost(app *lishwist.Session, session *response.Session, h http.Header, r *http.Request) rsvp.Response {
err := r.ParseForm()
if err != nil {
return response.Error(http.StatusBadRequest, "Failed to parse form")
}
switch r.Form.Get("intent") {
case "add_idea":
return WishlistAdd(app, h, r)
case "delete_idea":
return WishlistDelete(app, h, r)
default:
return TodoUpdate(app, h, r)
} }
groupLinks := make([]hmc.Link, len(groups))
for i, g := range groups {
groupLinks[i] = hmc.Link{
Label: g.Name,
Href: fmt.Sprintf("groups/%s", g.Reference),
}
}
navbar := templates.UserNavCollapse(user.Name, user.Reference, user.PasswordFromAdmin)
navbar.Links = nil
p := resources.HomeProps{
Namespace: hmc.NS(),
Navbar: navbar,
Wishlist: resources.InitialWishlist(user.Id, gifts),
Todo: resources.InitialTodo(todo),
GroupsList: resources.LinksList{
Label: "Your groups",
Links: groupLinks,
},
}
if r.Method == http.MethodGet {
return rsvp.Data(p)
}
err = r.ParseForm()
if err != nil {
p.Error = "Failed to parse form"
return rsvp.Data(p).StatusUnprocessableEntity()
}
if len(r.Form) < 1 {
p.Error = "No parameters provided"
return rsvp.Data(p).StatusBadRequest()
}
wishForm := maps.Clone(r.Form)
p.Wishlist.ExtractFormValues(wishForm)
p.Todo.ExtractFormValues(r.Form)
extra := mapKeysIntersect(wishForm, r.Form)
if len(extra) > 0 {
p.Warning = "Extraneous form values"
}
if p.Wishlist.Wishes.Elements.Intent.Value() == "delete" {
wishesToDelete := slices.Collect(p.Wishlist.Wishes.Elements.Select.Values())
err := app.RevokeWishes(wishesToDelete...)
if err != nil {
log.Printf("Failed to revoke wishes: %s\n", err)
p.Wishlist.Wishes.Elements.Intent.Error = "Something went wrong"
return rsvp.Data(p).StatusInternalServerError()
}
}
if p.Wishlist.NewWish.Elements.Value != "" {
_, err := app.MakeWish(p.Wishlist.NewWish.Elements.Value)
if err != nil {
log.Printf("Failed to make wish: %s\n", err)
p.Wishlist.NewWish.Elements.Error = "Something went wrong"
return rsvp.Data(p).StatusInternalServerError()
}
}
todosToChange := slices.Collect(p.Todo.Wishes.Elements.Select.Values())
if p.Todo.Wishes.Elements.Intent.Value() == "unclaim_todo" {
err := app.ClaimWishes([]string{}, todosToChange)
if err != nil {
log.Printf("Failed to unclaim wish: %s\n", err)
p.Todo.Wishes.Elements.Intent.Error = "Something went wrong"
return rsvp.Data(p).StatusInternalServerError()
}
} else if p.Todo.Wishes.Elements.Intent.Value() == "complete_todo" {
err := app.CompleteWishes(todosToChange)
if err != nil {
log.Printf("Failed to complete wish: %s\n", err)
p.Todo.Wishes.Elements.Intent.Error = "Something went wrong"
return rsvp.Data(p).StatusInternalServerError()
}
}
return rsvp.Data(p).StatusSeeOther(".")
} }

View File

@ -7,62 +7,53 @@ import (
"time" "time"
lishwist "lishwist/core" lishwist "lishwist/core"
"lishwist/http/props" "lishwist/http/api"
"lishwist/http/session" "lishwist/http/response"
"github.com/Teajey/hmc"
"github.com/Teajey/rsvp" "github.com/Teajey/rsvp"
) )
type LoginPage struct { func Login(s *response.Session, h http.Header, r *http.Request) rsvp.Response {
hmc.Namespace props := api.NewLoginProps("", "")
Form hmc.Form[props.Login]
RegisterLink hmc.Link
}
func NewLoginPage() LoginPage {
return LoginPage{
Namespace: hmc.NS(),
Form: hmc.Form[props.Login]{
Method: "POST",
},
RegisterLink: hmc.Link{
Label: "Register",
Href: "/register",
},
}
}
func Login(s *session.Session, w rsvp.ResponseWriter, r *http.Request) rsvp.Body {
login := props.NewLogin("", "")
flash := s.FlashGet() flash := s.FlashGet()
flashProps, ok := flash.(*props.Login) flashProps, ok := flash.(*api.LoginProps)
if ok { if ok {
login.Username.Value = flashProps.Username.Value props.Username.Value = flashProps.Username.Value
login.GeneralError = flashProps.GeneralError props.GeneralError = flashProps.GeneralError
login.Username.Error = flashProps.Username.Error props.Username.Error = flashProps.Username.Error
login.Password.Error = flashProps.Password.Error props.Password.Error = flashProps.Password.Error
login.SuccessfulRegistration = flashProps.SuccessfulRegistration props.SuccessfulRegistration = flashProps.SuccessfulRegistration
login.SuccessfulSetPassword = flashProps.SuccessfulSetPassword props.SuccessfulSetPassword = flashProps.SuccessfulSetPassword
} }
body := NewLoginPage() return rsvp.Response{TemplateName: "login.gotmpl", Body: props}
body.Form.Elements = login
return rsvp.Body{TemplateName: "login.gotmpl", Data: body}
} }
func LoginMiddle(username, password string, session *session.Session, r *http.Request) *props.Login { func LoginPost(session *response.Session, h http.Header, r *http.Request) rsvp.Response {
login := props.NewLogin(username, password) username, password, ok := r.BasicAuth()
if !ok {
err := r.ParseForm()
if err != nil {
return response.Error(http.StatusBadRequest, "Failed to parse form")
}
valid := login.Validate() username = r.Form.Get("username")
login.Password.Value = "" password = r.Form.Get("password")
}
props := api.NewLoginProps(username, password)
resp := rsvp.SeeOther(r.URL.Path, props)
valid := props.Validate()
props.Password.Value = ""
if !valid { if !valid {
session.FlashSet(&login) session.FlashSet(&props)
log.Printf("Invalid login submission: %#v\n", login) log.Printf("Invalid props: %#v\n", props)
return &login return resp
} }
appSession, err := lishwist.Login(username, password, time.Hour*24) appSession, err := lishwist.Login(username, password, time.Hour*24)
@ -70,43 +61,20 @@ func LoginMiddle(username, password string, session *session.Session, r *http.Re
var targ lishwist.ErrorInvalidCredentials var targ lishwist.ErrorInvalidCredentials
switch { switch {
case errors.As(err, &targ): case errors.As(err, &targ):
login.GeneralError = "Username or password invalid. If you're having trouble accessing your account, you may want to consider asking the System Admin (Thomas) to reset your password" props.GeneralError = "Username or password invalid. If you're having trouble accessing your account, you may want to consider asking the System Admin (Thomas) to reset your password"
session.FlashSet(&login) session.FlashSet(&props)
log.Printf("Invalid credentials: %s: %#v\n", err, login) log.Printf("Invalid credentials: %s: %#v\n", err, props)
return resp
default: default:
login.GeneralError = "Something went wrong." props.GeneralError = "Something went wrong."
session.FlashSet(&login) session.FlashSet(&props)
log.Printf("Login error: %s\n", err) log.Printf("Login error: %s\n", err)
return resp
} }
return &login
} }
session.SetID("") session.SetID("")
session.SetValue("sessionKey", appSession.Key) session.SetValue("sessionKey", appSession.Key)
return nil return rsvp.SeeOther(r.URL.Path, "Login successful!")
}
func LoginPost(session *session.Session, w rsvp.ResponseWriter, r *http.Request) rsvp.Body {
page := NewLoginPage()
err := r.ParseForm()
if err != nil {
page.Form.Elements.GeneralError = "Failed to parse form"
return rsvp.Data(page).StatusUnprocessableEntity()
}
username := r.Form.Get("username")
password := r.Form.Get("password")
login := LoginMiddle(username, password, session, r)
if login != nil {
page.Form.Elements = *login
return rsvp.Data(page).StatusSeeOther("")
}
referrer := r.URL.Query().Get("referrer")
return rsvp.Data("Login successful!").StatusSeeOther(referrer)
} }

View File

@ -1,16 +1,15 @@
package routing package routing
import ( import (
lishwist "lishwist/core" "lishwist/http/response"
"lishwist/http/session"
"net/http" "net/http"
"github.com/Teajey/rsvp" "github.com/Teajey/rsvp"
) )
func LogoutPost(app *lishwist.Session, s *session.Session, w rsvp.ResponseWriter, r *http.Request) rsvp.Body { func LogoutPost(session *response.Session, h http.Header, r *http.Request) rsvp.Response {
s.Options().MaxAge = 0 session.Options().MaxAge = 0
s.ClearValues() session.ClearValues()
return rsvp.Data("Logout successful").StatusSeeOther("/") return rsvp.SeeOther("/", "Logout successful")
} }

View File

@ -8,6 +8,6 @@ import (
"github.com/Teajey/rsvp" "github.com/Teajey/rsvp"
) )
func NotFound(w rsvp.ResponseWriter, r *http.Request) rsvp.Body { func NotFound(s *response.Session, h http.Header, r *http.Request) rsvp.Response {
return response.Error("Page not found").StatusNotFound() return response.Error(http.StatusNotFound, "Page not found")
} }

View File

@ -3,33 +3,32 @@ package routing
import ( import (
"errors" "errors"
lishwist "lishwist/core" lishwist "lishwist/core"
"lishwist/http/props" "lishwist/http/api"
"lishwist/http/response" "lishwist/http/response"
"lishwist/http/session"
"log" "log"
"net/http" "net/http"
"github.com/Teajey/rsvp" "github.com/Teajey/rsvp"
) )
func Register(session *session.Session, w rsvp.ResponseWriter, r *http.Request) rsvp.Body { func Register(session *response.Session, h http.Header, r *http.Request) rsvp.Response {
register := props.NewRegister("", "", "") props := api.NewRegisterProps("", "", "")
flash := session.FlashGet() flash := session.FlashGet()
flashProps, _ := flash.(*props.Register) flashProps, _ := flash.(*api.RegisterProps)
if flashProps != nil { if flashProps != nil {
register.Form.Elements.Username.Value = flashProps.Form.Elements.Username.Value props.Username.Value = flashProps.Username.Value
register.Error = flashProps.Error props.GeneralError = flashProps.GeneralError
register.Form.Elements.Username.Error = flashProps.Form.Elements.Username.Error props.Username.Error = flashProps.Username.Error
register.Form.Elements.ConfirmPassword.Error = flashProps.Form.Elements.ConfirmPassword.Error props.ConfirmPassword.Error = flashProps.ConfirmPassword.Error
} }
return response.Data("register.gotmpl", register) return response.Data("register.gotmpl", props)
} }
func RegisterPost(s *session.Session, w rsvp.ResponseWriter, r *http.Request) rsvp.Body { func RegisterPost(s *response.Session, h http.Header, r *http.Request) rsvp.Response {
var confirmPassword string var confirmPassword string
username, newPassword, ok := r.BasicAuth() username, newPassword, ok := r.BasicAuth()
if ok { if ok {
@ -37,7 +36,7 @@ func RegisterPost(s *session.Session, w rsvp.ResponseWriter, r *http.Request) rs
} else { } else {
err := r.ParseForm() err := r.ParseForm()
if err != nil { if err != nil {
return response.Error("Failed to parse form").StatusBadRequest() return response.Error(http.StatusBadRequest, "Failed to parse form")
} }
username = r.Form.Get("username") username = r.Form.Get("username")
@ -45,34 +44,29 @@ func RegisterPost(s *session.Session, w rsvp.ResponseWriter, r *http.Request) rs
confirmPassword = r.Form.Get("confirmPassword") confirmPassword = r.Form.Get("confirmPassword")
} }
register := props.NewRegister(username, newPassword, confirmPassword) props := api.NewRegisterProps(username, newPassword, confirmPassword)
valid := register.Form.Elements.Validate() valid := props.Validate()
register.Form.Elements.Password.Value = "" props.Password.Value = ""
register.Form.Elements.ConfirmPassword.Value = "" props.ConfirmPassword.Value = ""
if !valid { if !valid {
s.FlashSet(&register) s.FlashSet(&props)
log.Printf("Invalid register submission: %#v\n", register) log.Printf("Invalid register props: %#v\n", props)
return rsvp.Data(register).StatusSeeOther(r.URL.Path) return rsvp.SeeOther(r.URL.Path, props)
} }
_, err := lishwist.Register(username, newPassword) _, err := lishwist.Register(username, newPassword)
if err != nil { if err != nil {
if errors.Is(err, lishwist.ErrorUsernameTaken) { if errors.Is(err, lishwist.ErrorUsernameTaken) {
register.Form.Elements.Username.Error = "Username is taken" props.Username.Error = "Username is taken"
} else { } else {
register.Error = "Something went wrong." props.GeneralError = "Something went wrong."
} }
s.FlashSet(&register) s.FlashSet(&props)
log.Printf("Registration failed: %s\n", err) log.Printf("Registration failed: %s\n", err)
return rsvp.Data(register).StatusSeeOther(r.URL.Path) return rsvp.SeeOther(r.URL.Path, props)
} }
s.FlashSet(&props.Login{SuccessfulRegistration: true}) s.FlashSet(&api.LoginProps{SuccessfulRegistration: true})
referrer := r.URL.Query().Get("referrer") return rsvp.SeeOther("/", "Registration successful!")
if referrer != "" {
return rsvp.Data("Registration successful!").StatusSeeOther("/login?=" + referrer)
} else {
return rsvp.Data("Registration successful!").StatusSeeOther("/")
}
} }

View File

@ -10,10 +10,10 @@ import (
"lishwist/http/response" "lishwist/http/response"
) )
func TodoUpdate(app *lishwist.Session, w rsvp.ResponseWriter, r *http.Request) rsvp.Body { func TodoUpdate(app *lishwist.Session, h http.Header, r *http.Request) rsvp.Response {
err := r.ParseForm() err := r.ParseForm()
if err != nil { if err != nil {
return response.Error("Failed to parse form").StatusBadRequest() return response.Error(http.StatusBadRequest, "Failed to parse form")
} }
switch r.Form.Get("intent") { switch r.Form.Get("intent") {
@ -22,17 +22,17 @@ func TodoUpdate(app *lishwist.Session, w rsvp.ResponseWriter, r *http.Request) r
err := app.ClaimWishes([]string{}, unclaims) err := app.ClaimWishes([]string{}, unclaims)
if err != nil { if err != nil {
log.Printf("%s\n", err) log.Printf("%s\n", err)
return response.Error("Failed to update claim...").StatusInternalServerError() return response.Error(http.StatusInternalServerError, "Failed to update claim...")
} }
case "complete_todo": case "complete_todo":
claims := r.Form["gift"] claims := r.Form["gift"]
err := app.CompleteWishes(claims) err := app.CompleteWishes(claims)
if err != nil { if err != nil {
log.Printf("%s\n", err) log.Printf("%s\n", err)
return response.Error("Failed to complete gifts...").StatusInternalServerError() return response.Error(http.StatusInternalServerError, "Failed to complete gifts...")
} }
default: default:
return response.Error("Invalid intent").StatusBadRequest() return response.Error(http.StatusBadRequest, "Invalid intent")
} }
return rsvp.Data("Update successful").StatusSeeOther("/") return rsvp.SeeOther("/", "Update successful")
} }

View File

@ -3,9 +3,7 @@ package routing
import ( import (
"encoding/xml" "encoding/xml"
lishwist "lishwist/core" lishwist "lishwist/core"
"lishwist/http/file"
"lishwist/http/response" "lishwist/http/response"
"lishwist/http/session"
"net/http" "net/http"
"github.com/Teajey/rsvp" "github.com/Teajey/rsvp"
@ -16,7 +14,7 @@ type UserList struct {
Users []lishwist.User `xml:"User"` Users []lishwist.User `xml:"User"`
} }
func Users(app *lishwist.Session, session *session.Session, w rsvp.ResponseWriter, r *http.Request) rsvp.Body { func Users(app *lishwist.Session, session *response.Session, h http.Header, r *http.Request) rsvp.Response {
admin := app.Admin() admin := app.Admin()
if admin == nil { if admin == nil {
return response.NotFound() return response.NotFound()
@ -24,32 +22,32 @@ func Users(app *lishwist.Session, session *session.Session, w rsvp.ResponseWrite
users, err := admin.ListUsers() users, err := admin.ListUsers()
if err != nil { if err != nil {
return response.Error("Failed to get users: %s", err).StatusInternalServerError() return response.Error(http.StatusInternalServerError, "Failed to get users: %s", err)
} }
return response.Data("", UserList{Users: users}) return response.Data("", UserList{Users: users})
} }
func User(app *lishwist.Session, session *session.Session, w rsvp.ResponseWriter, r *http.Request) rsvp.Body { func User(app *lishwist.Session, session *response.Session, h http.Header, r *http.Request) rsvp.Response {
admin := app.Admin() admin := app.Admin()
if admin == nil { if admin == nil {
return response.NotFound() return response.NotFound()
} }
reference, _ := file.NameAtPathValue(r, "userReference") reference := r.PathValue("userReference")
user, err := lishwist.GetUserByReference(reference) user, err := lishwist.GetUserByReference(reference)
if err != nil { if err != nil {
return response.Error("Failed to get user: %s", err).StatusInternalServerError() return response.Error(http.StatusInternalServerError, "Failed to get user: %s", err)
} }
if user == nil { if user == nil {
return response.Error("User not found").StatusNotFound() return response.Error(http.StatusNotFound, "User not found")
} }
return response.Data("", user) return response.Data("", user)
} }
func UserPost(app *lishwist.Session, session *session.Session, w rsvp.ResponseWriter, r *http.Request) rsvp.Body { func UserPost(app *lishwist.Session, session *response.Session, h http.Header, r *http.Request) rsvp.Response {
admin := app.Admin() admin := app.Admin()
if admin == nil { if admin == nil {
return response.NotFound() return response.NotFound()
@ -57,10 +55,10 @@ func UserPost(app *lishwist.Session, session *session.Session, w rsvp.ResponseWr
err := r.ParseForm() err := r.ParseForm()
if err != nil { if err != nil {
return response.Error("Failed to parse form").StatusBadRequest() return response.Error(http.StatusBadRequest, "Failed to parse form")
} }
reference, _ := file.NameAtPathValue(r, "userReference") reference := r.PathValue("userReference")
intent := r.Form.Get("intent") intent := r.Form.Get("intent")
@ -68,32 +66,32 @@ func UserPost(app *lishwist.Session, session *session.Session, w rsvp.ResponseWr
switch intent { switch intent {
case "delete": case "delete":
if reference == app.User().Reference { if reference == app.User().Reference {
return response.Error("You cannot delete yourself.").StatusForbidden() return response.Error(http.StatusForbidden, "You cannot delete yourself.")
} }
err = admin.UserSetLive(reference, false) err = admin.UserSetLive(reference, false)
if err != nil { if err != nil {
return response.Error("Failed to delete user: %s", err).StatusInternalServerError() return response.Error(http.StatusInternalServerError, "Failed to delete user: %s", err)
} }
case "rename": case "rename":
name := r.Form.Get("display_name") name := r.Form.Get("display_name")
err = admin.RenameUser(reference, name) err = admin.RenameUser(reference, name)
if err != nil { if err != nil {
return response.Error("Failed to rename user: %s", err).StatusInternalServerError() return response.Error(http.StatusInternalServerError, "Failed to rename user: %s", err)
} }
case "set_password": case "set_password":
newPassword := r.Form.Get("new_password") newPassword := r.Form.Get("new_password")
err = admin.SetUserPassword(reference, newPassword) err = admin.SetUserPassword(reference, newPassword)
if err != nil { if err != nil {
return response.Error("Failed to set new password: %s", err).StatusInternalServerError() return response.Error(http.StatusInternalServerError, "Failed to set new password: %s", err)
} }
default: default:
return response.Error("Invalid intent %q", intent).StatusBadRequest() return response.Error(http.StatusBadRequest, "Invalid intent %q", intent)
} }
} }
user, err := lishwist.GetUserByReference(reference) user, err := lishwist.GetUserByReference(reference)
if err != nil { if err != nil {
return response.Error("Failed to get user: %s", err).StatusInternalServerError() return response.Error(http.StatusInternalServerError, "Failed to get user: %s", err)
} }
return response.Data("", user) return response.Data("", user)

View File

@ -7,49 +7,47 @@ import (
"github.com/Teajey/rsvp" "github.com/Teajey/rsvp"
lishwist "lishwist/core" lishwist "lishwist/core"
"lishwist/http/file"
"lishwist/http/response" "lishwist/http/response"
"lishwist/http/session"
) )
func WishlistAdd(app *lishwist.Session, w rsvp.ResponseWriter, r *http.Request) rsvp.Body { func WishlistAdd(app *lishwist.Session, h http.Header, r *http.Request) rsvp.Response {
err := r.ParseForm() err := r.ParseForm()
if err != nil { if err != nil {
return response.Error("Failed to parse form").StatusBadRequest() return response.Error(http.StatusBadRequest, "Failed to parse form")
} }
newGiftName := r.Form.Get("gift_name") newGiftName := r.Form.Get("gift_name")
_, err = app.MakeWish(newGiftName) _, err = app.MakeWish(newGiftName)
if err != nil { if err != nil {
log.Printf("%s\n", err) log.Printf("%s\n", err)
return response.Error("Failed to add gift.").StatusInternalServerError() return response.Error(http.StatusInternalServerError, "Failed to add gift.")
} }
return rsvp.Data("Wish added!").StatusSeeOther("/") return rsvp.SeeOther("/", "Wish added!")
} }
func WishlistDelete(app *lishwist.Session, w rsvp.ResponseWriter, r *http.Request) rsvp.Body { func WishlistDelete(app *lishwist.Session, h http.Header, r *http.Request) rsvp.Response {
err := r.ParseForm() err := r.ParseForm()
if err != nil { if err != nil {
return response.Error("Failed to parse form").StatusBadRequest() return response.Error(http.StatusBadRequest, "Failed to parse form")
} }
targets := r.Form["gift"] targets := r.Form["gift"]
err = app.RevokeWishes(targets...) err = app.RevokeWishes(targets...)
if err != nil { if err != nil {
log.Printf("%s\n", err) log.Printf("%s\n", err)
return response.Error("Failed to remove gifts.").StatusInternalServerError() return response.Error(http.StatusInternalServerError, "Failed to remove gifts.")
} }
return rsvp.Data("Wish deleted").StatusSeeOther("/") return rsvp.SeeOther("/", "Wish deleted")
} }
func ForeignWishlistPost(app *lishwist.Session, session *session.Session, w rsvp.ResponseWriter, r *http.Request) rsvp.Body { func ForeignWishlistPost(app *lishwist.Session, session *response.Session, h http.Header, r *http.Request) rsvp.Response {
err := r.ParseForm() err := r.ParseForm()
if err != nil { if err != nil {
return response.Error("Failed to parse form").StatusBadRequest() return response.Error(http.StatusBadRequest, "Failed to parse form")
} }
userReference, _ := file.NameAtPathValue(r, "userReference") userReference := r.PathValue("userReference")
resp := rsvp.Data("Update successful").StatusSeeOther("/lists/" + userReference) resp := rsvp.SeeOther("/lists/"+userReference, "Update successful")
intent := r.Form.Get("intent") intent := r.Form.Get("intent")
switch intent { switch intent {
case "claim": case "claim":
@ -58,28 +56,28 @@ func ForeignWishlistPost(app *lishwist.Session, session *session.Session, w rsvp
err := app.ClaimWishes(claims, unclaims) err := app.ClaimWishes(claims, unclaims)
if err != nil { if err != nil {
log.Printf("%s\n", err) log.Printf("%s\n", err)
return response.Error("Failed to update claim...").StatusInternalServerError() return response.Error(http.StatusInternalServerError, "Failed to update claim...")
} }
resp.Data = "Successfully claimed wishes" resp.Body = "Successfully claimed wishes"
case "complete": case "complete":
claims := r.Form["claimed"] claims := r.Form["claimed"]
err := app.CompleteWishes(claims) err := app.CompleteWishes(claims)
if err != nil { if err != nil {
log.Printf("%s\n", err) log.Printf("%s\n", err)
return response.Error("Failed to complete gifts...").StatusInternalServerError() return response.Error(http.StatusInternalServerError, "Failed to complete gifts...")
} }
resp.Data = "Successfully completed wishes" resp.Body = "Successfully completed wishes"
case "add": case "add":
wishName := r.Form.Get("gift_name") wishName := r.Form.Get("gift_name")
if wishName == "" { if wishName == "" {
return response.Error("Gift name not provided").StatusBadRequest() return response.Error(http.StatusBadRequest, "Gift name not provided")
} }
err := app.SuggestWishForUser(userReference, wishName) err := app.SuggestWishForUser(userReference, wishName)
if err != nil { if err != nil {
log.Printf("%s\n", err) log.Printf("%s\n", err)
return response.Error("Failed to add gift idea to other user...").StatusInternalServerError() return response.Error(http.StatusInternalServerError, "Failed to add gift idea to other user...")
} }
resp.Data = "Successfully added wishes" resp.Body = "Successfully added wishes"
case "delete": case "delete":
claims := r.Form["unclaimed"] claims := r.Form["unclaimed"]
unclaims := r.Form["claimed"] unclaims := r.Form["claimed"]
@ -87,11 +85,11 @@ func ForeignWishlistPost(app *lishwist.Session, session *session.Session, w rsvp
err := app.RecindWishesForUser(gifts...) err := app.RecindWishesForUser(gifts...)
if err != nil { if err != nil {
log.Printf("%s\n", err) log.Printf("%s\n", err)
return response.Error("Failed to remove gift idea for other user...").StatusInternalServerError() return response.Error(http.StatusInternalServerError, "Failed to remove gift idea for other user...")
} }
resp.Data = "Successfully removed wishes" resp.Body = "Successfully removed wishes"
default: default:
return response.Error("Invalid intent %q", intent).StatusBadRequest() return response.Error(http.StatusBadRequest, "Invalid intent %q", intent)
} }
return resp return resp
} }

View File

@ -3,22 +3,35 @@ package server
import ( import (
"encoding/gob" "encoding/gob"
"net/http" "net/http"
"strings"
lishwist "lishwist/core" "lishwist/http/api"
"lishwist/http/env" "lishwist/http/env"
"lishwist/http/file" "lishwist/http/response"
"lishwist/http/middleware" "lishwist/http/router"
"lishwist/http/mux"
"lishwist/http/props"
"lishwist/http/routing" "lishwist/http/routing"
"lishwist/http/session" "lishwist/http/session"
"github.com/Teajey/rsvp" "github.com/Teajey/rsvp"
) )
func Create(useSecureCookies bool) *mux.Serve { func prefixMovedPermanently(before, after string) response.HandlerFunc {
gob.Register(&props.Register{}) return func(s *response.Session, h http.Header, r *http.Request) rsvp.Response {
gob.Register(&props.Login{}) suffix := strings.TrimPrefix(r.RequestURI, before)
return rsvp.MovedPermanently(after + suffix)
}
}
func prefixPermanentRedirect(before, after string) response.HandlerFunc {
return func(s *response.Session, h http.Header, r *http.Request) rsvp.Response {
suffix := strings.TrimPrefix(r.RequestURI, before)
return rsvp.PermanentRedirect(after + suffix)
}
}
func Create(useSecureCookies bool) *router.VisibilityRouter {
gob.Register(&api.RegisterProps{})
gob.Register(&api.LoginProps{})
gob.Register(&routing.AccountProps{}) gob.Register(&routing.AccountProps{})
store := session.NewInMemoryStore([]byte(env.Configuration.SessionSecret)) store := session.NewInMemoryStore([]byte(env.Configuration.SessionSecret))
@ -28,60 +41,37 @@ func Create(useSecureCookies bool) *mux.Serve {
store.Options.Path = "/" store.Options.Path = "/"
store.Options.SameSite = http.SameSiteLaxMode store.Options.SameSite = http.SameSiteLaxMode
r := mux.New(store) r := router.New(store)
r.Public.HandleFunc("GET /", routing.Login)
r.Public.HandleFunc("GET /groups/{groupReference}", routing.PublicGroup) r.Public.HandleFunc("GET /groups/{groupReference}", routing.PublicGroup)
r.Public.HandleFunc("GET /lists/{userReference}", routing.PublicWishlist) r.Public.HandleFunc("GET /lists/{userReference}", routing.PublicWishlist)
r.Public.HandleFunc("GET /", routing.Login) r.Public.HandleFunc("GET /register", routing.Register)
r.Public.HandleFunc("GET /{file}", func(s *session.Session, w rsvp.ResponseWriter, r *http.Request) rsvp.Body {
filestem, _ := file.NameAtPathValue(r, "file")
switch filestem {
case "login":
return routing.Login(s, w, r)
case "register":
return routing.Register(s, w, r)
}
return rsvp.Blank().StatusNotFound()
})
r.Public.HandleFunc("POST /register", routing.RegisterPost)
r.Public.HandleFunc("POST /", routing.LoginPost) r.Public.HandleFunc("POST /", routing.LoginPost)
r.Public.HandleFunc("POST /register", routing.RegisterPost)
r.Private.HandleFunc("GET /groups/{groupReference}", routing.Group) r.Private.HandleFunc("GET /events", routing.ExpectAppSession(routing.EventList))
r.Private.HandleFunc("GET /lists/{userReference}", routing.ForeignWishlist) r.Private.HandleFunc("GET /account", routing.ExpectAppSession(routing.Account))
r.Private.HandleFunc("GET /users/{userReference}", routing.User) r.Private.HandleFunc("GET /health", routing.ExpectAppSession(routing.Health))
r.Private.HandleFunc("GET /{$}", routing.Home) r.Private.HandleFunc("GET /", routing.NotFound)
r.Private.HandleFunc("GET /{file}", func(app *lishwist.Session, s *session.Session, w rsvp.ResponseWriter, r *http.Request) rsvp.Body { r.Private.HandleFunc("GET /groups", routing.ExpectAppSession(routing.Groups))
filestem, _ := file.NameAtPathValue(r, "file") r.Private.HandleFunc("GET /groups/{groupReference}", routing.ExpectAppSession(routing.Group))
switch filestem { r.Private.HandleFunc("GET /lists/{userReference}", routing.ExpectAppSession(routing.ForeignWishlist))
case "account": r.Private.HandleFunc("GET /users", routing.ExpectAppSession(routing.Users))
return routing.Account(app, s, w, r) r.Private.HandleFunc("GET /users/{userReference}", routing.ExpectAppSession(routing.User))
case "events": r.Private.HandleFunc("GET /{$}", routing.ExpectAppSession(routing.Home))
return routing.EventList(app, s, w, r) r.Private.HandleFunc("POST /account", routing.ExpectAppSession(routing.AccountPost))
case "groups": r.Private.HandleFunc("POST /groups/{groupReference}", routing.ExpectAppSession(routing.GroupPost))
return routing.Groups(app, s, w, r) r.Private.HandleFunc("POST /lists/{userReference}", routing.ExpectAppSession(routing.ForeignWishlistPost))
case "health":
return routing.Health(app, s, w, r)
case "home":
return routing.Home(app, s, w, r)
case "users":
return routing.Users(app, s, w, r)
}
return routing.NotFound(w, r)
})
r.Private.HandleFunc("POST /account", routing.AccountPost)
r.Private.HandleFunc("POST /groups/{groupReference}", routing.GroupPost)
r.Private.HandleFunc("POST /lists/{userReference}", routing.ForeignWishlistPost)
r.Private.HandleFunc("POST /logout", routing.LogoutPost) r.Private.HandleFunc("POST /logout", routing.LogoutPost)
r.Private.HandleFunc("POST /users/{userReference}", routing.UserPost) r.Private.HandleFunc("POST /users/{userReference}", routing.ExpectAppSession(routing.UserPost))
r.Private.HandleFunc("POST /{$}", routing.Home) r.Private.HandleFunc("POST /{$}", routing.ExpectAppSession(routing.HomePost))
// Deprecated // Deprecated
r.HandleFunc("GET /group/{groupReference}", middleware.PrefixMovedPermanently("/group/", "/groups/")) r.HandleFunc("GET /group/{groupReference}", prefixMovedPermanently("/group/", "/groups/"))
r.HandleFunc("GET /list/{groupReference}", middleware.PrefixMovedPermanently("/list/", "/lists/")) r.HandleFunc("GET /list/{groupReference}", prefixMovedPermanently("/list/", "/lists/"))
r.HandleFunc("POST /group/{groupReference}", middleware.PrefixPermanentRedirect("/group/", "/groups/")) r.HandleFunc("POST /group/{groupReference}", prefixPermanentRedirect("/group/", "/groups/"))
r.HandleFunc("POST /list/{groupReference}", middleware.PrefixPermanentRedirect("/list/", "/lists/")) r.HandleFunc("POST /list/{groupReference}", prefixPermanentRedirect("/list/", "/lists/"))
return r return r
} }

View File

@ -1,6 +1,6 @@
{{define "input"}} {{define "input"}}
<input style="padding: .375rem .75rem;" class="form-control{{if .Error}} is-invalid{{end}}" {{if .Type}}type="{{.Type}}" {{end}}name="{{.Name}}" <input style="padding: .375rem .75rem;" class="form-control{{if .Error}} is-invalid{{end}}" {{if .Type}}type="{{.Type}}" {{end}}name="{{.Name}}"
value="{{.Value}}" {{if .Required}}required {{end}}{{if .MinLength}}minlength="{{.MinLength}}" {{end}}{{with .Error}} aria-describedby="{{.Name}}Error"{{end}}> value="{{.Value}}" {{if .Required}}required {{end}}{{if .MinLength}}minlength="{{.MinLength}}" {{end}} aria-describedby="{{if .Error}}{{.Name}}Error{{end}}">
{{with .Error}} {{with .Error}}
<div id="{{$.Name}}Error" class="invalid-feedback"> <div id="{{$.Name}}Error" class="invalid-feedback">
{{.}} {{.}}
@ -12,10 +12,6 @@
{{end}} {{end}}
{{end}} {{end}}
{{define "hyperlink"}}
<a href="{{.Href}}">{{.Label}}</a>
{{end}}
{{define "head"}} {{define "head"}}
<title>Lishwist</title> <title>Lishwist</title>
<meta name="viewport" content="width=device-width, initial-scale=1"> <meta name="viewport" content="width=device-width, initial-scale=1">
@ -25,6 +21,7 @@
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js" <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"
integrity="sha384-YvpcrYf0tY3lHB60NNkmXc5s9fDVZLESaAA55NDzOxhy9GkcIdslK1eN7N6jIeHz" integrity="sha384-YvpcrYf0tY3lHB60NNkmXc5s9fDVZLESaAA55NDzOxhy9GkcIdslK1eN7N6jIeHz"
crossorigin="anonymous"></script> crossorigin="anonymous"></script>
<script> <script>
function getSubmissionNames(form) { function getSubmissionNames(form) {
return Array.from(new FormData(form).keys()); return Array.from(new FormData(form).keys());
@ -48,20 +45,19 @@
<div class="navbar navbar-expand-lg bg-body-tertiary"> <div class="navbar navbar-expand-lg bg-body-tertiary">
<div class="container-fluid"> <div class="container-fluid">
<div class="navbar-brand">Lishwist</div> <div class="navbar-brand">Lishwist</div>
{{with .User}} {{with .}}
<button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarToggle" <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarToggle"
aria-controls="navbarToggle" aria-expanded="false" aria-label="Toggle navigation"> aria-controls="navbarToggle" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>{{if .Alert}} <span <span class="navbar-toggler-icon"></span>{{if and .AccountLink .AccountLink.Alert}} <span
class="badge text-bg-danger">!</span>{{end}} class="badge text-bg-danger">!</span>{{end}}
</button> </button>
{{end}}
<div class="collapse navbar-collapse" id="navbarToggle"> <div class="collapse navbar-collapse" id="navbarToggle">
{{with .Links}} {{with .Links}}
<nav> <nav>
<ul class="navbar-nav"> <ul class="navbar-nav">
{{range .}} {{range .}}
<li class="nav-item"> <li class="nav-item">
<a class="nav-link" href="{{.Href}}">{{.Label}}</a> <a class="nav-link" href="{{.Href}}">{{.Name}}</a>
</li> </li>
{{end}} {{end}}
</ul> </ul>
@ -70,46 +66,39 @@
<div class="flex-grow-1"></div> <div class="flex-grow-1"></div>
{{with .User}} {{with .User}}
<ul class="navbar-nav"> <ul class="navbar-nav">
{{ if .Link -}} {{with .CopyList}}
<li class="nav-item"> <li class="nav-item"><button class="btn btn-success"
<button onclick="navigator.clipboard.writeText('{{.Domain}}/lists/{{.Reference}}'); alert('The share link to your wishlist has been copied to your clipboard. Anyone with the link will be able to claim gifts for you. Share it with someone!');">Copy
class="btn btn-success" share link</button></li>
onclick="navigator.clipboard.writeText('{{.Link.Href}}'); alert('The share link to your wishlist has been copied to your clipboard. Anyone with the link will be able to claim gifts for you. Share it with someone!');"> {{end}}
{{.Link.Label}}
</button>
</li>
{{ end -}}
<li class="nav-item"> <li class="nav-item">
<div class="dropdown"> <div class="dropdown">
<button class="nav-link dropdown-toggle" data-bs-toggle="dropdown" aria-expanded="false"> <button class="nav-link dropdown-toggle" data-bs-toggle="dropdown" aria-expanded="false">
{{.Label}}{{if .Alert}} <span class="badge text-bg-danger">!</span>{{end}} Logged in as '{{.Name}}'{{if and $.AccountLink $.AccountLink.Alert}} <span class="badge text-bg-danger">!</span>{{end}}
</button> </button>
<ul class="dropdown-menu"> <ul class="dropdown-menu">
{{ if .Account -}} {{with $.AccountLink}}
<li> <li>
<a class="dropdown-item" href="{{.Account.Href}}">{{.Account.Label}}{{if .Alert}} <span <a class="dropdown-item" href="/account">Account{{if .Alert}} <span
class="badge text-bg-danger">!</span>{{end}}</a> class="badge text-bg-danger">!</span>{{end}}</a>
</li> </li>
{{ end -}} {{end}}
{{- with .Logout}}
<li> <li>
<form class="d-contents" method="{{.Method}}" action="{{.Action}}"> <form class="d-contents" method="post" action="/logout">
{{- with .Elements}} <button class="dropdown-item" type="submit">Logout</button>
<button class="dropdown-item" type="{{.Type}}">{{.Label}}</button>
{{- end}}
</form> </form>
</li> </li>
{{- end}}
</ul> </ul>
</div> </div>
</li> </li>
</ul> </ul>
{{end}} {{end}}
</div> </div>
{{end}}
</div> </div>
</div> </div>
{{end}} {{end}}
{{define "login_prompt"}} {{define "login_prompt"}}
<a href="/login?referrer={{.}}">Login</a> or <a href="/register?referrer={{.}}">register</a> <a href="/">Login</a> or <a href="/register">register</a>
{{end}} {{end}}

View File

@ -10,99 +10,83 @@
{{template "navbar" .Navbar}} {{template "navbar" .Navbar}}
<div class="overflow-y-scroll flex-grow-1"> <div class="overflow-y-scroll flex-grow-1">
<div class="container py-5"> <div class="container py-5">
{{- with .Wishlist}}
<section class="card mb-4"> <section class="card mb-4">
<div class="card-body"> <div class="card-body">
<h2>{{.Label}}</h2> <h2>Your wishlist</h2>
{{with .Wishes.Elements}} {{with .Gifts}}
<form method="post" onchange="acceptNames(this, 'deleteSubmit', 'wish')" autocomplete="off"> <form method="post" onchange="acceptNames(this, 'deleteSubmit', 'gift')" autocomplete="off">
<ul class="list-group mb-3"> <ul class="list-group mb-3">
{{range .Items}} {{range .}}
<li class="list-group-item"> <li class="list-group-item">
<input id="wishlist_select_{{.Input.Value}}" class="form-check-input" type="{{.Input.Type}}" name="{{.Input.Name}}" <input id="wishlist_select_{{.Id}}" class="form-check-input" type="checkbox" name="gift"
value="{{.Input.Value}}"> value="{{.Id}}">
<label class="form-check-label stretched-link" for="wishlist_select_{{.Input.Value}}"> <label class="form-check-label stretched-link" for="wishlist_select_{{.Id}}">
{{.Input.Label}} {{.Name}}
</label> </label>
</li> </li>
{{end}} {{end}}
</ul> </ul>
<button id="deleteSubmit" class="btn btn-danger mb-3" name="intent" value="delete" <button id="deleteSubmit" class="btn btn-danger mb-3" type="submit" name="intent" value="delete_idea"
disabled>Delete</button> disabled>Delete</button>
</form> </form>
{{else}} {{else}}
<p>Your list is empty. Think of some things to add!</p> <p>Your list is empty. Think of some things to add!</p>
{{end}} {{end}}
{{- with .NewWish}} <form method="post">
<form method="{{.Method}}">
{{- with .Elements}}
<div class="input-group"> <div class="input-group">
<input class="form-control" name="{{.Name}}" {{- if .Required}} required {{- end}} placeholder="Write a gift idea here" autofocus> <input class="form-control" name="gift_name" required placeholder="Write a gift idea here" autofocus>
<button class="btn btn-primary" type="submit" name="intent" value="add_idea">{{.Label}}</button> <button class="btn btn-primary" type="submit" name="intent" value="add_idea">Add gift idea</button>
</div> </div>
{{- end}}
</form> </form>
{{- end}}
</div> </div>
</section> </section>
{{- end}}
{{- with .Todo}}
<section class="card mb-4"> <section class="card mb-4">
<div class="card-body"> <div class="card-body">
<h2>{{.Label}}</h2> <h2>Your todo list</h2>
{{with .Wishes}} {{with .Todo}}
<form method="{{.Method}}" <form method="post"
onchange="acceptNames(this, 'unclaimSubmit', 'todo'); acceptNames(this, 'completeSubmit', 'todo')" onchange="acceptNames(this, 'unclaimSubmit', 'gift'); acceptNames(this, 'completeSubmit', 'gift')"
autocomplete="off"> autocomplete="off">
{{- with .Elements}}
<ul class="list-group mb-3"> <ul class="list-group mb-3">
{{range .Items}} {{range .}}
<li class="list-group-item{{if .Input.Disabled}} list-group-item-light{{end}}"> <li class="list-group-item{{if .Sent}} list-group-item-light{{end}}">
<input id="todo_select_{{.Input.Value}}" class="form-check-input" type="{{.Input.Type}}" {{if .Input.Disabled}} <input id="todo_select_{{.Id}}" class="form-check-input" type="checkbox" {{if .Sent}}
aria-describedby="todo_detail_{{.Input.Value}}" disabled{{else}} name="{{.Input.Name}}" value="{{.Input.Value}}" {{end}}> aria-describedby="todo_detail_{{.Id}}" disabled{{else}} name="gift" value="{{.Id}}" {{end}}>
<label for="todo_select_{{.Input.Value}}" class="form-check-label"> <label for="todo_select_{{.Id}}" class="form-check-label">
<em> <em>
{{if .Input.Disabled}} {{if .Sent}}
<s>{{.Input.Label}}</s> <s>{{.Name}}</s>
{{else}} {{else}}
{{.Input.Label}} {{.Name}}
{{end}} {{end}}
</em> </em>
</label> </label>
<span id="todo_detail_{{.Input.Value}}"> <span id="todo_detail_{{.Id}}">
for <a href="{{.Recipient.Href}}">{{.Recipient.Label}}</a> for <a href="/lists/{{.RecipientRef}}">{{.RecipientName}}</a>
</span> </span>
</li> </li>
{{end}} {{end}}
</ul> </ul>
{{ range .Intent.Options -}} <button id="unclaimSubmit" class="btn btn-warning" type="submit" name="intent" value="unclaim_todo"
{{ if eq .Value "unclaim_todo" }}
<button id="unclaimSubmit" class="btn btn-warning" name="intent" value="unclaim_todo"
disabled>Unclaim</button> disabled>Unclaim</button>
{{ else if eq .Value "complete_todo" -}} <button id="completeSubmit" class="btn btn-success" type="submit" name="intent" value="complete_todo"
<button id="completeSubmit" class="btn btn-success" name="intent" value="complete_todo"
disabled>Complete</button> disabled>Complete</button>
{{ end -}}
{{ end -}}
{{- end}}
</form> </form>
{{else}} {{else}}
<p class="mb-0">When you claim gifts for others, they will appear here.</p> <p class="mb-0">When you claim gifts for others, they will appear here.</p>
{{end}} {{end}}
</div> </div>
</section> </section>
{{- end}}
{{with .GroupsList}}
<section class="card"> <section class="card">
<div class="card-body"> <div class="card-body">
<h2>{{.Label}}</h2> <h2>Your groups</h2>
{{with .Links}} {{with .Groups}}
<ul class="list-group"> <ul class="list-group">
{{range .}} {{range .}}
<li class="list-group-item"> <li class="list-group-item">
<a href="{{.Href}}">{{.Label}}</a> <a href="/groups/{{.Reference}}">{{.Name}}</a>
</li> </li>
{{end}} {{end}}
</ul> </ul>
@ -111,7 +95,6 @@
{{end}} {{end}}
</div> </div>
</section> </section>
{{end}}
</div> </div>
</div> </div>
</div> </div>

View File

@ -4,7 +4,6 @@
{{template "head"}} {{template "head"}}
</head> </head>
{{with .Form.Elements}}
<body> <body>
<div style="height: 100svh;" class="d-flex flex-column"> <div style="height: 100svh;" class="d-flex flex-column">
{{template "navbar"}} {{template "navbar"}}
@ -24,24 +23,23 @@
<p class="mb-0">{{.}}</p> <p class="mb-0">{{.}}</p>
</div> </div>
{{end}} {{end}}
<form method="{{$.Form.Method}}"> <form method="post">
<div class="d-flex flex-column"> <div class="d-flex flex-column">
<label> <label>
{{.Username.Label}} Username
{{template "input" .Username}} {{template "input" .Username}}
</label> </label>
<label> <label>
{{.Password.Label}} Password
{{template "input" .Password}} {{template "input" .Password}}
</label> </label>
<div class="mb-3"> <div class="mb-3">
{{template "hyperlink" $.RegisterLink}} <a href="/register">Register</a>
</div> </div>
<button class="btn btn-primary" type="submit">Login</button> <input class="btn btn-primary" type="submit" value="Login">
</div> </div>
</form> </form>
</div> </div>
</div> </div>
</body> </body>
{{end}}
</html> </html>

View File

@ -14,14 +14,14 @@
<h2>{{.Username}}'s list</h2> <h2>{{.Username}}'s list</h2>
{{if eq .GiftCount 0}} {{if eq .GiftCount 0}}
<p>{{.Username}} hasn't written any gift ideas!</p> <p>{{.Username}} hasn't written any gift ideas!</p>
<p>{{template "login_prompt" .Referrer}} to add some! :^)</p> <p>{{template "login_prompt"}} to add some! :^)</p>
{{else}} {{else}}
{{if eq .GiftCount 1}} {{if eq .GiftCount 1}}
<p>{{.Username}} has only written one gift idea.</p> <p>{{.Username}} has only written one gift idea.</p>
<p>{{template "login_prompt" .Referrer}} to claim it, or add more! :^)</p> <p>{{template "login_prompt"}} to claim it, or add more! :^)</p>
{{else}} {{else}}
<p>{{.Username}} has written {{.GiftCount}} gift ideas.</p> <p>{{.Username}} has written {{.GiftCount}} gift ideas.</p>
<p>{{template "login_prompt" .Referrer}} to claim an idea, or add more! :^)</p> <p>{{template "login_prompt"}} to claim an idea, or add more! :^)</p>
{{end}} {{end}}
{{end}} {{end}}
</div> </div>

View File

@ -12,7 +12,7 @@
<section class="card"> <section class="card">
<div class="card-body"> <div class="card-body">
<h2><em>{{.Group.Name}}</em> group members</h2> <h2><em>{{.Group.Name}}</em> group members</h2>
<p>{{template "login_prompt" .Referrer}} to see your groups</p> <p>{{template "login_prompt"}} to see your groups</p>
{{with .Group.Members}} {{with .Group.Members}}
<ul class="list-group"> <ul class="list-group">
{{range .}} {{range .}}

View File

@ -6,39 +6,34 @@
<body> <body>
<div style="height: 100svh;" class="d-flex flex-column"> <div style="height: 100svh;" class="d-flex flex-column">
{{template "navbar" .Nav}} {{template "navbar" .Navbar}}
<div class="container d-flex flex-grow-1 justify-content-center align-items-center flex-column"> <div class="container d-flex flex-grow-1 justify-content-center align-items-center flex-column">
{{with .Warning}}
<div class="alert alert-warning" role="alert"> <div class="alert alert-warning" role="alert">
{{.}} <p>Your password will be stored in a safe, responsible manner; but don't trust my programming skills!</p>
<p class="mb-0">Maybe use a password here that you don't use for important things...</p>
</div> </div>
{{end}} {{with .GeneralError}}
{{with .Error}}
<div class="alert alert-danger" role="alert"> <div class="alert alert-danger" role="alert">
<p class="mb-0">{{.}}</p> <p class="mb-0">{{.}}</p>
</div> </div>
{{end}} {{end}}
{{with .Form}} <form method="post">
<form method="{{.Method}}">
{{with .Elements}}
<div class="d-flex flex-column"> <div class="d-flex flex-column">
<label> <label>
{{.Username.Label}} Username
{{template "input" .Username}} {{template "input" .Username}}
</label> </label>
<label> <label>
{{.Password.Label}} Password
{{template "input" .Password}} {{template "input" .Password}}
</label> </label>
<label> <label>
{{.ConfirmPassword.Label}} Confirm password
{{template "input" .ConfirmPassword}} {{template "input" .ConfirmPassword}}
</label> </label>
<button class="btn btn-primary" type="submit">Register</button> <input class="btn btn-primary" type="submit" value="Register">
</div> </div>
{{end}}
</form> </form>
{{end}}
</div> </div>
</div> </div>
</body> </body>

View File

@ -3,54 +3,69 @@ package templates
import ( import (
"fmt" "fmt"
"html/template" "html/template"
"lishwist/http/env"
"github.com/Teajey/hmc"
) )
type NavUser struct { type AccountLink struct {
Label string `json:"label" xml:",chardata"` Alert bool
Alert bool `json:"alert,omitempty" xml:",omitempty"` }
Link *hmc.Link `json:"link,omitempty" xml:",omitempty"`
Account *hmc.Link `json:"account,omitempty" xml:",omitempty"` type Link struct {
Logout hmc.Form[hmc.Input] `json:"logout"` Href string
Name string
}
type CopyList struct {
Domain string
Reference string
}
type User struct {
Name string
CopyList *CopyList
} }
type NavCollapse struct { type NavCollapse struct {
Links []hmc.Link User *User
User *NavUser `json:",omitempty"` AccountLink *AccountLink
Links []Link
} }
func DefaultNavCollapse() NavCollapse { func DefaultNavCollapse() NavCollapse {
return NavCollapse{Links: []hmc.Link{{Href: "/", Label: "Home"}}} return NavCollapse{Links: []Link{{Href: "/", Name: "Home"}}}
} }
func UserNavCollapse(username, reference string, accountAlert bool) NavCollapse { func UserNavCollapse(username string, accountAlert bool) NavCollapse {
return NavCollapse{ return NavCollapse{
Links: []hmc.Link{{Href: "/", Label: "Home"}}, Links: []Link{{Href: "/", Name: "Home"}},
User: &NavUser{ User: &User{Name: username},
Label: fmt.Sprintf("Logged in as '%s'", username), AccountLink: &AccountLink{Alert: accountAlert},
Alert: accountAlert,
Link: &hmc.Link{
Label: "Share link",
Href: fmt.Sprintf("%s/lists/%s", env.Configuration.HostUrl, reference),
},
Account: &hmc.Link{
Label: "Account",
Href: "/account",
},
Logout: hmc.Form[hmc.Input]{
Method: "POST",
Action: "/logout",
Elements: hmc.Input{
Label: "Logout",
Type: "submit",
},
},
},
} }
} }
type InputProps struct {
Type string `json:",omitempty"`
Name string
Required bool `json:",omitempty"`
Value string
Error string `json:",omitempty"`
MinLength uint `json:",omitempty"`
}
func (p *InputProps) Validate() bool {
if p.Required && p.Value == "" {
p.Error = fmt.Sprintf("%v is required", p.Name)
return false
}
value_len := len(p.Value)
if p.MinLength > 0 && int(p.MinLength) > value_len {
p.Error = fmt.Sprintf("%v requires at least %v characters (currently %v characters)", p.Name, p.MinLength, value_len)
return false
}
return true
}
var Template *template.Template var Template *template.Template
func init() { func init() {

View File

@ -14,3 +14,4 @@ func load() *template.Template {
t := template.Must(template.ParseGlob("templates/text/*.gotmpl")) t := template.Must(template.ParseGlob("templates/text/*.gotmpl"))
return t return t
} }

View File

@ -2,23 +2,10 @@
APISNAP=api.snap.txt APISNAP=api.snap.txt
./scripts/staged_files_match './scripts/**' 'core/**/*.go' && ./scripts/api_snapshot ./core > core/$APISNAP ./scripts/api_snapshot ./core > core/$APISNAP
git diff --quiet core/$APISNAP
if ! git diff --quiet core/$APISNAP; then if [[ $? -ne 0 ]]; then
echo "There are unstaged changes to $APISNAP" echo "There are unstaged changes to $APISNAP"
exit 1 exit 1
fi fi
if ./scripts/staged_files_match 'assert/**' 'core/**/*'; then
go test ./core/... || {
echo "./core test failure"
exit 1
}
fi
if ./scripts/staged_files_match 'assert/**' 'http/props/htmlx/**/*.go'; then
go test ./http/props/htmlx/... || {
echo "./http test failure"
exit 1
}
fi

View File

@ -1,15 +0,0 @@
#!/usr/bin/env bash
if [ $# -eq 0 ]; then
echo "Usage: $0 <file> [file2] ..." >&2
exit 1
fi
for file in "$@"; do
if [ ! -f "$file" ]; then
echo "Error: File not found: $file" >&2
exit 1
fi
printf '\n\n\n ## FROM %s\n\n' "$file"
cat "$file"
done

View File

@ -1,48 +0,0 @@
#!/bin/bash
# staged_files_match - Check if any staged files match the provided glob patterns
#
# Usage: staged_files_match <pattern1> [pattern2] [...]
#
# Exits 0 (success) if at least one staged file matches any pattern
# Exits 1 (failure) if no staged files match any pattern
#
# Example:
# staged_files_match './assert/**' './core/**/*.go' && go test ./core/...
set -e
# Check if at least one argument provided
if [[ $# -eq 0 ]]; then
echo "Error: No glob patterns provided" >&2
echo "Usage: $0 <pattern1> [pattern2] [...]" >&2
exit 2
fi
# Get all staged files (including renamed files)
staged_files=$(git diff --cached --name-only --diff-filter=ACMR)
# If no staged files, exit with failure
if [[ -z "$staged_files" ]]; then
exit 1
fi
# Check each glob pattern against each staged file
for pattern in "$@"; do
# Remove './' prefix if present for consistent matching
pattern="${pattern#./}"
while IFS= read -r file; do
# Remove './' prefix from file if present
file="${file#./}"
# Use case for glob matching
case "$file" in
$pattern)
exit 0
;;
esac
done <<< "$staged_files"
done
exit 1

View File

@ -1,30 +0,0 @@
#!/usr/bin/env bash
set -euo pipefail
if [[ $# -eq 0 ]]; then
echo "Usage: upfind <glob> [glob...]" >&2
exit 1
fi
dir="$(pwd)"
dirs=()
while true; do
dirs+=("$dir")
parent="$(dirname "$dir")"
if [[ "$parent" == "$dir" ]]; then
break
fi
dir="$parent"
done
for (( i=${#dirs[@]}-1; i>=0; i-- )); do
for glob in "$@"; do
for match in "${dirs[$i]}"/$glob; do
if [[ -e "$match" ]]; then
echo "$match"
fi
done
done
done

View File

@ -1,51 +0,0 @@
#!/usr/bin/env bash
if [ $# -eq 0 ]; then
echo "Usage: withenv <env-file> [env-file2] ... -- <command> [args]" >&2
exit 1
fi
script_dir=$(dirname "$0")
env_files=()
cmd_args=()
parsing_files=true
for arg in "$@"
do
if [ "$arg" = "--" ]
then
parsing_files=false
continue
fi
if $parsing_files
then
env_files+=("$arg")
else
cmd_args+=("$arg")
fi
done
if [ ${#env_files[@]} -eq 0 ]; then
echo "Error: No env files provided" >&2
echo >&2
echo "Usage: withenv <env-file> [env-file2] ... -- <command> [args]" >&2
exit 1
fi
if [ ${#cmd_args[@]} -eq 0 ]; then
echo "Error: No command specified after --" >&2
echo >&2
echo "Usage: withenv <env-file> [env-file2] ... -- <command> [args]" >&2
exit 1
fi
data=$($script_dir/upfind "${env_files[@]}" | xargs $script_dir/show) || exit $?
(
set -a
eval "$data"
set +a
exec "${cmd_args[@]}"
)