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

@ -36,24 +36,37 @@ async function tryLogin() {
} }
async function tryLogout() { async function tryLogout() {
logout(); console.info("Logging out...");
authState = AuthState.Unauthenticated; authState = AuthState.Unauthenticated;
logout();
} }
function deAuthenticatedCallback() { function UnauthorizedCallback() {
console.info("Unauthenticated"); console.info("Unauthenticated");
authState = AuthState.Unauthenticated; authState = AuthState.Unauthenticated;
} }
onMounted(async() => { async function checkAuth() {
setup(deAuthenticatedCallback); console.info("Checking Auth State...");
let res = await checkAuthentication(); let res = await checkAuthentication();
authState = res.auth; authState = res.auth;
loginDisabled = false; loginDisabled = false;
if (authState === AuthState.Authenticated) { if (authState === AuthState.Authenticated) {
console.info("Already Authenticated ", authState); console.info("Already Authenticated ", authState);
} else if (res.error == null) {
console.info("Unauthorized");
} }
else console.info("Check Authentication error",res.error); else console.info("Check Authentication error",res.error);
}
onMounted(async() => {
setup(UnauthorizedCallback);
await checkAuth();
setInterval(function () {
if (authState === AuthState.Authenticated) {
checkAuth();
}
}.bind(this), 120000);
}); });
</script> </script>
@ -97,11 +110,11 @@ onMounted(async() => {
<FocusTrap> <FocusTrap>
<form @submit="$event => $event.preventDefault()" :disabled="loginDisabled"> <form @submit="$event => $event.preventDefault()" :disabled="loginDisabled">
<h1>nfSense Login</h1> <h1>nfSense Login</h1>
<label for="username" v-text="'Username'"/> <h2 :hidden="!loginDisabled">Logging in...</h2>
<input name="username" v-model="username"/> <label for="username" v-text="'Username'" :hidden="loginDisabled" />
<label for="password" v-text="'Password'" type="password"/> <input name="username" v-model="username" :hidden="loginDisabled" :disabled="loginDisabled"/>
<input name="password" v-model="password"/> <label for="password" v-text="'Password'" type="password" :hidden="loginDisabled"/>
<input name="password" v-model="password" :hidden="loginDisabled" :disabled="loginDisabled"/>
<button @click="tryLogin">Login</button> <button @click="tryLogin">Login</button>
</form> </form>
</FocusTrap> </FocusTrap>

View file

@ -5,19 +5,24 @@ const httpTransport = new HTTPTransport("http://"+ window.location.host +"/api")
const manager = new RequestManager([httpTransport], () => crypto.randomUUID()); const manager = new RequestManager([httpTransport], () => crypto.randomUUID());
const client = new Client(manager); const client = new Client(manager);
let deAuthenticatedCallback; let UnauthorizedCallback: Function;
export function setup(_deAuthenticatedCallback: () => void) { export function setup(_UnauthorizedCallback: () => void) {
deAuthenticatedCallback = _deAuthenticatedCallback; UnauthorizedCallback = _UnauthorizedCallback;
} }
export async function apiCall(method: string, params: Record<string, any>): Promise<any>{ export async function apiCall(method: string, params: Record<string, any>): Promise<any>{
console.debug("Starting API Call...");
try { try {
const result = await client.request({method, params}); const result = await client.request({method, params});
console.debug("api call result", result); console.debug("api call result", result);
return { Data: result, Error: null}; return { Data: result, Error: null};
} catch (ex){ } catch (ex){
console.debug("api call epic fail", ex); if (ex == "Error: Unauthorized") {
UnauthorizedCallback();
} else {
console.debug("api call epic fail", ex);
}
return { Data: null, Error: ex}; return { Data: null, Error: ex};
} }
} }
@ -57,7 +62,10 @@ export async function checkAuthentication() {
} }
} else window.localStorage.setItem("commit_hash", response.data.commit_hash); } else window.localStorage.setItem("commit_hash", response.data.commit_hash);
return {auth: 2, error: null}; return {auth: 2, error: null};
} catch (error) { } catch (error: any) {
if (error.response.status == 401) {
return {auth: 0, error: null};
}
return {auth: 0, error: error}; return {auth: 0, error: error};
} }
} }

View file

@ -34,7 +34,7 @@ func main() {
os.Exit(1) os.Exit(1)
} }
slog.Info("Validating Config") slog.Info("Validating Config...")
if *applyPtr { if *applyPtr {
slog.Info("Applying Config...") slog.Info("Applying Config...")
@ -54,7 +54,7 @@ func main() {
slog.Info("Starting Webserver...") slog.Info("Starting Webserver...")
server.StartWebserver(conf, apiHandler) server.StartWebserver(conf, apiHandler)
slog.Info("Ready") slog.Info("Ready.")
// Handle Exit Signal // Handle Exit Signal
sigChan := make(chan os.Signal, 1) sigChan := make(chan os.Signal, 1)

View file

@ -14,7 +14,6 @@ type Config struct {
func ValidateConfig(conf *Config) error { func ValidateConfig(conf *Config) error {
val := validator.New() val := validator.New()
slog.Info("Registering validator")
val.RegisterValidation("test", nilIfOtherNil) val.RegisterValidation("test", nilIfOtherNil)
return val.Struct(conf) return val.Struct(conf)
} }

View file

@ -10,6 +10,7 @@ import (
"runtime/debug" "runtime/debug"
"golang.org/x/exp/slog" "golang.org/x/exp/slog"
"nfsense.net/nfsense/pkg/session"
) )
type Handler struct { type Handler struct {
@ -25,7 +26,7 @@ func NewHandler(maxRequestSize int64) *Handler {
} }
} }
func (h *Handler) HandleRequest(ctx context.Context, r io.Reader, w io.Writer) error { func (h *Handler) HandleRequest(ctx context.Context, s *session.Session, r io.Reader, w io.Writer) error {
defer func() { defer func() {
if r := recover(); r != nil { if r := recover(); r != nil {
slog.Error("Recovered Panic Handling JSONRPC Request", fmt.Errorf("%v", r), "stack", debug.Stack()) slog.Error("Recovered Panic Handling JSONRPC Request", fmt.Errorf("%v", r), "stack", debug.Stack())
@ -52,6 +53,10 @@ func (h *Handler) HandleRequest(ctx context.Context, r io.Reader, w io.Writer) e
return respondError(w, req.ID, ErrMethodNotFound, fmt.Errorf("Unsupported Jsonrpc version %v", req.Jsonrpc)) return respondError(w, req.ID, ErrMethodNotFound, fmt.Errorf("Unsupported Jsonrpc version %v", req.Jsonrpc))
} }
if s == nil {
return respondError(w, req.ID, 401, fmt.Errorf("Unauthorized"))
}
method, ok := h.methods[req.Method] method, ok := h.methods[req.Method]
if !ok { if !ok {
return respondError(w, req.ID, ErrMethodNotFound, fmt.Errorf("Unknown Method %v", req.Method)) return respondError(w, req.ID, ErrMethodNotFound, fmt.Errorf("Unknown Method %v", req.Method))

View file

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

View file

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

View file

@ -4,94 +4,17 @@ import (
"encoding/json" "encoding/json"
"io" "io"
"net/http" "net/http"
"runtime/debug"
"sync"
"time" "time"
"github.com/google/uuid"
"golang.org/x/exp/slog" "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 { type LoginRequest struct {
Username string `json:"username"` Username string `json:"username"`
Password string `json:"password"` 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) { func HandleLogin(w http.ResponseWriter, r *http.Request) {
buf, err := io.ReadAll(r.Body) buf, err := io.ReadAll(r.Body)
if err != nil { if err != nil {
@ -106,7 +29,7 @@ func HandleLogin(w http.ResponseWriter, r *http.Request) {
} }
if req.Username == "admin" && req.Password == "12345" { if req.Username == "admin" && req.Password == "12345" {
slog.Info("User Login Successfull") slog.Info("User Login Successfull")
GenerateSession(w, req.Username) session.GenerateSession(w, req.Username)
w.WriteHeader(http.StatusOK) w.WriteHeader(http.StatusOK)
return return
} }
@ -114,25 +37,21 @@ func HandleLogin(w http.ResponseWriter, r *http.Request) {
} }
func HandleLogout(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) w.WriteHeader(http.StatusOK)
} }
func HandleSession(w http.ResponseWriter, r *http.Request) { func HandleSession(w http.ResponseWriter, r *http.Request) {
id, s := GetSession(r) id, s := session.GetSession(r)
if s == nil { if s == nil {
w.WriteHeader(http.StatusUnauthorized) w.WriteHeader(http.StatusUnauthorized)
return return
} }
sessionsSync.Lock() session.ExtendSession(s)
defer sessionsSync.Unlock() http.SetCookie(w, session.GetCookie(id, s.Expires))
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})
w.WriteHeader(http.StatusOK) w.WriteHeader(http.StatusOK)
resp := SessionResponse{ resp := session.SessionResponse{
CommitHash: CommitHash, CommitHash: session.CommitHash,
} }
res, err := json.Marshal(resp) res, err := json.Marshal(resp)
if err != nil { if err != nil {

View file

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

10
pkg/session/cookie.go Normal file
View file

@ -0,0 +1,10 @@
package session
import (
"net/http"
"time"
)
func GetCookie(value string, expires time.Time) *http.Cookie {
return &http.Cookie{Name: SessionCookieName, HttpOnly: true, SameSite: http.SameSiteStrictMode, Value: value, Expires: expires}
}

93
pkg/session/session.go Normal file
View file

@ -0,0 +1,93 @@
package session
import (
"net/http"
"runtime/debug"
"sync"
"time"
"github.com/google/uuid"
)
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 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 ExtendSession(s *Session) {
sessionsSync.Lock()
defer sessionsSync.Unlock()
if s != nil {
s.Expires = time.Now().Add(time.Minute * 5)
}
}
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
}
}
}