40 lines
739 B
Go
40 lines
739 B
Go
package auth
|
|
|
|
import (
|
|
"net/http"
|
|
|
|
"github.com/gin-gonic/gin"
|
|
)
|
|
|
|
const ctxSessionKey = "km_session"
|
|
|
|
func GetSessionFromContext(c *gin.Context) *Session {
|
|
v, _ := c.Get(ctxSessionKey)
|
|
sess, _ := v.(*Session)
|
|
return sess
|
|
}
|
|
|
|
func Middleware() gin.HandlerFunc {
|
|
return func(c *gin.Context) {
|
|
if !authEnabled {
|
|
c.Next()
|
|
return
|
|
}
|
|
|
|
cookie, err := c.Request.Cookie(sessionCookieName)
|
|
if err != nil {
|
|
c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "not authenticated"})
|
|
return
|
|
}
|
|
|
|
sess, err := GetSession(c.Request.Context(), cookie.Value)
|
|
if err != nil {
|
|
c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "session expired"})
|
|
return
|
|
}
|
|
|
|
c.Set(ctxSessionKey, sess)
|
|
c.Next()
|
|
}
|
|
}
|