diff options
Diffstat (limited to '')
-rw-r--r-- | config.go | 1 | ||||
-rw-r--r-- | forge.scfg | 1 | ||||
-rw-r--r-- | http_handle_login.go | 36 |
3 files changed, 38 insertions, 0 deletions
@@ -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"` @@ -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 } |