Compare commits
No commits in common. "main" and "gitea-24" have entirely different histories.
@ -1,49 +0,0 @@
|
|||||||
package assert
|
|
||||||
|
|
||||||
import (
|
|
||||||
"errors"
|
|
||||||
"slices"
|
|
||||||
"testing"
|
|
||||||
)
|
|
||||||
|
|
||||||
func Eq[C comparable](t *testing.T, context string, expected, actual C) {
|
|
||||||
if expected != actual {
|
|
||||||
t.Errorf("%s: %#v != %#v", context, expected, actual)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func True(t *testing.T, context string, condition bool) {
|
|
||||||
if !condition {
|
|
||||||
t.Errorf("false: %s", context)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func FatalTrue(t *testing.T, context string, condition bool) {
|
|
||||||
if !condition {
|
|
||||||
t.Fatalf("%s", context)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func FatalErr(t *testing.T, context string, err error) {
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("%s: %s", context, err)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func FatalErrIs(t *testing.T, context string, err, target error) {
|
|
||||||
if !errors.Is(err, target) {
|
|
||||||
t.Fatalf("%s: encountered unexpected error: %s", context, err)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func FatalErrAs(t *testing.T, context string, err error, target any) {
|
|
||||||
if !errors.As(err, target) {
|
|
||||||
t.Fatalf("%s: encountered unexpected error: %s", context, err)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func SlicesEq[S ~[]E, E comparable](t *testing.T, context string, expected, actual S) {
|
|
||||||
if !slices.Equal(expected, actual) {
|
|
||||||
t.Errorf("%s: %#v != %#v", context, expected, actual)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@ -1,5 +0,0 @@
|
|||||||
module lishwist/assert
|
|
||||||
|
|
||||||
go 1.23.0
|
|
||||||
|
|
||||||
toolchain go1.23.3
|
|
||||||
@ -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)
|
|
||||||
}
|
|
||||||
@ -23,8 +23,6 @@ func (a *Admin) CreateGroup(name string, reference string) (*Group, error)
|
|||||||
|
|
||||||
func (*Admin) GetUser(id string) (*User, error)
|
func (*Admin) GetUser(id string) (*User, error)
|
||||||
|
|
||||||
func (a *Admin) ListEvents() ([]Event, error)
|
|
||||||
|
|
||||||
func (a *Admin) ListGroups() ([]Group, error)
|
func (a *Admin) ListGroups() ([]Group, error)
|
||||||
|
|
||||||
func (*Admin) ListUsers() ([]User, error)
|
func (*Admin) ListUsers() ([]User, error)
|
||||||
@ -39,15 +37,6 @@ func (u *Admin) UserSetLive(userReference string, setting bool) error
|
|||||||
|
|
||||||
type ErrorInvalidCredentials error
|
type ErrorInvalidCredentials error
|
||||||
|
|
||||||
type Event struct {
|
|
||||||
Id string
|
|
||||||
ActorId string
|
|
||||||
ActionType string
|
|
||||||
TargetType string
|
|
||||||
TargetId string
|
|
||||||
CreatedAt time.Time
|
|
||||||
}
|
|
||||||
|
|
||||||
type Group struct {
|
type Group struct {
|
||||||
Id string
|
Id string
|
||||||
Name string
|
Name string
|
||||||
@ -83,7 +72,7 @@ func (s *Session) GetOthersWishes(userReference string) ([]Wish, error)
|
|||||||
|
|
||||||
func (s *Session) GetWishes() ([]Wish, error)
|
func (s *Session) GetWishes() ([]Wish, error)
|
||||||
|
|
||||||
func (s *Session) MakeWish(name string) (string, error)
|
func (s *Session) MakeWish(name string) error
|
||||||
|
|
||||||
func (s *Session) RecindWishesForUser(ids ...string) error
|
func (s *Session) RecindWishesForUser(ids ...string) error
|
||||||
|
|
||||||
|
|||||||
150
core/event.go
150
core/event.go
@ -1,150 +0,0 @@
|
|||||||
package lishwist
|
|
||||||
|
|
||||||
import (
|
|
||||||
"fmt"
|
|
||||||
"log"
|
|
||||||
"strings"
|
|
||||||
"time"
|
|
||||||
|
|
||||||
"lishwist/core/internal/db"
|
|
||||||
)
|
|
||||||
|
|
||||||
const (
|
|
||||||
eventActionCreate = "CREATE"
|
|
||||||
eventActionHide = "HIDE"
|
|
||||||
eventActionUnhide = "UNHIDE"
|
|
||||||
eventActionClaim = "CLAIM"
|
|
||||||
eventActionUnclaim = "UNCLAIM"
|
|
||||||
eventActionComplete = "COMPLETE"
|
|
||||||
// eventActionDelete = "DELETE" NOTE: We can't have this, because there'll be no target to reference
|
|
||||||
)
|
|
||||||
|
|
||||||
const (
|
|
||||||
eventTargetGroup = "GROUP"
|
|
||||||
eventTargetUser = "USER"
|
|
||||||
eventTargetWish = "WISH"
|
|
||||||
eventTargetGroupMember = "GROUP_MEMBER"
|
|
||||||
)
|
|
||||||
|
|
||||||
type Event struct {
|
|
||||||
Id string
|
|
||||||
ActorId string
|
|
||||||
ActionType string
|
|
||||||
TargetType string
|
|
||||||
TargetId string
|
|
||||||
CreatedAt time.Time
|
|
||||||
}
|
|
||||||
|
|
||||||
// type EventCreateGroupMember struct {
|
|
||||||
// Event
|
|
||||||
// Actor User
|
|
||||||
// User
|
|
||||||
// Group
|
|
||||||
// }
|
|
||||||
|
|
||||||
func queryManyEvents(query string, args ...any) ([]Event, error) {
|
|
||||||
rows, err := db.Connection.Query(query, args...)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
defer rows.Close()
|
|
||||||
events := []Event{}
|
|
||||||
for rows.Next() {
|
|
||||||
var g Event
|
|
||||||
var createdAt string
|
|
||||||
err = rows.Scan(&g.Id, &g.ActorId, &g.ActionType, &g.TargetType, &g.TargetId, &createdAt)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
g.CreatedAt, err = time.Parse(time.RFC3339Nano, createdAt)
|
|
||||||
if err != nil {
|
|
||||||
return nil, fmt.Errorf("failed to parse created_at: %w", err)
|
|
||||||
}
|
|
||||||
events = append(events, g)
|
|
||||||
}
|
|
||||||
err = rows.Err()
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
return events, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func queryOneEvent(query string, args ...any) (*Event, error) {
|
|
||||||
events, err := queryManyEvents(query, args...)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
if len(events) < 1 {
|
|
||||||
return nil, nil
|
|
||||||
}
|
|
||||||
return &events[0], nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (a *Admin) ListEvents() ([]Event, error) {
|
|
||||||
query := "SELECT id, actor_id, action_type, target_type, target_id, created_at FROM event;"
|
|
||||||
return queryManyEvents(query)
|
|
||||||
}
|
|
||||||
|
|
||||||
func recordEvent(actorId, actionType, targetType string, targetIds ...string) {
|
|
||||||
// TODO: If this were to accept sql.Tx it could be used in atomic transactions
|
|
||||||
numTargets := len(targetIds)
|
|
||||||
if numTargets < 1 {
|
|
||||||
log.Println("Warning: recordEvent called with no target IDs. Skipping.")
|
|
||||||
return
|
|
||||||
}
|
|
||||||
stmt := "INSERT INTO event (actor_id, action_type, target_type, target_id) VALUES (?, ?, ?, ?)"
|
|
||||||
extraValuePlaceholders := strings.Repeat(", (?, ?, ?, ?)", numTargets-1)
|
|
||||||
args := make([]any, numTargets*4)
|
|
||||||
for i, id := range targetIds {
|
|
||||||
args[i*4] = actorId
|
|
||||||
args[i*4+1] = actionType
|
|
||||||
args[i*4+2] = targetType
|
|
||||||
args[i*4+3] = id
|
|
||||||
}
|
|
||||||
_, err := db.Connection.Exec(stmt+extraValuePlaceholders, args...)
|
|
||||||
if err == nil {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
if numTargets == 1 {
|
|
||||||
log.Printf("Failed to record %s %s event: failed to execute query: %s\n", actionType, targetType, err)
|
|
||||||
} else {
|
|
||||||
log.Printf("Failed to record %d %s %s events: failed to execute query: %s\n", numTargets, actionType, targetType, err)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func recordEventCreateGroup(actorId, groupId string) {
|
|
||||||
recordEvent(actorId, eventActionCreate, eventTargetGroup, groupId)
|
|
||||||
}
|
|
||||||
|
|
||||||
func recordEventCreateUser(actorId, userId string) {
|
|
||||||
recordEvent(actorId, eventActionCreate, eventTargetUser, userId)
|
|
||||||
}
|
|
||||||
|
|
||||||
func recordEventCreateWish(actorId, wishId string) {
|
|
||||||
recordEvent(actorId, eventActionCreate, eventTargetWish, wishId)
|
|
||||||
}
|
|
||||||
|
|
||||||
func recordEventCreateGroupMember(actorId, groupMemberId string) {
|
|
||||||
recordEvent(actorId, eventActionCreate, eventTargetGroupMember, groupMemberId)
|
|
||||||
}
|
|
||||||
|
|
||||||
// FIXME: I can't use these yet because the associated actions use reference
|
|
||||||
// func recordEventHideUser(actorId, userId string) {
|
|
||||||
// recordEvent(actorId, eventActionHide, eventTargetUser, userId)
|
|
||||||
// }
|
|
||||||
|
|
||||||
// func recordEventUnhideUser(actorId, userId string) {
|
|
||||||
// recordEvent(actorId, eventActionUnhide, eventTargetUser, userId)
|
|
||||||
// }
|
|
||||||
|
|
||||||
func recordEventClaimWishes(actorId string, wishIds ...string) {
|
|
||||||
recordEvent(actorId, eventActionClaim, eventTargetWish, wishIds...)
|
|
||||||
}
|
|
||||||
|
|
||||||
func recordEventUnclaimWishes(actorId string, wishIds ...string) {
|
|
||||||
recordEvent(actorId, eventActionUnclaim, eventTargetWish, wishIds...)
|
|
||||||
}
|
|
||||||
|
|
||||||
func recordEventCompleteWishes(actorId string, wishIds ...string) {
|
|
||||||
recordEvent(actorId, eventActionComplete, eventTargetWish, wishIds...)
|
|
||||||
}
|
|
||||||
@ -103,21 +103,15 @@ func (a *Admin) CreateGroup(name string, reference string) (*Group, error) {
|
|||||||
Name: name,
|
Name: name,
|
||||||
Reference: reference,
|
Reference: reference,
|
||||||
}
|
}
|
||||||
recordEventCreateGroup(a.session.user.Id, group.Id)
|
|
||||||
return &group, nil
|
return &group, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (a *Admin) AddUserToGroup(userId, groupId string) error {
|
func (a *Admin) AddUserToGroup(userId, groupId string) error {
|
||||||
stmt := "INSERT INTO group_member (user_id, group_id) VALUES (?, ?)"
|
stmt := "INSERT INTO group_member (user_id, group_id) VALUES (?, ?)"
|
||||||
result, err := db.Connection.Exec(stmt, userId, groupId)
|
_, err := db.Connection.Exec(stmt, userId, groupId)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return fmt.Errorf("query execution failed: %w", err)
|
return err
|
||||||
}
|
}
|
||||||
id, err := result.LastInsertId()
|
|
||||||
if err != nil {
|
|
||||||
return fmt.Errorf("failed to get last insert id: %w", err)
|
|
||||||
}
|
|
||||||
recordEventCreateGroupMember(a.session.user.Id, strconv.FormatInt(id, 10))
|
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@ -15,12 +15,6 @@ func TestCreateGroup(t *testing.T) {
|
|||||||
|
|
||||||
fixtures.AssertEq(t, "Number of users", "My Friends", group.Name)
|
fixtures.AssertEq(t, "Number of users", "My Friends", group.Name)
|
||||||
fixtures.AssertEq(t, "Number of users", "my-friends", group.Reference)
|
fixtures.AssertEq(t, "Number of users", "my-friends", group.Reference)
|
||||||
|
|
||||||
// FIXME: disabled for now because datetimes break this
|
|
||||||
// events, err := s.Admin().ListEvents()
|
|
||||||
// assert.FatalErr(t, "listing events", err)
|
|
||||||
|
|
||||||
// assert.JsonSnapshot(t, "TestCreateGroup.snap.txt", events)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestCantSeeSelfInGroup(t *testing.T) {
|
func TestCantSeeSelfInGroup(t *testing.T) {
|
||||||
@ -45,10 +39,4 @@ func TestCantSeeSelfInGroup(t *testing.T) {
|
|||||||
fixtures.AssertEq(t, "Group contains 2 users", 2, len(group.Members))
|
fixtures.AssertEq(t, "Group contains 2 users", 2, len(group.Members))
|
||||||
fixtures.AssertEq(t, "Group user 1 is thomas", "thomas", group.Members[0].Name)
|
fixtures.AssertEq(t, "Group user 1 is thomas", "thomas", group.Members[0].Name)
|
||||||
fixtures.AssertEq(t, "Group user 2 is caleb", "caleb", group.Members[1].Name)
|
fixtures.AssertEq(t, "Group user 2 is caleb", "caleb", group.Members[1].Name)
|
||||||
|
|
||||||
// FIXME: disabled for now because datetimes break this
|
|
||||||
// events, err := s.Admin().ListEvents()
|
|
||||||
// assert.FatalErr(t, "listing events", err)
|
|
||||||
|
|
||||||
// assert.JsonSnapshot(t, "TestCantSeeSelfInGroup.snap.txt", events)
|
|
||||||
}
|
}
|
||||||
|
|||||||
@ -30,10 +30,8 @@ CREATE TABLE IF NOT EXISTS "group" (
|
|||||||
PRIMARY KEY("id" AUTOINCREMENT)
|
PRIMARY KEY("id" AUTOINCREMENT)
|
||||||
);
|
);
|
||||||
CREATE TABLE IF NOT EXISTS "group_member" (
|
CREATE TABLE IF NOT EXISTS "group_member" (
|
||||||
"id" INTEGER NOT NULL UNIQUE,
|
|
||||||
"group_id" INTEGER NOT NULL,
|
"group_id" INTEGER NOT NULL,
|
||||||
"user_id" INTEGER NOT NULL,
|
"user_id" INTEGER NOT NULL,
|
||||||
PRIMARY KEY("id" AUTOINCREMENT),
|
|
||||||
UNIQUE("user_id","group_id"),
|
UNIQUE("user_id","group_id"),
|
||||||
FOREIGN KEY("group_id") REFERENCES "group"("id"),
|
FOREIGN KEY("group_id") REFERENCES "group"("id"),
|
||||||
FOREIGN KEY("user_id") REFERENCES "user"("id")
|
FOREIGN KEY("user_id") REFERENCES "user"("id")
|
||||||
@ -46,15 +44,6 @@ CREATE TABLE IF NOT EXISTS "session" (
|
|||||||
PRIMARY KEY("id" AUTOINCREMENT),
|
PRIMARY KEY("id" AUTOINCREMENT),
|
||||||
FOREIGN KEY("user_id") REFERENCES "user"("id")
|
FOREIGN KEY("user_id") REFERENCES "user"("id")
|
||||||
);
|
);
|
||||||
CREATE TABLE IF NOT EXISTS "event" (
|
|
||||||
"id" INTEGER NOT NULL UNIQUE,
|
|
||||||
"actor_id" INTEGER NOT NULL,
|
|
||||||
"action_type" TEXT NOT NULL,
|
|
||||||
"target_type" TEXT NOT NULL,
|
|
||||||
"target_id" INTEGER NOT NULL,
|
|
||||||
"created_at" TEXT NOT NULL DEFAULT (STRFTIME('%Y-%m-%dT%H:%M:%fZ')),
|
|
||||||
PRIMARY KEY("id" AUTOINCREMENT)
|
|
||||||
);
|
|
||||||
|
|
||||||
DROP VIEW IF EXISTS "v_user";
|
DROP VIEW IF EXISTS "v_user";
|
||||||
CREATE VIEW "v_user"
|
CREATE VIEW "v_user"
|
||||||
|
|||||||
@ -1,19 +0,0 @@
|
|||||||
BEGIN TRANSACTION;
|
|
||||||
|
|
||||||
ALTER TABLE group_member RENAME TO old_group_member;
|
|
||||||
|
|
||||||
CREATE TABLE "group_member" (
|
|
||||||
"id" INTEGER NOT NULL UNIQUE,
|
|
||||||
"group_id" INTEGER NOT NULL,
|
|
||||||
"user_id" INTEGER NOT NULL,
|
|
||||||
PRIMARY KEY("id" AUTOINCREMENT),
|
|
||||||
UNIQUE("user_id","group_id"),
|
|
||||||
FOREIGN KEY("group_id") REFERENCES "group"("id"),
|
|
||||||
FOREIGN KEY("user_id") REFERENCES "user"("id")
|
|
||||||
);
|
|
||||||
|
|
||||||
INSERT INTO group_member (group_id, user_id) SELECT group_id, user_id FROM old_group_member;
|
|
||||||
|
|
||||||
DROP TABLE "old_group_member";
|
|
||||||
|
|
||||||
COMMIT;
|
|
||||||
@ -2,28 +2,24 @@ package fixtures
|
|||||||
|
|
||||||
import "testing"
|
import "testing"
|
||||||
|
|
||||||
// Deprecated: use internal/assert
|
|
||||||
func AssertEq[C comparable](t *testing.T, context string, expected, actual C) {
|
func AssertEq[C comparable](t *testing.T, context string, expected, actual C) {
|
||||||
if expected != actual {
|
if expected != actual {
|
||||||
t.Errorf("%s: %#v != %#v", context, expected, actual)
|
t.Errorf("%s: %#v != %#v", context, expected, actual)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Deprecated: use internal/assert
|
|
||||||
func Assert(t *testing.T, context string, condition bool) {
|
func Assert(t *testing.T, context string, condition bool) {
|
||||||
if !condition {
|
if !condition {
|
||||||
t.Errorf("%s", context)
|
t.Errorf("%s", context)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Deprecated: use internal/assert
|
|
||||||
func FatalAssert(t *testing.T, context string, condition bool) {
|
func FatalAssert(t *testing.T, context string, condition bool) {
|
||||||
if !condition {
|
if !condition {
|
||||||
t.Fatalf("%s", context)
|
t.Fatalf("%s", context)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Deprecated: use internal/assert
|
|
||||||
func FailIfErr(t *testing.T, err error, context string) {
|
func FailIfErr(t *testing.T, err error, context string) {
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatalf("%s: %s\n", context, err)
|
t.Fatalf("%s: %s\n", context, err)
|
||||||
|
|||||||
@ -1,6 +1,7 @@
|
|||||||
package fixtures
|
package fixtures
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"log"
|
||||||
"testing"
|
"testing"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
@ -14,36 +15,21 @@ func TestInit(t *testing.T) error {
|
|||||||
return lishwist.Init(uri)
|
return lishwist.Init(uri)
|
||||||
}
|
}
|
||||||
|
|
||||||
// Deprecated: This function also inits the test, which prevents it from being used more than once per test
|
|
||||||
func Login(t *testing.T, username, password string) *lishwist.Session {
|
func Login(t *testing.T, username, password string) *lishwist.Session {
|
||||||
uri := memdb.TestDB(t)
|
uri := memdb.TestDB(t)
|
||||||
err := lishwist.Init(uri)
|
err := lishwist.Init(uri)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatalf("Failed to init db: %s\n", err)
|
log.Fatalf("Failed to init db: %s\n", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
_, err = lishwist.Register(username, password)
|
_, err = lishwist.Register(username, password)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatalf("Failed to register on login fixture: %s\n", err)
|
log.Fatalf("Failed to register on login fixture: %s\n", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
session, err := lishwist.Login(username, password, time.Hour*24)
|
session, err := lishwist.Login(username, password, time.Hour*24)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatalf("Failed to login on fixture: %s\n", err)
|
log.Fatalf("Failed to login on fixture: %s\n", err)
|
||||||
}
|
|
||||||
|
|
||||||
return session
|
|
||||||
}
|
|
||||||
|
|
||||||
func Login2(t *testing.T, username, password string) *lishwist.Session {
|
|
||||||
_, err := lishwist.Register(username, password)
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("Failed to register on login fixture: %s\n", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
session, err := lishwist.Login(username, password, time.Hour*24)
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("Failed to login on fixture: %s\n", err)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
return session
|
return session
|
||||||
|
|||||||
@ -78,7 +78,6 @@ func createUser(name string, passHash []byte, isAdmin bool) (*User, error) {
|
|||||||
Id: fmt.Sprintf("%d", id),
|
Id: fmt.Sprintf("%d", id),
|
||||||
Name: name,
|
Name: name,
|
||||||
}
|
}
|
||||||
recordEventCreateUser(user.Id, user.Id)
|
|
||||||
return &user, nil
|
return &user, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
44
core/wish.go
44
core/wish.go
@ -4,7 +4,6 @@ import (
|
|||||||
"database/sql"
|
"database/sql"
|
||||||
"errors"
|
"errors"
|
||||||
"fmt"
|
"fmt"
|
||||||
"strconv"
|
|
||||||
"strings"
|
"strings"
|
||||||
|
|
||||||
"lishwist/core/internal/db"
|
"lishwist/core/internal/db"
|
||||||
@ -53,20 +52,13 @@ func (s *Session) GetWishes() ([]Wish, error) {
|
|||||||
return wishs, nil
|
return wishs, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// May return the id of the wish
|
func (s *Session) MakeWish(name string) error {
|
||||||
func (s *Session) MakeWish(name string) (string, error) {
|
|
||||||
stmt := "INSERT INTO wish (name, recipient_id, creator_id) VALUES (?, ?, ?)"
|
stmt := "INSERT INTO wish (name, recipient_id, creator_id) VALUES (?, ?, ?)"
|
||||||
result, err := db.Connection.Exec(stmt, strings.TrimSpace(name), s.User().Id, s.User().Id)
|
_, err := db.Connection.Exec(stmt, strings.TrimSpace(name), s.User().Id, s.User().Id)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return "", fmt.Errorf("Query execution failed: %w", err)
|
return fmt.Errorf("Query execution failed: %w", err)
|
||||||
}
|
}
|
||||||
id, err := result.LastInsertId()
|
return nil
|
||||||
if err != nil {
|
|
||||||
return "", fmt.Errorf("failed to get last insert id: %w", err)
|
|
||||||
}
|
|
||||||
wishId := strconv.FormatInt(id, 10)
|
|
||||||
recordEventCreateWish(s.user.Id, wishId)
|
|
||||||
return wishId, nil
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func (s *Session) deleteWishes(tx *sql.Tx, ids []string) error {
|
func (s *Session) deleteWishes(tx *sql.Tx, ids []string) error {
|
||||||
@ -202,10 +194,7 @@ func (s *Session) executeClaims(tx *sql.Tx, claims, unclaims []string) error {
|
|||||||
|
|
||||||
// Undertake or abandon wishes made by other users
|
// Undertake or abandon wishes made by other users
|
||||||
func (s *Session) ClaimWishes(claims, unclaims []string) error {
|
func (s *Session) ClaimWishes(claims, unclaims []string) error {
|
||||||
lenClaims := len(claims)
|
if len(claims) < 1 && len(unclaims) < 1 {
|
||||||
lenUnclaims := len(unclaims)
|
|
||||||
// TODO: Would be nice if this used a request builder
|
|
||||||
if lenClaims < 1 && lenUnclaims < 1 {
|
|
||||||
return fmt.Errorf("Attempt to claim/unclaim zero wishes")
|
return fmt.Errorf("Attempt to claim/unclaim zero wishes")
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -224,18 +213,8 @@ func (s *Session) ClaimWishes(claims, unclaims []string) error {
|
|||||||
}
|
}
|
||||||
|
|
||||||
err = tx.Commit()
|
err = tx.Commit()
|
||||||
if err != nil {
|
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
// TODO: This could be atomic. See recordEvent function
|
|
||||||
if lenClaims > 0 {
|
|
||||||
recordEventClaimWishes(s.user.Id, claims...)
|
|
||||||
}
|
|
||||||
if lenUnclaims > 0 {
|
|
||||||
recordEventUnclaimWishes(s.user.Id, unclaims...)
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func executeCompletions(tx *sql.Tx, claims []string) error {
|
func executeCompletions(tx *sql.Tx, claims []string) error {
|
||||||
claimStmt := "UPDATE wish SET sent = 1 WHERE id = ?"
|
claimStmt := "UPDATE wish SET sent = 1 WHERE id = ?"
|
||||||
@ -255,8 +234,8 @@ func executeCompletions(tx *sql.Tx, claims []string) error {
|
|||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (s *Session) CompleteWishes(claims []string) error {
|
|
||||||
// TODO: User ought not be able to interact with wishes outside their group network
|
// TODO: User ought not be able to interact with wishes outside their group network
|
||||||
|
func (s *Session) CompleteWishes(claims []string) error {
|
||||||
if len(claims) < 1 {
|
if len(claims) < 1 {
|
||||||
return fmt.Errorf("Attempt to complete zero wishes")
|
return fmt.Errorf("Attempt to complete zero wishes")
|
||||||
}
|
}
|
||||||
@ -276,15 +255,9 @@ func (s *Session) CompleteWishes(claims []string) error {
|
|||||||
}
|
}
|
||||||
|
|
||||||
err = tx.Commit()
|
err = tx.Commit()
|
||||||
if err != nil {
|
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
recordEventCompleteWishes(s.user.Id, claims...)
|
|
||||||
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (u *Session) SuggestWishForUser(otherUserReference string, wishName string) error {
|
func (u *Session) SuggestWishForUser(otherUserReference string, wishName string) error {
|
||||||
otherUser, err := GetUserByReference(otherUserReference)
|
otherUser, err := GetUserByReference(otherUserReference)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@ -318,8 +291,5 @@ func (s *Session) RecindWishesForUser(ids ...string) error {
|
|||||||
}
|
}
|
||||||
|
|
||||||
err = tx.Commit()
|
err = tx.Commit()
|
||||||
if err != nil {
|
return err
|
||||||
return nil
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
}
|
}
|
||||||
|
|||||||
@ -3,18 +3,17 @@ package lishwist_test
|
|||||||
import (
|
import (
|
||||||
"testing"
|
"testing"
|
||||||
|
|
||||||
"lishwist/assert"
|
|
||||||
"lishwist/core/internal/fixtures"
|
"lishwist/core/internal/fixtures"
|
||||||
)
|
)
|
||||||
|
|
||||||
func TestMakeWish(t *testing.T) {
|
func TestMakeWish(t *testing.T) {
|
||||||
s := fixtures.Login(t, "thomas", "123")
|
s := fixtures.Login(t, "thomas", "123")
|
||||||
|
|
||||||
if _, err := s.MakeWish("apple"); err != nil {
|
if err := s.MakeWish("apple"); err != nil {
|
||||||
t.Fatalf("Failed to make wish 1: %s\n", err)
|
t.Fatalf("Failed to make wish 1: %s\n", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
if _, err := s.MakeWish(" A car "); err != nil {
|
if err := s.MakeWish(" A car "); err != nil {
|
||||||
t.Fatalf("Failed to make wish 2: %s\n", err)
|
t.Fatalf("Failed to make wish 2: %s\n", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -27,35 +26,3 @@ func TestMakeWish(t *testing.T) {
|
|||||||
fixtures.AssertEq(t, "Wish 1 name", wishes[0].Name, "apple")
|
fixtures.AssertEq(t, "Wish 1 name", wishes[0].Name, "apple")
|
||||||
fixtures.AssertEq(t, "Wish 2 name", wishes[1].Name, "A car")
|
fixtures.AssertEq(t, "Wish 2 name", wishes[1].Name, "A car")
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestClaimUnclaimWishes(t *testing.T) {
|
|
||||||
err := fixtures.TestInit(t)
|
|
||||||
assert.FatalErr(t, "initializing db", err)
|
|
||||||
|
|
||||||
thomas := fixtures.Login2(t, "thomas", "123")
|
|
||||||
assert.FatalErr(t, "registering thomas", err)
|
|
||||||
|
|
||||||
caleb := fixtures.Login2(t, "caleb", "123")
|
|
||||||
assert.FatalErr(t, "registering caleb", err)
|
|
||||||
|
|
||||||
food, err := caleb.MakeWish("food")
|
|
||||||
assert.FatalErr(t, "making wish 1", err)
|
|
||||||
|
|
||||||
box, err := caleb.MakeWish("box")
|
|
||||||
assert.FatalErr(t, "making wish 2", err)
|
|
||||||
|
|
||||||
drink, err := caleb.MakeWish("drink")
|
|
||||||
assert.FatalErr(t, "making wish 3", err)
|
|
||||||
|
|
||||||
err = thomas.ClaimWishes([]string{food, box, drink}, []string{})
|
|
||||||
assert.FatalErr(t, "claiming wishes", err)
|
|
||||||
|
|
||||||
err = thomas.ClaimWishes([]string{}, []string{food, box, drink})
|
|
||||||
assert.FatalErr(t, "unclaiming wishes", err)
|
|
||||||
|
|
||||||
// FIXME: disabled for now because datetimes break this
|
|
||||||
// events, err := thomas.Admin().ListEvents()
|
|
||||||
// assert.FatalErr(t, "listing events", err)
|
|
||||||
|
|
||||||
// assert.JsonSnapshot(t, "TestClaimUnclaimWishes.snap.txt", events)
|
|
||||||
}
|
|
||||||
|
|||||||
3
go.work
3
go.work
@ -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
43
http/api/login.go
Normal 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
97
http/api/register.go
Normal 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
|
||||||
|
// }
|
||||||
@ -1,5 +1,4 @@
|
|||||||
top_level=$(git rev-parse --show-toplevel)
|
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 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
|
|
||||||
|
|||||||
@ -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
|
|
||||||
}
|
|
||||||
11
http/go.mod
11
http/go.mod
@ -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.21.1
|
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.9.0
|
|
||||||
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
|
||||||
|
|||||||
10
http/go.sum
10
http/go.sum
@ -1,11 +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/hmc v0.9.0 h1:OYDn95/ZheJlVQTXFIztsuU2jUG57XahcMpJZ5dM1VQ=
|
|
||||||
github.com/Teajey/hmc v0.9.0/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/Teajey/rsvp v0.21.1 h1:qDo0VHvatOKFG6oqsq3daPOq0TU9pjicdz5mwxwGMO4=
|
|
||||||
github.com/Teajey/rsvp v0.21.1/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=
|
||||||
|
|||||||
@ -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)
|
|
||||||
}
|
|
||||||
@ -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)
|
|
||||||
}
|
|
||||||
@ -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)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@ -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, r, m.rsvp, rsvp.HandlerFunc(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)
|
|
||||||
}
|
|
||||||
@ -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)
|
|
||||||
}
|
|
||||||
@ -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)
|
|
||||||
})
|
|
||||||
}
|
|
||||||
@ -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 == ""
|
|
||||||
}
|
|
||||||
@ -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,
|
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@ -1,197 +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(wishes []lishwist.Wish) Wishlist {
|
|
||||||
list := Wishlist{
|
|
||||||
Label: "Your wishlist",
|
|
||||||
NewWish: &hmc.Form[hmc.Input]{
|
|
||||||
Method: "POST",
|
|
||||||
Elements: hmc.Input{
|
|
||||||
Label: "Add gift idea",
|
|
||||||
Name: "gift_name",
|
|
||||||
},
|
|
||||||
},
|
|
||||||
}
|
|
||||||
|
|
||||||
if len(wishes) < 1 {
|
|
||||||
return list
|
|
||||||
}
|
|
||||||
|
|
||||||
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",
|
|
||||||
},
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
list.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",
|
|
||||||
}},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
}
|
|
||||||
|
|
||||||
return list
|
|
||||||
}
|
|
||||||
|
|
||||||
func InitialTodo(todo []lishwist.Wish) Wishlist {
|
|
||||||
list := Wishlist{
|
|
||||||
Label: "Your todo list",
|
|
||||||
}
|
|
||||||
|
|
||||||
if len(todo) < 1 {
|
|
||||||
return list
|
|
||||||
}
|
|
||||||
|
|
||||||
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
|
|
||||||
}
|
|
||||||
|
|
||||||
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",
|
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
}
|
|
||||||
|
|
||||||
return list
|
|
||||||
}
|
|
||||||
|
|
||||||
func (w Wishlist) ExtractFormValues(form url.Values) {
|
|
||||||
if w.NewWish != nil {
|
|
||||||
_ = w.NewWish.Elements.ExtractValue(form)
|
|
||||||
}
|
|
||||||
|
|
||||||
if w.Wishes == nil {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
err := w.Wishes.Elements.Select.ExtractValue(form)
|
|
||||||
if err != nil {
|
|
||||||
w.Wishes.Elements.Select.Error = err.Error()
|
|
||||||
}
|
|
||||||
|
|
||||||
err = w.Wishes.Elements.Intent.ExtractValue(form)
|
|
||||||
if err != nil {
|
|
||||||
w.Wishes.Elements.Intent.Error = err.Error()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
58
http/response/handler.go
Normal file
58
http/response/handler.go
Normal 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
10
http/response/request.go
Normal 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}
|
||||||
|
}
|
||||||
@ -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,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@ -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
38
http/router/router.go
Normal 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)
|
||||||
|
}
|
||||||
@ -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!")
|
||||||
}
|
}
|
||||||
|
|||||||
@ -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,
|
||||||
}}
|
}}
|
||||||
|
|||||||
@ -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)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
@ -1,31 +0,0 @@
|
|||||||
package routing
|
|
||||||
|
|
||||||
import (
|
|
||||||
lishwist "lishwist/core"
|
|
||||||
"lishwist/http/response"
|
|
||||||
"lishwist/http/session"
|
|
||||||
"log"
|
|
||||||
"net/http"
|
|
||||||
|
|
||||||
"github.com/Teajey/rsvp"
|
|
||||||
)
|
|
||||||
|
|
||||||
type Events struct {
|
|
||||||
Events []lishwist.Event `xml:"Event"`
|
|
||||||
}
|
|
||||||
|
|
||||||
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.")
|
|
||||||
return response.NotFound()
|
|
||||||
}
|
|
||||||
|
|
||||||
events, err := admin.ListEvents()
|
|
||||||
if err != nil {
|
|
||||||
log.Printf("Admin failed to ListEvents: %s\n", err)
|
|
||||||
return response.Error("Failed to get events: %s", err).StatusInternalServerError()
|
|
||||||
}
|
|
||||||
|
|
||||||
return response.Data("", Events{Events: events})
|
|
||||||
}
|
|
||||||
@ -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)
|
||||||
}
|
}
|
||||||
|
|||||||
@ -7,9 +7,7 @@ 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"
|
||||||
@ -18,17 +16,16 @@ import (
|
|||||||
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})
|
||||||
|
|||||||
@ -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 :(")
|
||||||
}
|
}
|
||||||
groupLinks := make([]hmc.Link, len(groups))
|
p := HomeProps{Navbar: templates.NavCollapse{
|
||||||
for i, g := range groups {
|
User: &templates.User{Name: user.Name, CopyList: &templates.CopyList{Domain: env.Configuration.HostUrl, Reference: user.Reference}},
|
||||||
groupLinks[i] = hmc.Link{
|
AccountLink: &templates.AccountLink{Alert: user.PasswordFromAdmin},
|
||||||
Label: g.Name,
|
}, Gifts: gifts, Todo: todo, Groups: groups}
|
||||||
Href: fmt.Sprintf("groups/%s", g.Reference),
|
return response.Data("home.gotmpl", p)
|
||||||
}
|
|
||||||
}
|
|
||||||
navbar := templates.UserNavCollapse(user.Name, user.Reference, user.PasswordFromAdmin)
|
|
||||||
navbar.Links = nil
|
|
||||||
p := resources.HomeProps{
|
|
||||||
Namespace: hmc.NS(),
|
|
||||||
Navbar: navbar,
|
|
||||||
Wishlist: resources.InitialWishlist(gifts),
|
|
||||||
Todo: resources.InitialTodo(todo),
|
|
||||||
GroupsList: resources.LinksList{
|
|
||||||
Label: "Your groups",
|
|
||||||
Links: groupLinks,
|
|
||||||
},
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if r.Method == http.MethodGet {
|
func HomePost(app *lishwist.Session, session *response.Session, h http.Header, r *http.Request) rsvp.Response {
|
||||||
return rsvp.Data(p)
|
err := r.ParseForm()
|
||||||
}
|
|
||||||
|
|
||||||
err = r.ParseForm()
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
p.Error = "Failed to parse form"
|
return response.Error(http.StatusBadRequest, "Failed to parse form")
|
||||||
return rsvp.Data(p).StatusUnprocessableEntity()
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if len(r.Form) < 1 {
|
switch r.Form.Get("intent") {
|
||||||
p.Error = "No parameters provided"
|
case "add_idea":
|
||||||
return rsvp.Data(p).StatusBadRequest()
|
return WishlistAdd(app, h, r)
|
||||||
}
|
case "delete_idea":
|
||||||
|
return WishlistDelete(app, h, r)
|
||||||
wishForm := maps.Clone(r.Form)
|
default:
|
||||||
p.Wishlist.ExtractFormValues(wishForm)
|
return TodoUpdate(app, h, r)
|
||||||
p.Todo.ExtractFormValues(r.Form)
|
|
||||||
|
|
||||||
extra := mapKeysIntersect(wishForm, r.Form)
|
|
||||||
if len(extra) > 0 {
|
|
||||||
p.Warning = "Extraneous form values"
|
|
||||||
}
|
|
||||||
|
|
||||||
if p.Wishlist.Wishes != nil && 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()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if p.Todo.Wishes != nil && p.Todo.Wishes.Elements.Intent.Value() == "unclaim_todo" {
|
|
||||||
todosToChange := slices.Collect(p.Todo.Wishes.Elements.Select.Values())
|
|
||||||
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 != nil && p.Todo.Wishes.Elements.Intent.Value() == "complete_todo" {
|
|
||||||
todosToChange := slices.Collect(p.Todo.Wishes.Elements.Select.Values())
|
|
||||||
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(".")
|
|
||||||
}
|
|
||||||
|
|||||||
@ -1,69 +1,59 @@
|
|||||||
package routing
|
package routing
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"cmp"
|
|
||||||
"errors"
|
"errors"
|
||||||
"log"
|
"log"
|
||||||
"net/http"
|
"net/http"
|
||||||
"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)
|
||||||
@ -71,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(cmp.Or(referrer, "."))
|
|
||||||
}
|
}
|
||||||
|
|||||||
@ -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")
|
||||||
}
|
}
|
||||||
|
|||||||
@ -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")
|
||||||
}
|
}
|
||||||
|
|||||||
@ -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(®ister)
|
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(®ister)
|
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("/")
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|||||||
@ -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")
|
||||||
}
|
}
|
||||||
|
|||||||
@ -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)
|
||||||
|
|||||||
@ -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
|
||||||
}
|
}
|
||||||
|
|||||||
@ -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,36 @@ 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 /account", routing.ExpectAppSession(routing.Account))
|
||||||
r.Private.HandleFunc("GET /lists/{userReference}", routing.ForeignWishlist)
|
r.Private.HandleFunc("GET /health", routing.ExpectAppSession(routing.Health))
|
||||||
r.Private.HandleFunc("GET /users/{userReference}", routing.User)
|
r.Private.HandleFunc("GET /", routing.NotFound)
|
||||||
r.Private.HandleFunc("GET /{$}", routing.Home)
|
r.Private.HandleFunc("GET /groups", routing.ExpectAppSession(routing.Groups))
|
||||||
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/{groupReference}", routing.ExpectAppSession(routing.Group))
|
||||||
filestem, _ := file.NameAtPathValue(r, "file")
|
r.Private.HandleFunc("GET /lists/{userReference}", routing.ExpectAppSession(routing.ForeignWishlist))
|
||||||
switch filestem {
|
r.Private.HandleFunc("GET /users", routing.ExpectAppSession(routing.Users))
|
||||||
case "account":
|
r.Private.HandleFunc("GET /users/{userReference}", routing.ExpectAppSession(routing.User))
|
||||||
return routing.Account(app, s, w, r)
|
r.Private.HandleFunc("GET /{$}", routing.ExpectAppSession(routing.Home))
|
||||||
case "events":
|
r.Private.HandleFunc("POST /account", routing.ExpectAppSession(routing.AccountPost))
|
||||||
return routing.EventList(app, s, w, r)
|
r.Private.HandleFunc("POST /groups/{groupReference}", routing.ExpectAppSession(routing.GroupPost))
|
||||||
case "groups":
|
r.Private.HandleFunc("POST /lists/{userReference}", routing.ExpectAppSession(routing.ForeignWishlistPost))
|
||||||
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 /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
|
||||||
}
|
}
|
||||||
|
|||||||
@ -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}}
|
||||||
|
|||||||
@ -10,101 +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}}
|
{{with .Gifts}}
|
||||||
{{with .Elements}}
|
<form method="post" onchange="acceptNames(this, 'deleteSubmit', 'gift')" autocomplete="off">
|
||||||
<form method="post" onchange="acceptNames(this, 'deleteSubmit', 'wish')" 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>
|
||||||
{{end}}
|
|
||||||
{{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>
|
||||||
@ -113,7 +95,6 @@
|
|||||||
{{end}}
|
{{end}}
|
||||||
</div>
|
</div>
|
||||||
</section>
|
</section>
|
||||||
{{end}}
|
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@ -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>
|
||||||
|
|||||||
@ -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>
|
||||||
|
|||||||
@ -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 .}}
|
||||||
|
|||||||
@ -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>
|
||||||
|
|||||||
@ -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() {
|
||||||
|
|||||||
@ -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
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@ -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
|
|
||||||
|
|||||||
15
scripts/show
15
scripts/show
@ -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
|
|
||||||
@ -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
|
|
||||||
@ -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
|
|
||||||
@ -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[@]}"
|
|
||||||
)
|
|
||||||
Loading…
Reference in New Issue
Block a user