feat: auth handlers and session management

This commit is contained in:
2026-08-26 23:16:08 +08:00
parent 2852097b26
commit af6aba3d37
4 changed files with 229 additions and 0 deletions
+50
View File
@@ -0,0 +1,50 @@
package server
import (
"bytes"
"net/http"
"net/http/httptest"
"testing"
"time"
)
func TestLoginSuccess(t *testing.T) {
s := &Server{
accessToken: "secret123",
sessions: make(map[string]int64),
loginAttempts: make(map[string]int),
loginLockout: make(map[string]time.Time),
}
req := httptest.NewRequest("POST", "/api/login", bytes.NewBufferString(`{"token":"secret123"}`))
req.Header.Set("Content-Type", "application/json")
w := httptest.NewRecorder()
s.handleLogin(w, req)
if w.Code != http.StatusOK {
t.Errorf("Status = %d, want %d", w.Code, http.StatusOK)
}
if len(w.Header().Values("Set-Cookie")) == 0 {
t.Error("Expected Set-Cookie header")
}
}
func TestLoginFailure(t *testing.T) {
s := &Server{
accessToken: "secret123",
sessions: make(map[string]int64),
loginAttempts: make(map[string]int),
loginLockout: make(map[string]time.Time),
}
req := httptest.NewRequest("POST", "/api/login", bytes.NewBufferString(`{"token":"wrong"}`))
req.Header.Set("Content-Type", "application/json")
w := httptest.NewRecorder()
s.handleLogin(w, req)
if w.Code != http.StatusUnauthorized {
t.Errorf("Status = %d, want %d", w.Code, http.StatusUnauthorized)
}
}