Add Auth0 JWT support
This commit is contained in:
@ -15,8 +15,9 @@ const (
|
||||
)
|
||||
|
||||
var (
|
||||
userIDKey = struct{}{}
|
||||
errSessionData = errors.New("error decoding session data")
|
||||
userIDProviderKey = struct{}{}
|
||||
userIDKey = struct{}{}
|
||||
errSessionData = errors.New("error decoding session data")
|
||||
)
|
||||
|
||||
func headerHandler(next http.HandlerFunc) http.HandlerFunc {
|
||||
|
@ -4,15 +4,27 @@ import (
|
||||
"context"
|
||||
"io/ioutil"
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
jwt "github.com/dgrijalva/jwt-go"
|
||||
)
|
||||
|
||||
const (
|
||||
jwtBase int = iota
|
||||
jwtAuth0
|
||||
)
|
||||
|
||||
func jwtHandler(next http.HandlerFunc) http.HandlerFunc {
|
||||
var key interface{}
|
||||
var jwtProvider int
|
||||
|
||||
cookie := conf.GetString("auth.cookie")
|
||||
|
||||
provider := conf.GetString("auth.provider")
|
||||
if provider == "auth0" {
|
||||
jwtProvider = jwtAuth0
|
||||
}
|
||||
|
||||
conf.BindEnv("auth.secret", "SG_AUTH_SECRET")
|
||||
secret := conf.GetString("auth.secret")
|
||||
|
||||
@ -75,7 +87,17 @@ func jwtHandler(next http.HandlerFunc) http.HandlerFunc {
|
||||
}
|
||||
|
||||
if claims, ok := token.Claims.(*jwt.StandardClaims); ok {
|
||||
ctx := context.WithValue(r.Context(), userIDKey, claims.Id)
|
||||
ctx := r.Context()
|
||||
|
||||
if jwtProvider == jwtAuth0 {
|
||||
sub := strings.Split(claims.Subject, "|")
|
||||
if len(sub) != 2 {
|
||||
ctx = context.WithValue(ctx, userIDProviderKey, sub[0])
|
||||
ctx = context.WithValue(ctx, userIDKey, sub[1])
|
||||
}
|
||||
} else {
|
||||
ctx = context.WithValue(ctx, userIDKey, claims.Subject)
|
||||
}
|
||||
next.ServeHTTP(w, r.WithContext(ctx))
|
||||
}
|
||||
|
||||
|
15
serv/http.go
15
serv/http.go
@ -153,15 +153,24 @@ func authCheck(ctx context.Context) bool {
|
||||
}
|
||||
|
||||
func varValues(ctx context.Context) map[string]interface{} {
|
||||
userIDFn := fasttemplate.TagFunc(func(w io.Writer, _ string) (int, error) {
|
||||
uidFn := fasttemplate.TagFunc(func(w io.Writer, _ string) (int, error) {
|
||||
if v := ctx.Value(userIDKey); v != nil {
|
||||
return w.Write([]byte(v.(string)))
|
||||
}
|
||||
return 0, errNoUserID
|
||||
})
|
||||
|
||||
uidpFn := fasttemplate.TagFunc(func(w io.Writer, _ string) (int, error) {
|
||||
if v := ctx.Value(userIDProviderKey); v != nil {
|
||||
return w.Write([]byte(v.(string)))
|
||||
}
|
||||
return 0, errNoUserID
|
||||
})
|
||||
|
||||
return map[string]interface{}{
|
||||
"USER_ID": userIDFn,
|
||||
"user_id": userIDFn,
|
||||
"USER_ID": uidFn,
|
||||
"user_id": uidFn,
|
||||
"USER_ID_PROVIDER": uidpFn,
|
||||
"user_id_provider": uidpFn,
|
||||
}
|
||||
}
|
||||
|
Reference in New Issue
Block a user