~emersion/hottub

01e2853ed91e4d3b661cc6456df8a67bf53592e4 — Simon Ser 2 months ago fb89878
Refresh sr.ht tokens
2 files changed, 33 insertions(+), 3 deletions(-)

M main.go
M srht.go
M main.go => main.go +4 -0
@@ 276,6 276,10 @@ func main() {
				break
			}

			if err := refreshSrhtToken(r.Context(), db, srhtOAuth2Client, installation); err != nil {
				log.Printf("failed to refresh sr.ht token for installation %v: %v", installation.ID, err)
			}

			ctx := &checkSuiteContext{
				Context:        r.Context(),
				gh:             newInstallationClient(atr, event.Installation),

M srht.go => srht.go +29 -3
@@ 42,9 42,7 @@ func createSrhtClient(endpoint string, oauth2Client *oauth2.Client, installation
}

func saveSrhtToken(ctx context.Context, db *DB, srhtEndpoint string, oauth2Client *oauth2.Client, installation *Installation, tokenResp *oauth2.TokenResp) error {
	installation.SrhtToken = tokenResp.AccessToken
	installation.SrhtRefreshToken = tokenResp.RefreshToken
	installation.SrhtTokenExpiresAt = time.Now().Add(tokenResp.ExpiresIn)
	populateSrhtInstallation(installation, tokenResp)
	srht := createSrhtClient(srhtEndpoint, oauth2Client, installation)
	user, err := buildssrht.FetchUser(srht.GQL, ctx)
	if err != nil {


@@ 58,3 56,31 @@ func saveSrhtToken(ctx context.Context, db *DB, srhtEndpoint string, oauth2Clien
	log.Printf("user %v has completed installation %v", user.CanonicalName, installation.ID)
	return nil
}

func refreshSrhtToken(ctx context.Context, db *DB, oauth2Client *oauth2.Client, installation *Installation) error {
	if installation.SrhtRefreshToken == "" || installation.SrhtTokenExpiresAt.IsZero() {
		return nil
	}
	if time.Until(installation.SrhtTokenExpiresAt) > 15*24*time.Hour {
		return nil
	}

	tokenResp, err := oauth2Client.Refresh(ctx, installation.SrhtRefreshToken, nil)
	if err != nil {
		return err
	}

	populateSrhtInstallation(installation, tokenResp)
	if err := db.StoreInstallation(installation); err != nil {
		return fmt.Errorf("failed to store installation: %v", err)
	}

	log.Printf("refreshed sr.ht token for installation %v", installation.ID)
	return nil
}

func populateSrhtInstallation(installation *Installation, tokenResp *oauth2.TokenResp) {
	installation.SrhtToken = tokenResp.AccessToken
	installation.SrhtRefreshToken = tokenResp.RefreshToken
	installation.SrhtTokenExpiresAt = time.Now().Add(tokenResp.ExpiresIn)
}