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
71 lines
1.5 KiB
package auth
|
|
|
|
import (
|
|
"context"
|
|
"encoding/base64"
|
|
"encoding/json"
|
|
"github.com/gin-gonic/gin"
|
|
"github.com/gissleh/stufflog/internal/slerrors"
|
|
"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(uuid string) gin.HandlerFunc {
|
|
return func(c *gin.Context) {
|
|
c.Request = c.Request.WithContext(
|
|
context.WithValue(c.Request.Context(), &contextKey, uuid),
|
|
)
|
|
}
|
|
}
|
|
|
|
func abortRequest(c *gin.Context) {
|
|
c.AbortWithStatusJSON(http.StatusUnauthorized, slerrors.ErrorResponse{
|
|
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() gin.HandlerFunc {
|
|
return func(c *gin.Context) {
|
|
auth := c.GetHeader("Authorization")
|
|
split := strings.Split(auth, ".")
|
|
|
|
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(
|
|
context.WithValue(c.Request.Context(), &contextKey, sub),
|
|
)
|
|
} else {
|
|
abortRequest(c)
|
|
return
|
|
}
|
|
} else {
|
|
abortRequest(c)
|
|
}
|
|
}
|
|
}
|