protect auth token with mutex
Signed-off-by: Tobias Erbshäußer <tobias@tesoft.dev>
This commit is contained in:
@@ -8,10 +8,12 @@ import (
|
|||||||
"io"
|
"io"
|
||||||
"log"
|
"log"
|
||||||
"net/http"
|
"net/http"
|
||||||
|
"sync"
|
||||||
)
|
)
|
||||||
|
|
||||||
type ApiHandler struct {
|
type ApiHandler struct {
|
||||||
db *Database
|
db *Database
|
||||||
|
mutex sync.RWMutex
|
||||||
authToken *string
|
authToken *string
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -60,7 +62,10 @@ func (h *ApiHandler) ServeLoginPost(writer http.ResponseWriter, request *http.Re
|
|||||||
rawAuthToken := make([]byte, 128)
|
rawAuthToken := make([]byte, 128)
|
||||||
_, _ = rand.Read(rawAuthToken)
|
_, _ = rand.Read(rawAuthToken)
|
||||||
authToken := hex.EncodeToString(rawAuthToken)
|
authToken := hex.EncodeToString(rawAuthToken)
|
||||||
|
|
||||||
|
h.mutex.Lock()
|
||||||
h.authToken = &authToken
|
h.authToken = &authToken
|
||||||
|
h.mutex.Unlock()
|
||||||
|
|
||||||
cookie := http.Cookie{}
|
cookie := http.Cookie{}
|
||||||
cookie.Name = authTokenCookieName
|
cookie.Name = authTokenCookieName
|
||||||
@@ -85,7 +90,9 @@ func (h *ApiHandler) ServeLogoutPost(writer http.ResponseWriter, request *http.R
|
|||||||
http.SetCookie(writer, &cookie)
|
http.SetCookie(writer, &cookie)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
h.mutex.Lock()
|
||||||
h.authToken = nil
|
h.authToken = nil
|
||||||
|
h.mutex.Unlock()
|
||||||
|
|
||||||
WriteResponse(writer, http.StatusOK, map[string]interface{}{})
|
WriteResponse(writer, http.StatusOK, map[string]interface{}{})
|
||||||
|
|
||||||
@@ -97,7 +104,9 @@ func (h *ApiHandler) ProcessAuth(next http.Handler, required bool) http.Handler
|
|||||||
isAuthorized := false
|
isAuthorized := false
|
||||||
cookie, _ := request.Cookie(authTokenCookieName)
|
cookie, _ := request.Cookie(authTokenCookieName)
|
||||||
if cookie != nil {
|
if cookie != nil {
|
||||||
|
h.mutex.RLock()
|
||||||
isAuthorized = h.authToken != nil && *h.authToken == cookie.Value
|
isAuthorized = h.authToken != nil && *h.authToken == cookie.Value
|
||||||
|
h.mutex.RUnlock()
|
||||||
}
|
}
|
||||||
|
|
||||||
if !isAuthorized && required {
|
if !isAuthorized && required {
|
||||||
|
|||||||
Reference in New Issue
Block a user