Skip to content
Permalink
Browse files

add grafana proxy

  • Loading branch information...
birdayz committed May 1, 2019
1 parent 9f70dff commit 98246eafee3e66d01675f912f4d965cd51491df3
@@ -0,0 +1,151 @@
package main

import (
"context"
"encoding/base64"
"errors"
"fmt"
"net/http"
"net/http/httputil"
"net/url"
"time"

jwt "github.com/dgrijalva/jwt-go"
"github.com/spf13/viper"
"go.uber.org/zap"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"

cache "github.com/patrickmn/go-cache"

"github.com/infinimesh/infinimesh/pkg/node/nodepb"
)

var (
signingSecret []byte
accountIDClaim = "account_id"

nodeserver string

log *zap.Logger

accountService nodepb.AccountServiceClient

userCache *cache.Cache
)

func init() {
log, _ = zap.NewDevelopment()

viper.SetDefault("NODE_HOST", "localhost:8082")
viper.AutomaticEnv()

nodeserver = viper.GetString("NODE_HOST")

{
b64SignSecret := viper.GetString("JWT_SIGNING_KEY")
if b64SignSecret == "" {
panic("Invalid signing secret")
}
s, err := base64.StdEncoding.DecodeString(b64SignSecret)
if err != nil {
panic("Failed to base64 decode sign secret")
}
signingSecret = s
}

userCache = cache.New(1*time.Second, 5*time.Second)
}

func main() {
u, err := url.Parse("http://localhost:3000")
if err != nil {
panic(err)
}
proxy := httputil.NewSingleHostReverseProxy(u)

c, err := grpc.Dial(nodeserver, grpc.WithInsecure())
if err != nil {
panic(err)
}

accountService = nodepb.NewAccountServiceClient(c)

http.HandleFunc("/", handler(proxy))
err = http.ListenAndServe(":8080", nil)
if err != nil {
panic(err)
}
}

func handler(p *httputil.ReverseProxy) func(http.ResponseWriter, *http.Request) {
return func(w http.ResponseWriter, r *http.Request) {
cookie, err := r.Cookie("token")
if err != nil {
w.WriteHeader(http.StatusUnauthorized)
return
}

userID, err := ParseJWT(cookie.Value)
if err != nil {
log.Error("Failed")
w.WriteHeader(http.StatusUnauthorized)
return
}

var name string
if cachedUser, ok := userCache.Get(userID); ok {
if userString, ok := cachedUser.(string); ok {
log.Debug("Using cached value", zap.String("userID", userID), zap.String("username", userString))
name = userString
}
} else {
acc, err := accountService.GetAccount(context.Background(), &nodepb.GetAccountRequest{
Id: userID,
})
if err != nil {
log.Error("Failed to fetch account", zap.String("userID", userID), zap.Error(err))
w.WriteHeader(http.StatusUnauthorized)
return
}
name = acc.Name

userCache.Add(userID, acc.Name, time.Minute*1)
}

r.Header.Set("X-WEBAUTH-USER", name)
p.ServeHTTP(w, r)
}
}

func ParseJWT(tokenString string) (user string, err error) {
token, err := jwt.Parse(tokenString, func(t *jwt.Token) (interface{}, error) {
if _, ok := t.Method.(*jwt.SigningMethodHMAC); !ok {
return nil, status.Error(codes.Unauthenticated, fmt.Sprintf("Unexpected signing method: %v", t.Header["alg"]))
}
return signingSecret, nil
})
if err != nil {
return "", err
}

if !token.Valid {
return "", errors.New("Invalid token")
}

if claims, ok := token.Claims.(jwt.MapClaims); ok {
log.Info("Validated token", zap.Any("claims", claims))

if accountID, ok := claims[accountIDClaim]; ok {
if accountIDStr, ok := accountID.(string); ok {
return accountIDStr, nil
}

}
log.Info("Token does not contain account id field", zap.Any("token", token))
}

return "", errors.New("Invalid token")

}
4 go.mod
@@ -8,7 +8,7 @@ require (
github.com/alecthomas/units v0.0.0-20151022065526-2efee857e7cf // indirect
github.com/avast/retry-go v2.2.0+incompatible
github.com/birdayz/conjungo v1.0.1-0.20181127234741-4eb7246db343
github.com/cskr/pubsub v1.0.1
github.com/cskr/pubsub v1.0.2
github.com/dgraph-io/dgo v0.0.0-20181226155115-a20f509ade83
github.com/dgrijalva/jwt-go v3.2.0+incompatible
github.com/eapache/go-resiliency v1.1.0 // indirect
@@ -26,7 +26,6 @@ require (
github.com/grpc-ecosystem/go-grpc-middleware v1.0.0
github.com/grpc-ecosystem/grpc-gateway v1.7.0
github.com/hokaccha/go-prettyjson v0.0.0-20180920040306-f579f869bbfe
github.com/imdario/mergo v0.3.7
github.com/inconshreveable/mousetrap v1.0.0 // indirect
github.com/infinimesh/mqtt-go v0.0.0-20190331134856-46f3ca3950fb
github.com/jeremywohl/flatten v0.0.0-20180923035001-588fe0d4c603
@@ -36,6 +35,7 @@ require (
github.com/manifoldco/promptui v0.3.2
github.com/mitchellh/go-homedir v1.1.0
github.com/nicksnyder/go-i18n v1.10.0 // indirect
github.com/patrickmn/go-cache v2.1.0+incompatible
github.com/pierrec/lz4 v2.0.5+incompatible // indirect
github.com/pkg/errors v0.8.0 // indirect
github.com/rcrowley/go-metrics v0.0.0-20181016184325-3113b8401b8a // indirect
8 go.sum
@@ -24,8 +24,8 @@ github.com/chzyer/test v0.0.0-20180213035817-a1ea475d72b1 h1:q763qf9huN11kDQavWs
github.com/chzyer/test v0.0.0-20180213035817-a1ea475d72b1/go.mod h1:Q3SI9o4m/ZMnBNeIyt5eFwwo7qiLfzFZmjNmxjkiQlU=
github.com/client9/misspell v0.3.4 h1:ta993UF76GwbvJcIo3Y68y/M3WxlpEHPWIGDkJYwzJI=
github.com/client9/misspell v0.3.4/go.mod h1:qj6jICC3Q7zFZvVWo7KLAzC3yx5G7kyvSDkc90ppPyw=
github.com/cskr/pubsub v1.0.1 h1:zAaDV+uWy55qU+guKH0skkEGTePJpnBy/BJ3YwwDmOo=
github.com/cskr/pubsub v1.0.1/go.mod h1:Sa0GZ6ObN+iL7BemRztT4twaIREPOG+9UXtWhOL/SLg=
github.com/cskr/pubsub v1.0.2 h1:vlOzMhl6PFn60gRlTQQsIfVwaPB/B/8MziK8FhEPt/0=
github.com/cskr/pubsub v1.0.2/go.mod h1:/8MzYXk/NJAz782G8RPkFzXTZVu63VotefPnR9TIRis=
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
@@ -77,8 +77,6 @@ github.com/hokaccha/go-prettyjson v0.0.0-20180920040306-f579f869bbfe h1:MCgzztuo
github.com/hokaccha/go-prettyjson v0.0.0-20180920040306-f579f869bbfe/go.mod h1:pFlLw2CfqZiIBOx6BuCeRLCrfxBJipTY0nIOF/VbGcI=
github.com/hpcloud/tail v1.0.0 h1:nfCOvKYfkgYP8hkirhJocXT2+zOD8yUNjXaWfTlyFKI=
github.com/hpcloud/tail v1.0.0/go.mod h1:ab1qPbhIpdTxEkNHXyeSf5vhxWSCs/tWer42PpOxQnU=
github.com/imdario/mergo v0.3.7 h1:Y+UAYTZ7gDEuOfhxKWy+dvb5dRQ6rJjFSdX2HZY1/gI=
github.com/imdario/mergo v0.3.7/go.mod h1:2EnlNZ0deacrJVfApfmtdGgDfMuh/nq6Ok1EcJh5FfA=
github.com/inconshreveable/mousetrap v1.0.0 h1:Z8tu5sraLXCXIcARxBp/8cbvlwVa7Z1NHg9XEKhtSvM=
github.com/inconshreveable/mousetrap v1.0.0/go.mod h1:PxqpIevigyE2G7u3NXJIT2ANytuPF1OarO4DADm73n8=
github.com/infinimesh/mqtt-go v0.0.0-20190331134856-46f3ca3950fb h1:dGawVY1NNPz1LFk3ct/8fUrQs7xrxciEsJf9XX3NI0Y=
@@ -122,6 +120,8 @@ github.com/onsi/ginkgo v1.7.0 h1:WSHQ+IS43OoUrWtD1/bbclrwK8TTH5hzp+umCiuxHgs=
github.com/onsi/ginkgo v1.7.0/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE=
github.com/onsi/gomega v1.4.3 h1:RE1xgDvH7imwFD45h+u2SgIfERHlS2yNG4DObb5BSKU=
github.com/onsi/gomega v1.4.3/go.mod h1:ex+gbHU/CVuBBDIJjb2X0qEXbFg53c61hWP/1CpauHY=
github.com/patrickmn/go-cache v2.1.0+incompatible h1:HRMgzkcYKYpi3C8ajMPV8OFXaaRUnok+kx1WdO15EQc=
github.com/patrickmn/go-cache v2.1.0+incompatible/go.mod h1:3Qf8kWWT7OJRJbdiICTKqZju1ZixQ/KpMGzzAfe6+WQ=
github.com/pelletier/go-toml v1.2.0 h1:T5zMGML61Wp+FlcbWjRDT7yAxhJNAiPPLOFECq181zc=
github.com/pelletier/go-toml v1.2.0/go.mod h1:5z9KED0ma1S8pY6P1sdut58dfprrGBbd/94hg7ilaic=
github.com/pierrec/lz4 v2.0.5+incompatible h1:2xWsjqPFWcplujydGg4WmhC/6fZqK42wMM8aXeqhl0I=

Some generated files are not rendered by default. Learn more.

Some generated files are not rendered by default. Learn more.

Some generated files are not rendered by default. Learn more.

Some generated files are not rendered by default. Learn more.

0 comments on commit 98246ea

Please sign in to comment.
You can’t perform that action at this time.