summaryrefslogtreecommitdiff
path: root/server/admin/handler.go
blob: 2ae0b0d4e4ed7fa9214a96c3b43ced2cf7dd00ea (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
package admin

import (
	"encoding/json"
	"net/http"
	"os"
	"time"

	"git.huntm.net/wedding/server/errors"
	"git.huntm.net/wedding/server/guest"
	"github.com/golang-jwt/jwt/v5"
)

type AdminHandler struct {
	adminStore AdminStore
	guestStore guest.GuestStore
}

type AdminStore interface {
	Find(Admin) (Admin, error)
}

func NewAdminHandler(a AdminStore, g guest.GuestStore) *AdminHandler {
	return &AdminHandler{a, g}
}

func (a *AdminHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	switch {
	case r.Method == http.MethodOptions:
		w.WriteHeader(http.StatusOK)
	case r.Method == http.MethodPost && r.URL.Path == "/api/admin/login":
		a.handleLogIn(w, r)
	default:
		w.WriteHeader(http.StatusNotFound)
	}
}

func (a *AdminHandler) handleLogIn(w http.ResponseWriter, r *http.Request) {
	token, err := a.logIn(r)
	if err != nil {
		http.Error(w, string(err.Message), err.Status)
	} else {
		w.Write(token)
	}
}

func (a *AdminHandler) logIn(r *http.Request) ([]byte, *errors.AppError) {
	admin, err := a.decodeCredentials(r)
	if err != nil {
		return nil, errors.NewAppError(http.StatusBadRequest, err.Error())
	}
	_, err = a.adminStore.Find(admin)
	if err != nil {
		return nil, errors.NewAppError(http.StatusUnauthorized, err.Error())
	}
	key, err := a.readKey()
	if err != nil {
		return nil, errors.NewAppError(http.StatusInternalServerError, err.Error())
	}
	token, err := a.newToken(NewClaims(admin, a.setExpirationTime()), key)
	if err != nil {
		return nil, errors.NewAppError(http.StatusInternalServerError, err.Error())
	}
	guests, err := a.guestStore.Get()
	if err != nil {
		return nil, errors.NewAppError(http.StatusInternalServerError, err.Error())
	}
	jsonBytes, err := a.marshalResponse(guests, token)
	if err != nil {
		return nil, errors.NewAppError(http.StatusInternalServerError, err.Error())
	}
	return jsonBytes, nil
}

func (a *AdminHandler) decodeCredentials(r *http.Request) (Admin, error) {
	var admin Admin
	err := json.NewDecoder(r.Body).Decode(&admin)
	defer r.Body.Close()
	return admin, err
}

func (a *AdminHandler) setExpirationTime() time.Time {
	return time.Now().Add(15 * time.Minute)
}

func (a *AdminHandler) readKey() ([]byte, error) {
	return os.ReadFile(os.Getenv("ADMIN_KEY"))
}

func (a *AdminHandler) newToken(claims *Claims, key []byte) (string, error) {
	return jwt.NewWithClaims(jwt.SigningMethodHS256, claims).SignedString(key)
}

func (a *AdminHandler) marshalResponse(guests []guest.Guest, token string) ([]byte, error) {
	return json.Marshal(NewLogin(guests, token))
}