Skip to content

Commit

Permalink
fix(tokens): probably fix of incorrect refreshing of tokens
Browse files Browse the repository at this point in the history
  • Loading branch information
Satont committed Aug 16, 2024
1 parent 8c951ad commit 68ebe26
Show file tree
Hide file tree
Showing 2 changed files with 57 additions and 4 deletions.
25 changes: 25 additions & 0 deletions apps/tokens/cmd/decode/decode.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
package main

import (
"fmt"
"log"
"os"

"github.com/satont/twir/libs/crypto"
)

func main() {
args := os.Args
if len(args) < 3 {
log.Fatal("Wrong number of arguments")
}

cipherKey := args[1]

encoded, err := crypto.Decrypt(args[2], cipherKey)
if err != nil {
log.Fatal(err)
}

fmt.Println("encoded: ", encoded)
}
36 changes: 32 additions & 4 deletions apps/tokens/internal/grpc_impl/grpc_impl.go
Original file line number Diff line number Diff line change
Expand Up @@ -53,12 +53,33 @@ type tokensGrpcImpl struct {
redSync *redsync.Redsync
}

func rateLimitFunc(lastResponse *helix.Response) error {
if lastResponse.GetRateLimitRemaining() > 0 {
return nil
}

var reset64 int64
reset64 = int64(lastResponse.GetRateLimitReset())

currentTime := time.Now().UTC().Unix()

if currentTime < reset64 {
timeDiff := time.Duration(reset64 - currentTime)
if timeDiff > 0 {
time.Sleep(timeDiff * time.Second)
}
}

return nil
}

func NewTokens(opts Opts) error {
helixClient, err := helix.NewClient(
&helix.Options{
ClientID: opts.Config.TwitchClientId,
ClientSecret: opts.Config.TwitchClientSecret,
RedirectURI: opts.Config.TwitchCallbackUrl,
ClientID: opts.Config.TwitchClientId,
ClientSecret: opts.Config.TwitchClientSecret,
RedirectURI: opts.Config.TwitchCallbackUrl,
RateLimitFunc: rateLimitFunc,
},
)
if err != nil {
Expand Down Expand Up @@ -161,6 +182,10 @@ func (c *tokensGrpcImpl) RequestUserToken(
return nil, err
}

if decryptedRefreshToken == "" {
return nil, errors.New("refresh token is empty")
}

if isTokenExpired(int(user.Token.ExpiresIn), user.Token.ObtainmentTimestamp) {
newToken, err := c.globalClient.RefreshUserAccessToken(decryptedRefreshToken)
if err != nil {
Expand All @@ -170,6 +195,10 @@ func (c *tokensGrpcImpl) RequestUserToken(
return nil, fmt.Errorf("refresh token error: %s", newToken.ErrorMessage)
}

if newToken.StatusCode != 200 || newToken.Data.AccessToken == "" {
return nil, fmt.Errorf("refresh token status code: %d", newToken.StatusCode)
}

newRefreshToken, err := crypto.Encrypt(newToken.Data.RefreshToken, c.config.TokensCipherKey)
if err != nil {
return nil, err
Expand All @@ -191,7 +220,6 @@ func (c *tokensGrpcImpl) RequestUserToken(

c.log.Info(
"user token refreshed",
slog.Any("twitchResponse", newToken),
slog.String("user_id", user.ID),
slog.Int("expires_in", int(user.Token.ExpiresIn)),
slog.String("access_token", newAccessToken),
Expand Down

0 comments on commit 68ebe26

Please sign in to comment.