Loggest thine Stuff
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

71 lines
1.5 KiB

package httpapi
import (
"context"
"encoding/base64"
"encoding/json"
"git.aiterp.net/stufflog3/stufflog3/usecases/auth"
"github.com/gin-gonic/gin"
"net/http"
"strings"
)
var contextKey = struct{}{}
func UserID(ctx context.Context) string {
if c, ok := ctx.(*gin.Context); ok {
return UserID(c.Request.Context())
}
return ctx.Value(&contextKey).(string)
}
func DummyMiddleware(auth *auth.Service, uuid string) gin.HandlerFunc {
return func(c *gin.Context) {
c.Request = c.Request.WithContext(
auth.ContextWithUser(c.Request.Context(), uuid),
)
}
}
func abortRequest(c *gin.Context) {
c.AbortWithStatusJSON(http.StatusUnauthorized, Error{
Code: http.StatusUnauthorized,
Message: "You're not supposed to be here!",
})
}
// TrustingJwtParserMiddleware is meant to be put behind an AWS API gateway that has already
// verified this token.
func TrustingJwtParserMiddleware(auth *auth.Service) gin.HandlerFunc {
return func(c *gin.Context) {
authHeader := c.GetHeader("Authorization")
split := strings.Split(authHeader, ".")
if len(split) >= 3 {
data, err := base64.RawStdEncoding.DecodeString(split[1])
if err != nil {
abortRequest(c)
return
}
fields := make(map[string]interface{})
err = json.Unmarshal(data, &fields)
if err != nil {
abortRequest(c)
return
}
if sub, ok := fields["sub"].(string); ok {
c.Request = c.Request.WithContext(
auth.ContextWithUser(c.Request.Context(), sub),
)
} else {
abortRequest(c)
return
}
} else {
abortRequest(c)
}
}
}