From 4316301e221407614e4271c910a90cdfb2e1e938 Mon Sep 17 00:00:00 2001 From: William Chong Date: Wed, 19 Jun 2024 04:24:45 +0800 Subject: [PATCH] [preprocessor/webhook] reuse browsertrix jwt before exp --- webhook/browsertrix.go | 18 +++++++++++++++++- 1 file changed, 17 insertions(+), 1 deletion(-) diff --git a/webhook/browsertrix.go b/webhook/browsertrix.go index 3455317..7c96d58 100644 --- a/webhook/browsertrix.go +++ b/webhook/browsertrix.go @@ -11,8 +11,10 @@ import ( "os" "path/filepath" "strings" + "sync" "time" + "github.com/lestrrat-go/jwx/v2/jwt" "github.com/starlinglab/integrity-v2/aa" "github.com/starlinglab/integrity-v2/config" wacz "github.com/starlinglab/integrity-v2/preprocessor/wacz" @@ -41,7 +43,19 @@ type LoginResponse struct { TokenType string `json:"token_type"` } +var browsertrixJwtMutex = &sync.RWMutex{} +var browsertrixJwtToken string + func getJWTToken() (string, error) { + browsertrixJwtMutex.RLock() + if browsertrixJwtToken != "" { + token, err := jwt.Parse([]byte(browsertrixJwtToken), nil) + browsertrixJwtMutex.RUnlock() + if err == nil && token.Expiration().After(time.Now()) { + return browsertrixJwtToken, nil + } + } + browsertrixJwtMutex.Lock() b, err := json.Marshal(map[string]string{ "username": config.GetConfig().Browsertrix.User, "password": config.GetConfig().Browsertrix.Password, @@ -70,7 +84,9 @@ func getJWTToken() (string, error) { if err != nil { return "", err } - return value.AccessToken, nil + browsertrixJwtToken = value.AccessToken + browsertrixJwtMutex.Unlock() + return browsertrixJwtToken, nil } type CrawlInfoResponse struct {