Improve Session / Auth, APICall

This commit is contained in:
Samuel Lorch 2023-03-11 14:54:21 +01:00
parent fb70f41fcb
commit 2fe21169bb
11 changed files with 167 additions and 115 deletions

View file

@ -8,14 +8,17 @@ import (
"time"
"golang.org/x/exp/slog"
"nfsense.net/nfsense/pkg/session"
)
func HandleAPI(w http.ResponseWriter, r *http.Request) {
_, s := GetSession(r)
slog.Info("Api Handler hit")
_, s := session.GetSession(r)
if s == nil {
// Fallthrough after so that jsonrpc can still deliver a valid jsonrpc error
w.WriteHeader(http.StatusUnauthorized)
return
}
defer func() {
if r := recover(); r != nil {
slog.Error("Recovered Panic Handling HTTP API Request", fmt.Errorf("%v", r), "stack", debug.Stack())
@ -23,10 +26,10 @@ func HandleAPI(w http.ResponseWriter, r *http.Request) {
return
}
}()
ctx, cancel := context.WithTimeout(context.WithValue(r.Context(), SessionKey, s), time.Second*10)
ctx, cancel := context.WithTimeout(context.WithValue(r.Context(), session.SessionKey, s), time.Second*10)
defer cancel()
err := apiHandler.HandleRequest(ctx, r.Body, w)
err := apiHandler.HandleRequest(ctx, s, r.Body, w)
if err != nil {
slog.Error("Handling HTTP API Request", err)
}

View file

@ -10,6 +10,7 @@ import (
"nfsense.net/nfsense/pkg/definitions"
"nfsense.net/nfsense/pkg/jsonrpc"
"nfsense.net/nfsense/pkg/session"
)
var server http.Server
@ -32,7 +33,7 @@ func StartWebserver(conf *definitions.Config, _apiHandler *jsonrpc.Handler) {
stopCleanup = make(chan struct{})
go CleanupSessions(stopCleanup)
go session.CleanupSessions(stopCleanup)
go func() {
if err := server.ListenAndServe(); !errors.Is(err, http.ErrServerClosed) {

View file

@ -4,94 +4,17 @@ import (
"encoding/json"
"io"
"net/http"
"runtime/debug"
"sync"
"time"
"github.com/google/uuid"
"golang.org/x/exp/slog"
"nfsense.net/nfsense/pkg/session"
)
type SessionKeyType string
const SessionKey SessionKeyType = "session"
const SessionCookieName string = "session"
type Session struct {
Username string
Expires time.Time
// TODO Add []websocket.Conn pointer to close all active websockets, alternativly do this via context cancelation
}
type LoginRequest struct {
Username string `json:"username"`
Password string `json:"password"`
}
type SessionResponse struct {
CommitHash string `json:"commit_hash"`
}
var sessionsSync sync.Mutex
var sessions map[string]*Session = map[string]*Session{}
var CommitHash = func() string {
if info, ok := debug.ReadBuildInfo(); ok {
for _, setting := range info.Settings {
if setting.Key == "vcs.revision" {
return setting.Value
}
}
}
return "asd"
}()
func GetSession(r *http.Request) (string, *Session) {
c, err := r.Cookie("session")
if err != nil {
return "", nil
}
s, ok := sessions[c.Value]
if ok {
return c.Value, s
}
return "", nil
}
func GenerateSession(w http.ResponseWriter, username string) {
id := uuid.New().String()
expires := time.Now().Add(time.Minute * 5)
sessionsSync.Lock()
defer sessionsSync.Unlock()
sessions[id] = &Session{
Username: username,
Expires: expires,
}
http.SetCookie(w, &http.Cookie{Name: SessionCookieName, HttpOnly: true, SameSite: http.SameSiteStrictMode, Value: id, Expires: expires})
}
func CleanupSessions(stop chan struct{}) {
tick := time.NewTicker(time.Minute)
for {
select {
case <-tick.C:
ids := []string{}
sessionsSync.Lock()
for id, s := range sessions {
if time.Now().After(s.Expires) {
ids = append(ids, id)
}
}
for _, id := range ids {
delete(sessions, id)
}
sessionsSync.Unlock()
case <-stop:
return
}
}
}
func HandleLogin(w http.ResponseWriter, r *http.Request) {
buf, err := io.ReadAll(r.Body)
if err != nil {
@ -106,7 +29,7 @@ func HandleLogin(w http.ResponseWriter, r *http.Request) {
}
if req.Username == "admin" && req.Password == "12345" {
slog.Info("User Login Successfull")
GenerateSession(w, req.Username)
session.GenerateSession(w, req.Username)
w.WriteHeader(http.StatusOK)
return
}
@ -114,25 +37,21 @@ func HandleLogin(w http.ResponseWriter, r *http.Request) {
}
func HandleLogout(w http.ResponseWriter, r *http.Request) {
http.SetCookie(w, &http.Cookie{Name: SessionCookieName, HttpOnly: true, SameSite: http.SameSiteStrictMode, Value: "", Expires: time.Now()})
http.SetCookie(w, session.GetCookie("", time.Now()))
w.WriteHeader(http.StatusOK)
}
func HandleSession(w http.ResponseWriter, r *http.Request) {
id, s := GetSession(r)
id, s := session.GetSession(r)
if s == nil {
w.WriteHeader(http.StatusUnauthorized)
return
}
sessionsSync.Lock()
defer sessionsSync.Unlock()
if s != nil {
s.Expires = time.Now().Add(time.Minute * 5)
}
http.SetCookie(w, &http.Cookie{Name: SessionCookieName, HttpOnly: true, SameSite: http.SameSiteStrictMode, Value: id, Expires: s.Expires})
session.ExtendSession(s)
http.SetCookie(w, session.GetCookie(id, s.Expires))
w.WriteHeader(http.StatusOK)
resp := SessionResponse{
CommitHash: CommitHash,
resp := session.SessionResponse{
CommitHash: session.CommitHash,
}
res, err := json.Marshal(resp)
if err != nil {

View file

@ -9,17 +9,18 @@ import (
"time"
"golang.org/x/exp/slog"
"nfsense.net/nfsense/pkg/session"
"nhooyr.io/websocket"
)
func HandleWebsocketAPI(w http.ResponseWriter, r *http.Request) {
_, s := GetSession(r)
_, s := session.GetSession(r)
if s == nil {
w.WriteHeader(http.StatusUnauthorized)
return
}
ctx, cancel := context.WithCancel(context.WithValue(r.Context(), SessionKey, s))
ctx, cancel := context.WithCancel(context.WithValue(r.Context(), session.SessionKey, s))
defer cancel()
c, err := websocket.Accept(w, r, nil)
if err != nil {
@ -51,7 +52,7 @@ func HandleWebsocketAPI(w http.ResponseWriter, r *http.Request) {
ctx, cancel := context.WithTimeout(ctx, time.Second*10)
defer cancel()
err := apiHandler.HandleRequest(ctx, bytes.NewReader(m), w)
err := apiHandler.HandleRequest(ctx, s, bytes.NewReader(m), w)
if err != nil {
slog.Error("Handling Websocket API Request", err)
}