first commit
This commit is contained in:
@@ -0,0 +1,71 @@
|
||||
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)
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user