mirror of
https://github.com/grafana/grafana.git
synced 2024-12-01 21:19:28 -06:00
ed6b3e9e7c
* Introduce preLogoutHooks in authn service * Add gcom_logout_hook * Config the api token from the Grafana config file * Simplify * Add tests for logout hook * Clean up * Update * Address PR comment * Fix
66 lines
1.6 KiB
Go
66 lines
1.6 KiB
Go
package gcomsso
|
|
|
|
import (
|
|
"bytes"
|
|
"context"
|
|
"encoding/json"
|
|
"fmt"
|
|
"log/slog"
|
|
"net/http"
|
|
|
|
"github.com/grafana/grafana/pkg/models/usertoken"
|
|
"github.com/grafana/grafana/pkg/services/auth/identity"
|
|
"github.com/grafana/grafana/pkg/setting"
|
|
)
|
|
|
|
type gcomLogoutRequest struct {
|
|
Token string `json:"idToken"`
|
|
SessionID string `json:"sessionId"`
|
|
}
|
|
|
|
type GComSSOService struct {
|
|
cfg *setting.Cfg
|
|
logger *slog.Logger
|
|
}
|
|
|
|
func ProvideGComSSOService(cfg *setting.Cfg) *GComSSOService {
|
|
return &GComSSOService{
|
|
cfg: cfg,
|
|
logger: slog.Default().With("logger", "gcomsso-service"),
|
|
}
|
|
}
|
|
|
|
func (s *GComSSOService) LogoutHook(ctx context.Context, user identity.Requester, sessionToken *usertoken.UserToken) error {
|
|
s.logger.Debug("Logging out from Grafana.com", "user", user.GetID(), "session", sessionToken.Id)
|
|
data, err := json.Marshal(&gcomLogoutRequest{
|
|
Token: user.GetIDToken(),
|
|
SessionID: fmt.Sprint(sessionToken.Id),
|
|
})
|
|
if err != nil {
|
|
s.logger.Error("failed to marshal request", "error", err)
|
|
return err
|
|
}
|
|
|
|
hReq, err := http.NewRequestWithContext(ctx, http.MethodPost, s.cfg.GrafanaComURL+"/api/logout/grafana/sso", bytes.NewReader(data))
|
|
if err != nil {
|
|
return err
|
|
}
|
|
hReq.Header.Add("Content-Type", "application/json")
|
|
hReq.Header.Add("Authorization", "Bearer "+s.cfg.GrafanaComSSOAPIToken)
|
|
|
|
c := http.DefaultClient
|
|
resp, err := c.Do(hReq)
|
|
if err != nil {
|
|
s.logger.Error("failed to send request", "error", err)
|
|
return err
|
|
}
|
|
// nolint: errcheck
|
|
defer resp.Body.Close()
|
|
|
|
if resp.StatusCode != http.StatusNoContent {
|
|
return fmt.Errorf("failed to logout from grafana com: %d", resp.StatusCode)
|
|
}
|
|
|
|
return nil
|
|
}
|