Render analytics identifiers (#67860)

* Append analytics identifier upon authenticate session

* Add id and module upon syncing user to identity

* Add authModule & id to `IdentityFromSignedInUser`

* Allow req calls in test to use basic auth

* Add `intercom_secret` to grafana config in tests

* Add test for analytics render in html view
This commit is contained in:
linoman
2023-05-05 17:17:18 +02:00
committed by GitHub
parent ae1a85b5ad
commit 15e34505e2
5 changed files with 78 additions and 6 deletions

View File

@@ -3,6 +3,9 @@ package contexthandler
import (
"context"
"crypto/hmac"
"crypto/sha256"
"encoding/hex"
"errors"
"fmt"
"net/http"
@@ -110,6 +113,25 @@ func FromContext(c context.Context) *contextmodel.ReqContext {
return nil
}
func hashUserIdentifier(identifier string, secret string) string {
key := []byte(secret)
h := hmac.New(sha256.New, key)
h.Write([]byte(identifier))
return hex.EncodeToString(h.Sum(nil))
}
func setSignedInUser(reqContext *contextmodel.ReqContext, identity *authn.Identity, intercomSecret string) {
reqContext.SignedInUser = identity.SignedInUser()
if identity.AuthID != "" {
reqContext.SignedInUser.Analytics.Identifier = identity.AuthID
} else {
reqContext.SignedInUser.Analytics.Identifier = identity.Email + "@" + setting.AppUrl
}
if intercomSecret != "" {
reqContext.SignedInUser.Analytics.IntercomIdentifier = hashUserIdentifier(identity.AuthID, intercomSecret)
}
}
// Middleware provides a middleware to initialize the request context.
func (h *ContextHandler) Middleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
@@ -151,7 +173,7 @@ func (h *ContextHandler) Middleware(next http.Handler) http.Handler {
reqContext.LookupTokenErr = err
} else {
reqContext.UserToken = identity.SessionToken
reqContext.SignedInUser = identity.SignedInUser()
setSignedInUser(reqContext, identity, h.Cfg.IntercomSecret)
reqContext.IsSignedIn = !identity.IsAnonymous
reqContext.AllowAnonymous = identity.IsAnonymous
reqContext.IsRenderCall = identity.AuthModule == login.RenderModule