aboutsummaryrefslogtreecommitdiff
path: root/pkg/ext/middleware.go
blob: d9f06e15515cddc0af33453fdaa1aa34da336a9e (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
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
package ext

import (
	"context"
	"encoding/base64"
	"errors"
	"net/http"
	"time"

	"golang.org/x/exp/slog"

	"git.sr.ht/~gabrielgio/img/pkg/database/repository"
	"git.sr.ht/~gabrielgio/img/pkg/service"
)

func HTML(next http.HandlerFunc) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		w.Header().Set("Content-Type", "text/html")
		next(w, r)
	}
}

type (
	User string

	LogMiddleware struct {
		logger *slog.Logger
	}
)

const (
	UserKey User = "user"
)

func NewLogMiddleare(log *slog.Logger) *LogMiddleware {
	return &LogMiddleware{
		logger: log,
	}
}

func (l *LogMiddleware) HTTP(next http.HandlerFunc) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		start := time.Now()
		next(w, r)
		elapsed := time.Since(start)
		l.logger.Info(
			r.Method,
			slog.Duration("elapsed", elapsed),
			slog.String("path", r.URL.Path),
		)
	}
}

type AuthMiddleware struct {
	key            []byte
	logger         *slog.Logger
	userRepository repository.UserRepository
}

func NewAuthMiddleware(
	key []byte,
	logger *slog.Logger,
	userRepository repository.UserRepository,
) *AuthMiddleware {
	return &AuthMiddleware{
		key:            key,
		logger:         logger,
		userRepository: userRepository,
	}
}

func (a *AuthMiddleware) LoggedIn(next http.HandlerFunc) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		path := r.URL.Path
		if path == "/login" || path == "/initial" {
			next(w, r)
			return
		}

		redirectLogin := "/login?redirect=" + path
		authBase64, err := r.Cookie("auth")
		if errors.Is(err, http.ErrNoCookie) {
			a.logger.Info("No auth provided")
			http.Redirect(w, r, redirectLogin, http.StatusTemporaryRedirect)
			return
		}

		auth, err := base64.StdEncoding.DecodeString(authBase64.Value)
		if err != nil {
			a.logger.Error(err.Error())
			return
		}

		token, err := service.ReadToken(auth, a.key)
		if err != nil {
			a.logger.Error(err.Error())
			http.Redirect(w, r, redirectLogin, http.StatusTemporaryRedirect)
			return
		}

		user, err := a.userRepository.Get(r.Context(), token.UserID)
		if err != nil {
			a.logger.Error(err.Error())
			return
		}

		r = r.WithContext(context.WithValue(r.Context(), UserKey, user))
		a.logger.
			Info(
				"user recognized",
				slog.Uint64("userid", uint64(token.UserID)),
				slog.String("username", token.Username),
			)
		next(w, r)
	}
}

func GetUserFromCtx(r *http.Request) *repository.User {
	tokenValue := r.Context().Value(UserKey)
	if token, ok := tokenValue.(*repository.User); ok {
		return token
	}
	return nil
}

type InitialSetupMiddleware struct {
	userRepository repository.UserRepository
}

func NewInitialSetupMiddleware(userRepository repository.UserRepository) *InitialSetupMiddleware {
	return &InitialSetupMiddleware{
		userRepository: userRepository,
	}
}

func (i *InitialSetupMiddleware) Check(next http.HandlerFunc) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		// if user has been set to context it is logged in already
		token := GetUserFromCtx(r)
		if token != nil {
			next(w, r)
			return
		}

		path := r.URL.Path
		if path == "/initial" {
			next(w, r)
			return
		}

		exists, err := i.userRepository.Any(r.Context())
		if err != nil {
			InternalServerError(w, err)
			return
		}

		if exists {
			next(w, r)
			return
		}
		http.Redirect(w, r, "/initial", http.StatusTemporaryRedirect)
	}
}