aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
Diffstat (limited to '')
-rw-r--r--config.go1
-rw-r--r--forge.scfg1
-rw-r--r--http_handle_login.go36
3 files changed, 38 insertions, 0 deletions
diff --git a/config.go b/config.go
index bf4e571..2fdd8c8 100644
--- a/config.go
+++ b/config.go
@@ -18,6 +18,7 @@ var config struct {
HTTP struct {
Net string `scfg:"net"`
Addr string `scfg:"addr"`
+ CookieExpiry int `scfg:"cookie_expiry"`
} `scfg:"http"`
SSH struct {
Net string `scfg:"net"`
diff --git a/forge.scfg b/forge.scfg
index 3b0fc2e..27f6fdc 100644
--- a/forge.scfg
+++ b/forge.scfg
@@ -1,6 +1,7 @@
http {
net tcp
addr :8080
+ cookie_expiry 604800
}
ssh {
diff --git a/http_handle_login.go b/http_handle_login.go
index 9e859c2..6f98859 100644
--- a/http_handle_login.go
+++ b/http_handle_login.go
@@ -1,9 +1,12 @@
package main
import (
+ "crypto/rand"
+ "encoding/base64"
"errors"
"fmt"
"net/http"
+ "time"
"github.com/alexedwards/argon2id"
"github.com/jackc/pgx/v5"
@@ -53,4 +56,37 @@ func handle_login(w http.ResponseWriter, r *http.Request, params map[string]any)
return
}
+ cookie_value, err := random_urlsafe_string(16)
+ now := time.Now()
+ expiry := now.Add(time.Duration(config.HTTP.CookieExpiry) * time.Second)
+
+ cookie := http.Cookie{
+ Name: "session",
+ Value: cookie_value,
+ SameSite: http.SameSiteLaxMode,
+ HttpOnly: true,
+ Secure: false, // TODO
+ Expires: expiry,
+ Path: "/",
+ // TODO: Expire
+ }
+
+ http.SetCookie(w, &cookie)
+
+ _, err = database.Exec(r.Context(), "INSERT INTO sessions (user_id, session_id) VALUES ($1, $2)", user_id, cookie_value)
+ if err != nil {
+ fmt.Fprintln(w, "Error inserting session:", err.Error())
+ return
+ }
+
+ http.Redirect(w, r, "/", http.StatusSeeOther)
+}
+
+func random_urlsafe_string(sz int) (string, error) {
+ r := make([]byte, 3*sz)
+ _, err := rand.Read(r)
+ if err != nil {
+ return "", fmt.Errorf("error generating random string: %w", err)
+ }
+ return base64.RawURLEncoding.EncodeToString(r), nil
}