TRA-4157 fix ws auth (#669)

* Update socket_routes.go, user_controller.go, and 2 more files...

* Update user_controller.go

* Switch to http-only cookies for more security
This commit is contained in:
RamiBerm
2022-01-20 14:10:25 +02:00
committed by GitHub
parent 6bab381280
commit 676e50b0b1
4 changed files with 50 additions and 37 deletions

View File

@@ -1,49 +1,51 @@
package middlewares
import (
"errors"
"mizuserver/pkg/config"
"mizuserver/pkg/providers"
"time"
"net/http"
"github.com/gin-gonic/gin"
"github.com/patrickmn/go-cache"
"github.com/up9inc/mizu/shared/logger"
)
const cachedValidTokensRetainmentTime = time.Minute * 1
var cachedValidTokens = cache.New(cachedValidTokensRetainmentTime, cachedValidTokensRetainmentTime)
const errorMessage = "unknown authentication error occured"
func RequiresAuth() gin.HandlerFunc {
return func(c *gin.Context) {
// auth is irrelevant for ephermeral mizu
// authentication is irrelevant for ephermeral mizu
if !config.Config.StandaloneMode {
c.Next()
return
}
token := c.GetHeader("x-session-token")
if token == "" {
c.AbortWithStatusJSON(401, gin.H{"error": "token header is empty"})
token, err := c.Cookie("x-session-token")
if err != nil {
if errors.Is(err, http.ErrNoCookie) {
c.AbortWithStatusJSON(401, gin.H{"error": "could not find session cookie"})
} else {
logger.Log.Errorf("error reading cookie %s", err)
c.AbortWithStatusJSON(500, gin.H{"error": errorMessage})
}
return
}
if _, isTokenCached := cachedValidTokens.Get(token); isTokenCached {
c.Next()
if token == "" {
c.AbortWithStatusJSON(401, gin.H{"error": "token cookie is empty"})
return
}
if isTokenValid, err := providers.VerifyToken(token, c.Request.Context()); err != nil {
logger.Log.Errorf("error verifying token %s", err)
c.AbortWithStatusJSON(401, gin.H{"error": "unknown auth error occured"})
c.AbortWithStatusJSON(500, gin.H{"error": errorMessage})
return
} else if !isTokenValid {
c.AbortWithStatusJSON(401, gin.H{"error": "invalid token"})
return
}
cachedValidTokens.Set(token, true, cachedValidTokensRetainmentTime)
c.Next()
}
}