Skip to content

Commit

Permalink
fix(event-auth): only run authenticate at the start of event auth and…
Browse files Browse the repository at this point in the history
… not for every sent event (#53)
  • Loading branch information
trietsch authored Oct 5, 2021
1 parent cbd8e32 commit 907097f
Showing 1 changed file with 30 additions and 8 deletions.
38 changes: 30 additions & 8 deletions pkg/auth/event.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,22 +6,34 @@ import (
"io"
"net/http"
"streammachine.io/strm/pkg/common"
"time"
)

var token *eventToken

type eventToken struct {
IdToken string `json:"idToken"`
RefreshToken string `json:"refreshToken"`
ExpiresAt int `json:"expiresAt"`
}

type authJson struct {
BillingId string `json:"billingId"`
ClientId string `json:"clientId"`
ClientSecret string `json:"clientSecret"`
}

func GetEventToken(billingId string, clientId string, secret string) string {
// authJson json format for posting to sts. Don't change
type authJson struct {
BillingId string `json:"billingId"`
ClientId string `json:"clientId"`
ClientSecret string `json:"clientSecret"`
if token == nil {
authenticate(billingId, clientId, secret)
} else if int64((*token).ExpiresAt)-30 < time.Now().Unix() {
refresh()
}

return (*token).IdToken
}

func authenticate(billingId string, clientId string, secret string) {
postBody, err := json.Marshal(authJson{
BillingId: billingId, ClientId: clientId, ClientSecret: secret,
})
Expand All @@ -31,12 +43,22 @@ func GetEventToken(billingId string, clientId string, secret string) string {
common.CliExit(err)
defer resp.Body.Close()

return handleAuthResponse(resp)
handleAuthResponse(resp)
}

func handleAuthResponse(resp *http.Response) string {
func refresh() {
b, err := json.Marshal(token)
common.CliExit(err)
resp, err := http.Post(common.EventAuthHost+"/refresh", "application/json; charset=UTF-8", bytes.NewReader(b))
common.CliExit(err)
defer resp.Body.Close()
handleAuthResponse(resp)
}

func handleAuthResponse(resp *http.Response) {
body, err := io.ReadAll(resp.Body)
common.CliExit(err)

eventToken := eventToken{}

err = json.Unmarshal(body, &eventToken)
Expand All @@ -45,5 +67,5 @@ func handleAuthResponse(resp *http.Response) string {
}
common.CliExit(err)

return eventToken.IdToken
token = &eventToken
}

0 comments on commit 907097f

Please sign in to comment.