aboutsummaryrefslogtreecommitdiffstats
path: root/web/command/handler/authenticate.go
diff options
context:
space:
mode:
authorLeonardo Bishop <me@leonardobishop.net>2025-07-14 01:24:40 +0100
committerLeonardo Bishop <me@leonardobishop.net>2025-07-14 01:24:40 +0100
commit08a3fb8a2b0281c3c329b33215ec7f8866add606 (patch)
treeff8a5413449ea198bc063bf0099fc025ea49c82b /web/command/handler/authenticate.go
parent684787bcb72aece2aa914597a3bc8788432e66f7 (diff)
Add authentication and ability to change host
Diffstat (limited to 'web/command/handler/authenticate.go')
-rw-r--r--web/command/handler/authenticate.go52
1 files changed, 52 insertions, 0 deletions
diff --git a/web/command/handler/authenticate.go b/web/command/handler/authenticate.go
new file mode 100644
index 0000000..1c7d312
--- /dev/null
+++ b/web/command/handler/authenticate.go
@@ -0,0 +1,52 @@
+package handler
+
+import (
+ "crypto/subtle"
+ "fmt"
+ "net/http"
+
+ "github.com/LMBishop/scrapbook/pkg/auth"
+ "github.com/LMBishop/scrapbook/pkg/config"
+ "github.com/LMBishop/scrapbook/web/command/html"
+ . "maragu.dev/gomponents"
+ ghttp "maragu.dev/gomponents/http"
+)
+
+func GetAuthenticate() func(http.ResponseWriter, *http.Request) {
+ return ghttp.Adapt(func(w http.ResponseWriter, r *http.Request) (Node, error) {
+ return html.AuthenticatePage(""), nil
+ })
+}
+
+func PostAuthenticate(mainConfig *config.MainConfig, authenticator *auth.Authenticator) func(http.ResponseWriter, *http.Request) {
+ return func(w http.ResponseWriter, r *http.Request) {
+ err := r.ParseForm()
+ if err != nil {
+ html.AuthenticatePage(err.Error()).Render(w)
+ return
+ }
+
+ token := r.Form.Get("token")
+
+ if len(mainConfig.Command.Secret) == 0 || subtle.ConstantTimeCompare([]byte(token), []byte(mainConfig.Command.Secret)) != 1 {
+ html.AuthenticatePage("The secret key is incorrect").Render(w)
+ return
+ }
+
+ jwt, err := authenticator.NewJwt()
+ if err != nil {
+ html.AuthenticatePage(fmt.Errorf("Failed to create jwt: %w", err).Error()).Render(w)
+ return
+ }
+
+ http.SetCookie(w, &http.Cookie{
+ Name: "session",
+ Value: jwt,
+
+ Secure: true,
+ SameSite: http.SameSiteStrictMode,
+ HttpOnly: true,
+ })
+ http.Redirect(w, r, "/", 302)
+ }
+}