diff options
author | Gabriel A. Giovanini <mail@gabrielgio.me> | 2024-12-11 17:05:12 +0100 |
---|---|---|
committer | Gabriel A. Giovanini <mail@gabrielgio.me> | 2024-12-11 17:05:12 +0100 |
commit | 1e45ae2ea3497958b2ea6a20137955cfc3bbc964 (patch) | |
tree | 00af0e28864d79d7a9cbb8b693aff1b397b1a949 /pkg/ext/auth.go | |
parent | e6ded0d01117c592ec124f3e02d6c89eeafec382 (diff) | |
download | cerrado-1e45ae2ea3497958b2ea6a20137955cfc3bbc964.tar.gz cerrado-1e45ae2ea3497958b2ea6a20137955cfc3bbc964.tar.bz2 cerrado-1e45ae2ea3497958b2ea6a20137955cfc3bbc964.zip |
feat: Add UI/Handler login process
It adds the whole workflow to store and handle login on both UI and
handler level. With that the login information should be available at
any point given the context.
Diffstat (limited to 'pkg/ext/auth.go')
-rw-r--r-- | pkg/ext/auth.go | 45 |
1 files changed, 45 insertions, 0 deletions
diff --git a/pkg/ext/auth.go b/pkg/ext/auth.go new file mode 100644 index 0000000..bb6c0a2 --- /dev/null +++ b/pkg/ext/auth.go @@ -0,0 +1,45 @@ +package ext + +import ( + "context" + "encoding/base64" + "log/slog" + "net/http" +) + +type authService interface { + ValidateToken(token []byte) (bool, error) +} + +func Authenticate(auth authService) func(next http.HandlerFunc) http.HandlerFunc { + return func(next http.HandlerFunc) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + cookie, err := r.Cookie("auth") + if err != nil { + slog.Error("Error loading cookie", "error", err) + next(w, r) + return + } + + value, err := base64.StdEncoding.DecodeString(cookie.Value) + if err != nil { + slog.Error("Error decoding", "error", err) + next(w, r) + return + } + + valid, err := auth.ValidateToken(value) + if err != nil { + slog.Error("Error validating token", "error", err, "cookie", cookie.Value) + next(w, r) + return + } + + ctx := r.Context() + ctx = context.WithValue(ctx, "logged", true) + + slog.Info("Validated token", "valid?", valid) + next(w, r.WithContext(ctx)) + } + } +} |