Compare commits

..

19 Commits

Author SHA1 Message Date
Teajey
b5dfb135df
Complete old home page hmc-related refactor 2026-11-17 23:29:34 +09:00
Teajey
658884c2cc
Home resource uses hmc 2026-02-23 13:50:07 +09:00
Teajey
ab713f6662
Save session for basic auth 2026-02-21 10:23:19 +09:00
Teajey
60b4fa773c
Register link goes outside login form 2026-02-21 10:23:02 +09:00
Teajey
84fb52ac21
Basic auth middleware 2026-02-21 00:10:35 +09:00
Teajey
297ec2780b
Use withenv script 2026-02-20 23:49:42 +09:00
Teajey
a4146d1421
Remove BasicAuth middleware (for now) 2026-02-19 20:16:04 +09:00
Teajey
7334de957a
Replace htmlx with hmc 2026-02-14 12:29:47 +09:00
Teajey
f09d61509f
Update to rsvp 0.19 2026-02-13 10:36:24 +09:00
Teajey
51a84c0fba
Login referrer URL 2025-12-16 00:38:07 +09:00
Teajey
eacf3365c8
URL file extension support 2025-12-16 00:38:05 +09:00
Teajey
f945e9eb0f
Reword register home link to login link 2025-12-16 00:23:13 +09:00
Teajey
07313fbda4
SaveIfWritten session method 2025-12-15 12:25:11 +09:00
Teajey
c7122a591b
More refactoring and basic auth middleware 2025-12-11 22:44:15 +09:00
Teajey
f50446d04a
Use RSVP 0.14.0 and refactor for middleware 2025-12-11 19:55:01 +09:00
Teajey
8c4334e063
Better semantics, esp. for register page 2025-12-11 14:21:12 +09:00
Teajey
d9dc6caea3
Only run relevant tests in pre-commit 2025-12-10 17:24:14 +09:00
Teajey
df2e58026a
Snapshot htmlx stuff 2025-12-10 16:08:27 +09:00
Teajey
44d920d336
feat: better xml semantics for login page 2025-12-10 15:37:25 +09:00
54 changed files with 1432 additions and 751 deletions

5
assert/go.mod Normal file
View File

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

88
assert/snapshot.go Normal file
View File

@ -0,0 +1,88 @@
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

@ -1,62 +0,0 @@
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 (
"testing"
"lishwist/core/internal/assert"
"lishwist/assert"
"lishwist/core/internal/fixtures"
)

View File

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

View File

@ -1,43 +0,0 @@
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
}

View File

@ -1,97 +0,0 @@
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)
go generate ../core/internal/db
go run -ldflags=-X=lishwist/http/env.GitVersion=$git_version main.go
../scripts/withenv .env .env.local .env.dev .env.dev.local -- go run -ldflags=-X=lishwist/http/env.GitVersion=$git_version main.go

14
http/file/file.go Normal file
View File

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

View File

@ -1,5 +1,7 @@
github.com/Teajey/rsvp v0.13.1 h1:0lw+JosaWmdjSmXoKQYBRS9nptSZPInm60Y5GQ3llEU=
github.com/Teajey/rsvp v0.13.1/go.mod h1:z0L20VphVg+Ec2+hnpLFTG2MZTrWYFprav1kpxDba0Q=
github.com/Teajey/hmc v0.6.0-rc.12 h1:Vkx6mJa3pfMlYx4vyI9LfVLHa8fNyl8LikMvXBfDGZk=
github.com/Teajey/hmc v0.6.0-rc.12/go.mod h1:9K7SL4RyybNLHooqsZcyFoL6QGqqa2zPgIBidw4qWQY=
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/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/google/gofuzz v1.2.0 h1:xRy4A+RhZaiKjJ1bPfwQ8sedCA+YS2YcCHW6ec7JMi0=

20
http/handler/private.go Normal file
View File

@ -0,0 +1,20 @@
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)
}

19
http/handler/public.go Normal file
View File

@ -0,0 +1,19 @@
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)
}

22
http/middleware/prefix.go Normal file
View File

@ -0,0 +1,22 @@
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)
}
}

104
http/mux/private.go Normal file
View File

@ -0,0 +1,104 @@
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)
}

26
http/mux/public.go Normal file
View File

@ -0,0 +1,26 @@
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)
}

76
http/mux/serve.go Normal file
View File

@ -0,0 +1,76 @@
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)
})
}

37
http/props/login.go Normal file
View File

@ -0,0 +1,37 @@
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 == ""
}

85
http/props/register.go Normal file
View File

@ -0,0 +1,85 @@
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,
},
},
},
}
}

179
http/resources/home.go Normal file
View File

@ -0,0 +1,179 @@
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()
}
}

View File

@ -1,58 +0,0 @@
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)
}

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -1,60 +1,131 @@
package routing
import (
"fmt"
"log"
"maps"
"net/http"
"slices"
lishwist "lishwist/core"
"lishwist/http/env"
"lishwist/http/resources"
"lishwist/http/response"
"lishwist/http/session"
"lishwist/http/templates"
"github.com/Teajey/hmc"
"github.com/Teajey/rsvp"
)
type HomeProps struct {
Navbar templates.NavCollapse
Gifts []lishwist.Wish
Todo []lishwist.Wish
Groups []lishwist.Group
func mapKeysIntersect(a, b map[string][]string) []string {
var out []string
for k := range a {
if _, ok := b[k]; ok {
out = append(out, k)
}
}
return out
}
func Home(app *lishwist.Session, session *response.Session, h http.Header, r *http.Request) rsvp.Response {
func Home(app *lishwist.Session, session *session.Session, w rsvp.ResponseWriter, r *http.Request) rsvp.Body {
w.DefaultTemplateName("home.gotmpl")
gifts, err := app.GetWishes()
if err != nil {
log.Printf("Failed to get gifts: %s\n", err)
return response.Error(http.StatusInternalServerError, "An error occurred while fetching your wishlist :(")
return response.Error("An error occurred while fetching your wishlist :(").StatusInternalServerError()
}
user := app.User()
todo, err := user.GetTodo()
if err != nil {
log.Printf("Failed to get todo: %s\n", err)
return response.Error(http.StatusInternalServerError, "An error occurred while fetching your wishlist :(")
return response.Error("An error occurred while fetching your wishlist :(").StatusInternalServerError()
}
groups, err := app.GetGroups()
if err != nil {
log.Printf("Failed to get groups: %s\n", err)
return response.Error(http.StatusInternalServerError, "An error occurred while fetching your wishlist :(")
return response.Error("An error occurred while fetching your wishlist :(").StatusInternalServerError()
}
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)
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,
},
}
func HomePost(app *lishwist.Session, session *response.Session, h http.Header, r *http.Request) rsvp.Response {
err := r.ParseForm()
if r.Method == http.MethodGet {
return rsvp.Data(p)
}
err = r.ParseForm()
if err != nil {
return response.Error(http.StatusBadRequest, "Failed to parse form")
p.Error = "Failed to parse form"
return rsvp.Data(p).StatusUnprocessableEntity()
}
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)
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,53 +7,62 @@ import (
"time"
lishwist "lishwist/core"
"lishwist/http/api"
"lishwist/http/response"
"lishwist/http/props"
"lishwist/http/session"
"github.com/Teajey/hmc"
"github.com/Teajey/rsvp"
)
func Login(s *response.Session, h http.Header, r *http.Request) rsvp.Response {
props := api.NewLoginProps("", "")
type LoginPage struct {
hmc.Namespace
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()
flashProps, ok := flash.(*api.LoginProps)
flashProps, ok := flash.(*props.Login)
if ok {
props.Username.Value = flashProps.Username.Value
login.Username.Value = flashProps.Username.Value
props.GeneralError = flashProps.GeneralError
props.Username.Error = flashProps.Username.Error
props.Password.Error = flashProps.Password.Error
login.GeneralError = flashProps.GeneralError
login.Username.Error = flashProps.Username.Error
login.Password.Error = flashProps.Password.Error
props.SuccessfulRegistration = flashProps.SuccessfulRegistration
props.SuccessfulSetPassword = flashProps.SuccessfulSetPassword
login.SuccessfulRegistration = flashProps.SuccessfulRegistration
login.SuccessfulSetPassword = flashProps.SuccessfulSetPassword
}
return rsvp.Response{TemplateName: "login.gotmpl", Body: props}
body := NewLoginPage()
body.Form.Elements = login
return rsvp.Body{TemplateName: "login.gotmpl", Data: body}
}
func LoginPost(session *response.Session, h http.Header, r *http.Request) rsvp.Response {
username, password, ok := r.BasicAuth()
if !ok {
err := r.ParseForm()
if err != nil {
return response.Error(http.StatusBadRequest, "Failed to parse form")
}
func LoginMiddle(username, password string, session *session.Session, r *http.Request) *props.Login {
login := props.NewLogin(username, password)
username = r.Form.Get("username")
password = r.Form.Get("password")
}
props := api.NewLoginProps(username, password)
resp := rsvp.SeeOther(r.URL.Path, props)
valid := props.Validate()
props.Password.Value = ""
valid := login.Validate()
login.Password.Value = ""
if !valid {
session.FlashSet(&props)
log.Printf("Invalid props: %#v\n", props)
return resp
session.FlashSet(&login)
log.Printf("Invalid login submission: %#v\n", login)
return &login
}
appSession, err := lishwist.Login(username, password, time.Hour*24)
@ -61,20 +70,43 @@ func LoginPost(session *response.Session, h http.Header, r *http.Request) rsvp.R
var targ lishwist.ErrorInvalidCredentials
switch {
case errors.As(err, &targ):
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(&props)
log.Printf("Invalid credentials: %s: %#v\n", err, props)
return resp
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"
session.FlashSet(&login)
log.Printf("Invalid credentials: %s: %#v\n", err, login)
default:
props.GeneralError = "Something went wrong."
session.FlashSet(&props)
login.GeneralError = "Something went wrong."
session.FlashSet(&login)
log.Printf("Login error: %s\n", err)
return resp
}
return &login
}
session.SetID("")
session.SetValue("sessionKey", appSession.Key)
return rsvp.SeeOther(r.URL.Path, "Login successful!")
return nil
}
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,15 +1,16 @@
package routing
import (
"lishwist/http/response"
lishwist "lishwist/core"
"lishwist/http/session"
"net/http"
"github.com/Teajey/rsvp"
)
func LogoutPost(session *response.Session, h http.Header, r *http.Request) rsvp.Response {
session.Options().MaxAge = 0
session.ClearValues()
func LogoutPost(app *lishwist.Session, s *session.Session, w rsvp.ResponseWriter, r *http.Request) rsvp.Body {
s.Options().MaxAge = 0
s.ClearValues()
return rsvp.SeeOther("/", "Logout successful")
return rsvp.Data("Logout successful").StatusSeeOther("/")
}

View File

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

View File

@ -3,32 +3,33 @@ package routing
import (
"errors"
lishwist "lishwist/core"
"lishwist/http/api"
"lishwist/http/props"
"lishwist/http/response"
"lishwist/http/session"
"log"
"net/http"
"github.com/Teajey/rsvp"
)
func Register(session *response.Session, h http.Header, r *http.Request) rsvp.Response {
props := api.NewRegisterProps("", "", "")
func Register(session *session.Session, w rsvp.ResponseWriter, r *http.Request) rsvp.Body {
register := props.NewRegister("", "", "")
flash := session.FlashGet()
flashProps, _ := flash.(*api.RegisterProps)
flashProps, _ := flash.(*props.Register)
if flashProps != nil {
props.Username.Value = flashProps.Username.Value
register.Form.Elements.Username.Value = flashProps.Form.Elements.Username.Value
props.GeneralError = flashProps.GeneralError
props.Username.Error = flashProps.Username.Error
props.ConfirmPassword.Error = flashProps.ConfirmPassword.Error
register.Error = flashProps.Error
register.Form.Elements.Username.Error = flashProps.Form.Elements.Username.Error
register.Form.Elements.ConfirmPassword.Error = flashProps.Form.Elements.ConfirmPassword.Error
}
return response.Data("register.gotmpl", props)
return response.Data("register.gotmpl", register)
}
func RegisterPost(s *response.Session, h http.Header, r *http.Request) rsvp.Response {
func RegisterPost(s *session.Session, w rsvp.ResponseWriter, r *http.Request) rsvp.Body {
var confirmPassword string
username, newPassword, ok := r.BasicAuth()
if ok {
@ -36,7 +37,7 @@ func RegisterPost(s *response.Session, h http.Header, r *http.Request) rsvp.Resp
} else {
err := r.ParseForm()
if err != nil {
return response.Error(http.StatusBadRequest, "Failed to parse form")
return response.Error("Failed to parse form").StatusBadRequest()
}
username = r.Form.Get("username")
@ -44,29 +45,34 @@ func RegisterPost(s *response.Session, h http.Header, r *http.Request) rsvp.Resp
confirmPassword = r.Form.Get("confirmPassword")
}
props := api.NewRegisterProps(username, newPassword, confirmPassword)
register := props.NewRegister(username, newPassword, confirmPassword)
valid := props.Validate()
props.Password.Value = ""
props.ConfirmPassword.Value = ""
valid := register.Form.Elements.Validate()
register.Form.Elements.Password.Value = ""
register.Form.Elements.ConfirmPassword.Value = ""
if !valid {
s.FlashSet(&props)
log.Printf("Invalid register props: %#v\n", props)
return rsvp.SeeOther(r.URL.Path, props)
s.FlashSet(&register)
log.Printf("Invalid register submission: %#v\n", register)
return rsvp.Data(register).StatusSeeOther(r.URL.Path)
}
_, err := lishwist.Register(username, newPassword)
if err != nil {
if errors.Is(err, lishwist.ErrorUsernameTaken) {
props.Username.Error = "Username is taken"
register.Form.Elements.Username.Error = "Username is taken"
} else {
props.GeneralError = "Something went wrong."
register.Error = "Something went wrong."
}
s.FlashSet(&props)
s.FlashSet(&register)
log.Printf("Registration failed: %s\n", err)
return rsvp.SeeOther(r.URL.Path, props)
return rsvp.Data(register).StatusSeeOther(r.URL.Path)
}
s.FlashSet(&api.LoginProps{SuccessfulRegistration: true})
return rsvp.SeeOther("/", "Registration successful!")
s.FlashSet(&props.Login{SuccessfulRegistration: true})
referrer := r.URL.Query().Get("referrer")
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"
)
func TodoUpdate(app *lishwist.Session, h http.Header, r *http.Request) rsvp.Response {
func TodoUpdate(app *lishwist.Session, w rsvp.ResponseWriter, r *http.Request) rsvp.Body {
err := r.ParseForm()
if err != nil {
return response.Error(http.StatusBadRequest, "Failed to parse form")
return response.Error("Failed to parse form").StatusBadRequest()
}
switch r.Form.Get("intent") {
@ -22,17 +22,17 @@ func TodoUpdate(app *lishwist.Session, h http.Header, r *http.Request) rsvp.Resp
err := app.ClaimWishes([]string{}, unclaims)
if err != nil {
log.Printf("%s\n", err)
return response.Error(http.StatusInternalServerError, "Failed to update claim...")
return response.Error("Failed to update claim...").StatusInternalServerError()
}
case "complete_todo":
claims := r.Form["gift"]
err := app.CompleteWishes(claims)
if err != nil {
log.Printf("%s\n", err)
return response.Error(http.StatusInternalServerError, "Failed to complete gifts...")
return response.Error("Failed to complete gifts...").StatusInternalServerError()
}
default:
return response.Error(http.StatusBadRequest, "Invalid intent")
return response.Error("Invalid intent").StatusBadRequest()
}
return rsvp.SeeOther("/", "Update successful")
return rsvp.Data("Update successful").StatusSeeOther("/")
}

View File

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

View File

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

View File

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

View File

@ -1,6 +1,8 @@
package response
package session
import (
"net/http"
"github.com/gorilla/sessions"
)
@ -9,6 +11,10 @@ type Session struct {
written bool
}
func New(inner *sessions.Session) *Session {
return &Session{inner: inner}
}
const flashKey = "_flash"
func (s *Session) FlashGet() any {
@ -49,8 +55,18 @@ func (s *Session) RemoveValue(key any) {
s.written = true
}
func (s *Session) GetValue(key any) any {
return s.inner.Values[key]
func (s *Session) GetValue(key any) (any, bool) {
val, ok := 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() {
@ -61,3 +77,11 @@ func (s *Session) ClearValues() {
func (s *Session) Options() *sessions.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)
}

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -6,34 +6,39 @@
<body>
<div style="height: 100svh;" class="d-flex flex-column">
{{template "navbar" .Navbar}}
{{template "navbar" .Nav}}
<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">
<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>
{{with .GeneralError}}
{{end}}
{{with .Error}}
<div class="alert alert-danger" role="alert">
<p class="mb-0">{{.}}</p>
</div>
{{end}}
<form method="post">
{{with .Form}}
<form method="{{.Method}}">
{{with .Elements}}
<div class="d-flex flex-column">
<label>
Username
{{.Username.Label}}
{{template "input" .Username}}
</label>
<label>
Password
{{.Password.Label}}
{{template "input" .Password}}
</label>
<label>
Confirm password
{{.ConfirmPassword.Label}}
{{template "input" .ConfirmPassword}}
</label>
<input class="btn btn-primary" type="submit" value="Register">
<button class="btn btn-primary" type="submit">Register</button>
</div>
{{end}}
</form>
{{end}}
</div>
</div>
</body>

View File

@ -3,69 +3,54 @@ package templates
import (
"fmt"
"html/template"
"lishwist/http/env"
"github.com/Teajey/hmc"
)
type AccountLink struct {
Alert bool
}
type Link struct {
Href string
Name string
}
type CopyList struct {
Domain string
Reference string
}
type User struct {
Name string
CopyList *CopyList
type NavUser struct {
Label string `json:"label" xml:",chardata"`
Alert bool `json:"alert,omitempty" xml:",omitempty"`
Link *hmc.Link `json:"link,omitempty" xml:",omitempty"`
Account *hmc.Link `json:"account,omitempty" xml:",omitempty"`
Logout hmc.Form[hmc.Input] `json:"logout"`
}
type NavCollapse struct {
User *User
AccountLink *AccountLink
Links []Link
Links []hmc.Link
User *NavUser `json:",omitempty"`
}
func DefaultNavCollapse() NavCollapse {
return NavCollapse{Links: []Link{{Href: "/", Name: "Home"}}}
return NavCollapse{Links: []hmc.Link{{Href: "/", Label: "Home"}}}
}
func UserNavCollapse(username string, accountAlert bool) NavCollapse {
func UserNavCollapse(username, reference string, accountAlert bool) NavCollapse {
return NavCollapse{
Links: []Link{{Href: "/", Name: "Home"}},
User: &User{Name: username},
AccountLink: &AccountLink{Alert: accountAlert},
Links: []hmc.Link{{Href: "/", Label: "Home"}},
User: &NavUser{
Label: fmt.Sprintf("Logged in as '%s'", username),
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
func init() {

View File

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

View File

@ -2,10 +2,23 @@
APISNAP=api.snap.txt
./scripts/api_snapshot ./core > core/$APISNAP
git diff --quiet core/$APISNAP
./scripts/staged_files_match './scripts/**' 'core/**/*.go' && ./scripts/api_snapshot ./core > core/$APISNAP
if [[ $? -ne 0 ]]; then
if ! git diff --quiet core/$APISNAP; then
echo "There are unstaged changes to $APISNAP"
exit 1
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

15
scripts/show Executable file
View File

@ -0,0 +1,15 @@
#!/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

48
scripts/staged_files_match Executable file
View File

@ -0,0 +1,48 @@
#!/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

30
scripts/upfind Executable file
View File

@ -0,0 +1,30 @@
#!/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

51
scripts/withenv Executable file
View File

@ -0,0 +1,51 @@
#!/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[@]}"
)