feat: extend equipment and workout models with service tracking

This commit is contained in:
Blake Ridgway
2026-02-12 10:09:50 -06:00
parent eb9ac1b67a
commit 178ffb3425
37 changed files with 4005 additions and 40 deletions

View File

@@ -0,0 +1,140 @@
package integration
import (
"bytes"
"fmt"
"io"
"net/http"
"net/url"
"rideaware/internal/config"
"rideaware/internal/export"
"rideaware/internal/user"
"rideaware/internal/workout"
)
type GarminClient struct {
oauthService *OAuthService
workoutRepo *workout.Repository
userRepo *user.Repository
}
func NewGarminClient() *GarminClient {
return &GarminClient{
oauthService: NewOAuthService(),
workoutRepo: workout.NewRepository(),
userRepo: user.NewRepository(),
}
}
// BuildAuthURL constructs the Garmin OAuth2 PKCE authorization URL.
func (c *GarminClient) BuildAuthURL(userID uint) (string, error) {
cfg := config.OAuth.Garmin
if cfg.ClientID == "" {
return "", fmt.Errorf("Garmin OAuth is not configured")
}
stateToken, _, codeChallenge, err := c.oauthService.GenerateStateWithPKCE(userID, "garmin")
if err != nil {
return "", err
}
params := url.Values{
"client_id": {cfg.ClientID},
"response_type": {"code"},
"redirect_uri": {cfg.RedirectURI},
"scope": {"TRAINING_API"},
"state": {stateToken},
"code_challenge": {codeChallenge},
"code_challenge_method": {"S256"},
}
return cfg.AuthURL + "?" + params.Encode(), nil
}
// HandleCallback exchanges the authorization code for tokens and stores them.
func (c *GarminClient) HandleCallback(code, stateToken string) (uint, error) {
state, err := c.oauthService.ValidateState(stateToken)
if err != nil {
return 0, err
}
if state.Provider != "garmin" {
return 0, fmt.Errorf("invalid state provider: expected garmin, got %s", state.Provider)
}
cfg := config.OAuth.Garmin
params := url.Values{
"grant_type": {"authorization_code"},
"code": {code},
"redirect_uri": {cfg.RedirectURI},
"client_id": {cfg.ClientID},
"code_verifier": {state.CodeVerifier},
}
tokenResp, err := c.oauthService.ExchangeCode(cfg.TokenURL, params)
if err != nil {
return 0, fmt.Errorf("Garmin token exchange failed: %w", err)
}
if err := c.oauthService.SaveConnection(state.UserID, "garmin", tokenResp); err != nil {
return 0, err
}
return state.UserID, nil
}
// PushWorkout sends a structured workout to Garmin Connect via the Training API.
// If the Training API is not yet available, returns an error with instructions to use FIT export.
func (c *GarminClient) PushWorkout(workoutID, userID uint) error {
accessToken, err := c.oauthService.GetValidToken(userID, "garmin")
if err != nil {
return err
}
w, err := c.workoutRepo.GetWorkoutByID(workoutID, userID)
if err != nil {
return fmt.Errorf("workout not found: %w", err)
}
u, err := c.userRepo.GetUserByID(userID)
if err != nil {
return fmt.Errorf("user not found: %w", err)
}
ftp := 0
if u.Profile != nil {
ftp = u.Profile.FTP
}
if ftp <= 0 {
return fmt.Errorf("FTP must be set in your profile before pushing workouts")
}
fitData, err := export.EncodeFITWorkout(w, ftp)
if err != nil {
return fmt.Errorf("failed to generate FIT workout: %w", err)
}
// Push FIT file to Garmin Training API
apiURL := "https://apis.garmin.com/training-api/workout"
req, err := http.NewRequest("POST", apiURL, bytes.NewReader(fitData))
if err != nil {
return err
}
req.Header.Set("Authorization", "Bearer "+accessToken)
req.Header.Set("Content-Type", "application/octet-stream")
resp, err := http.DefaultClient.Do(req)
if err != nil {
return fmt.Errorf("failed to push workout to Garmin: %w", err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK && resp.StatusCode != http.StatusCreated {
body, _ := io.ReadAll(resp.Body)
return fmt.Errorf("Garmin API returned status %d: %s", resp.StatusCode, string(body))
}
return nil
}

View File

@@ -0,0 +1,158 @@
package integration
import (
"encoding/json"
"log"
"net/http"
"strconv"
"rideaware/internal/config"
"rideaware/internal/middleware"
)
type GarminHandler struct {
client *GarminClient
oauthService *OAuthService
}
func NewGarminHandler() *GarminHandler {
return &GarminHandler{
client: NewGarminClient(),
oauthService: NewOAuthService(),
}
}
// StartAuth GET /api/protected/garmin/auth - initiates Garmin OAuth2 PKCE flow
func (h *GarminHandler) StartAuth(w http.ResponseWriter, r *http.Request) {
claims := r.Context().Value(middleware.UserContextKey).(*config.CustomClaims)
if claims == nil {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusUnauthorized)
json.NewEncoder(w).Encode(map[string]string{"error": "unauthorized"})
return
}
authURL, err := h.client.BuildAuthURL(claims.UserID)
if err != nil {
log.Printf("Garmin auth error: %v", err)
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusBadRequest)
json.NewEncoder(w).Encode(map[string]string{"error": err.Error()})
return
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
json.NewEncoder(w).Encode(map[string]string{"auth_url": authURL})
}
// Callback GET /api/garmin/callback - handles Garmin OAuth callback (public endpoint)
func (h *GarminHandler) Callback(w http.ResponseWriter, r *http.Request) {
code := r.URL.Query().Get("code")
state := r.URL.Query().Get("state")
if code == "" || state == "" {
errMsg := r.URL.Query().Get("error")
if errMsg == "" {
errMsg = "missing code or state parameter"
}
appURL := config.OAuth.AppURL
http.Redirect(w, r, appURL+"/settings?garmin=error&message="+errMsg, http.StatusFound)
return
}
_, err := h.client.HandleCallback(code, state)
if err != nil {
log.Printf("Garmin callback error: %v", err)
appURL := config.OAuth.AppURL
http.Redirect(w, r, appURL+"/settings?garmin=error&message=auth_failed", http.StatusFound)
return
}
appURL := config.OAuth.AppURL
http.Redirect(w, r, appURL+"/settings?garmin=connected", http.StatusFound)
}
// PushWorkout POST /api/protected/workouts/push/garmin?id=X - pushes workout to Garmin Connect
func (h *GarminHandler) PushWorkout(w http.ResponseWriter, r *http.Request) {
claims := r.Context().Value(middleware.UserContextKey).(*config.CustomClaims)
if claims == nil {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusUnauthorized)
json.NewEncoder(w).Encode(map[string]string{"error": "unauthorized"})
return
}
idStr := r.URL.Query().Get("id")
if idStr == "" {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusBadRequest)
json.NewEncoder(w).Encode(map[string]string{"error": "workout id is required"})
return
}
id, err := strconv.ParseUint(idStr, 10, 64)
if err != nil {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusBadRequest)
json.NewEncoder(w).Encode(map[string]string{"error": "invalid workout id"})
return
}
if err := h.client.PushWorkout(uint(id), claims.UserID); err != nil {
log.Printf("Garmin push error: %v", err)
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusBadRequest)
json.NewEncoder(w).Encode(map[string]string{"error": err.Error()})
return
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
json.NewEncoder(w).Encode(map[string]string{"message": "workout pushed to Garmin Connect"})
}
// ConnectionStatus GET /api/protected/garmin/status - check Garmin connection status
func (h *GarminHandler) ConnectionStatus(w http.ResponseWriter, r *http.Request) {
claims := r.Context().Value(middleware.UserContextKey).(*config.CustomClaims)
if claims == nil {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusUnauthorized)
json.NewEncoder(w).Encode(map[string]string{"error": "unauthorized"})
return
}
status, err := h.oauthService.GetConnectionStatus(claims.UserID, "garmin")
if err != nil {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusInternalServerError)
json.NewEncoder(w).Encode(map[string]string{"error": err.Error()})
return
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
json.NewEncoder(w).Encode(status)
}
// Disconnect DELETE /api/protected/garmin/disconnect - revoke Garmin connection
func (h *GarminHandler) Disconnect(w http.ResponseWriter, r *http.Request) {
claims := r.Context().Value(middleware.UserContextKey).(*config.CustomClaims)
if claims == nil {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusUnauthorized)
json.NewEncoder(w).Encode(map[string]string{"error": "unauthorized"})
return
}
if err := h.oauthService.Disconnect(claims.UserID, "garmin"); err != nil {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusInternalServerError)
json.NewEncoder(w).Encode(map[string]string{"error": err.Error()})
return
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
json.NewEncoder(w).Encode(map[string]string{"message": "Garmin disconnected"})
}

View File

@@ -0,0 +1,35 @@
package integration
import "time"
type OAuthConnection struct {
ID uint `gorm:"primaryKey" json:"id"`
UserID uint `gorm:"not null;uniqueIndex:idx_user_provider" json:"user_id"`
Provider string `gorm:"not null;uniqueIndex:idx_user_provider" json:"provider"` // "garmin", "wahoo"
AccessToken string `gorm:"not null" json:"-"`
RefreshToken string `gorm:"default:''" json:"-"`
TokenExpiresAt time.Time `json:"token_expires_at"`
ProviderUserID string `gorm:"default:''" json:"provider_user_id"`
Scopes string `gorm:"default:''" json:"scopes"`
Status string `gorm:"default:'active'" json:"status"` // "active", "revoked", "expired"
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
}
func (OAuthConnection) TableName() string {
return "oauth_connections"
}
type OAuthState struct {
ID uint `gorm:"primaryKey"`
State string `gorm:"uniqueIndex;not null"`
UserID uint `gorm:"not null"`
Provider string `gorm:"not null"` // "garmin", "wahoo"
CodeVerifier string `gorm:"default:''"` // for PKCE (Garmin)
ExpiresAt time.Time `gorm:"not null"`
CreatedAt time.Time
}
func (OAuthState) TableName() string {
return "oauth_states"
}

View File

@@ -0,0 +1,325 @@
package integration
import (
"crypto/aes"
"crypto/cipher"
"crypto/rand"
"crypto/sha256"
"encoding/base64"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"net/url"
"strings"
"time"
"rideaware/internal/config"
)
type OAuthService struct {
repo *Repository
}
func NewOAuthService() *OAuthService {
return &OAuthService{
repo: NewRepository(),
}
}
// GenerateState creates a cryptographically random state token for OAuth CSRF protection.
func (s *OAuthService) GenerateState(userID uint, provider string) (string, error) {
b := make([]byte, 32)
if _, err := rand.Read(b); err != nil {
return "", fmt.Errorf("failed to generate state: %w", err)
}
stateToken := base64.URLEncoding.EncodeToString(b)
state := &OAuthState{
State: stateToken,
UserID: userID,
Provider: provider,
ExpiresAt: time.Now().Add(10 * time.Minute),
}
if err := s.repo.CreateState(state); err != nil {
return "", err
}
return stateToken, nil
}
// GenerateStateWithPKCE creates a state token and PKCE code verifier/challenge for Garmin OAuth.
func (s *OAuthService) GenerateStateWithPKCE(userID uint, provider string) (stateToken, codeVerifier, codeChallenge string, err error) {
b := make([]byte, 32)
if _, err := rand.Read(b); err != nil {
return "", "", "", fmt.Errorf("failed to generate state: %w", err)
}
stateToken = base64.URLEncoding.EncodeToString(b)
// Generate code verifier (43-128 chars, base64url-safe)
verifierBytes := make([]byte, 32)
if _, err := rand.Read(verifierBytes); err != nil {
return "", "", "", fmt.Errorf("failed to generate code verifier: %w", err)
}
codeVerifier = base64.RawURLEncoding.EncodeToString(verifierBytes)
// code_challenge = base64url(SHA256(code_verifier))
h := sha256.Sum256([]byte(codeVerifier))
codeChallenge = base64.RawURLEncoding.EncodeToString(h[:])
state := &OAuthState{
State: stateToken,
UserID: userID,
Provider: provider,
CodeVerifier: codeVerifier,
ExpiresAt: time.Now().Add(10 * time.Minute),
}
if err := s.repo.CreateState(state); err != nil {
return "", "", "", err
}
return stateToken, codeVerifier, codeChallenge, nil
}
// ValidateState validates and consumes an OAuth state token.
func (s *OAuthService) ValidateState(stateToken string) (*OAuthState, error) {
return s.repo.GetAndDeleteState(stateToken)
}
// TokenResponse is the standard OAuth2 token response.
type TokenResponse struct {
AccessToken string `json:"access_token"`
RefreshToken string `json:"refresh_token"`
TokenType string `json:"token_type"`
ExpiresIn int `json:"expires_in"`
Scope string `json:"scope"`
}
// ExchangeCode exchanges an authorization code for tokens.
func (s *OAuthService) ExchangeCode(tokenURL string, params url.Values) (*TokenResponse, error) {
resp, err := http.Post(tokenURL, "application/x-www-form-urlencoded", strings.NewReader(params.Encode()))
if err != nil {
return nil, fmt.Errorf("token exchange request failed: %w", err)
}
defer resp.Body.Close()
body, err := io.ReadAll(resp.Body)
if err != nil {
return nil, fmt.Errorf("failed to read token response: %w", err)
}
if resp.StatusCode != http.StatusOK {
return nil, fmt.Errorf("token exchange failed (status %d): %s", resp.StatusCode, string(body))
}
var tokenResp TokenResponse
if err := json.Unmarshal(body, &tokenResp); err != nil {
return nil, fmt.Errorf("failed to parse token response: %w", err)
}
return &tokenResp, nil
}
// RefreshAccessToken refreshes an expired access token.
func (s *OAuthService) RefreshAccessToken(tokenURL, clientID, clientSecret, refreshToken string) (*TokenResponse, error) {
params := url.Values{
"grant_type": {"refresh_token"},
"refresh_token": {refreshToken},
"client_id": {clientID},
"client_secret": {clientSecret},
}
return s.ExchangeCode(tokenURL, params)
}
// SaveConnection encrypts tokens and stores the OAuth connection.
func (s *OAuthService) SaveConnection(userID uint, provider string, tokenResp *TokenResponse) error {
encAccess, err := Encrypt(tokenResp.AccessToken, config.OAuth.EncryptionKey)
if err != nil {
return fmt.Errorf("failed to encrypt access token: %w", err)
}
encRefresh := ""
if tokenResp.RefreshToken != "" {
encRefresh, err = Encrypt(tokenResp.RefreshToken, config.OAuth.EncryptionKey)
if err != nil {
return fmt.Errorf("failed to encrypt refresh token: %w", err)
}
}
expiresAt := time.Now().Add(time.Duration(tokenResp.ExpiresIn) * time.Second)
conn := &OAuthConnection{
UserID: userID,
Provider: provider,
AccessToken: encAccess,
RefreshToken: encRefresh,
TokenExpiresAt: expiresAt,
Scopes: tokenResp.Scope,
Status: "active",
}
return s.repo.UpsertConnection(conn)
}
// GetValidToken retrieves a connection and ensures the token is valid (refreshing if needed).
func (s *OAuthService) GetValidToken(userID uint, provider string) (string, error) {
conn, err := s.repo.GetConnection(userID, provider)
if err != nil {
return "", err
}
if conn.Status != "active" {
return "", fmt.Errorf("%s connection is %s, please reconnect", provider, conn.Status)
}
accessToken, err := Decrypt(conn.AccessToken, config.OAuth.EncryptionKey)
if err != nil {
return "", fmt.Errorf("failed to decrypt access token: %w", err)
}
// Token still valid (with 30s buffer)
if time.Now().Before(conn.TokenExpiresAt.Add(-30 * time.Second)) {
return accessToken, nil
}
// Token expired - try refresh
if conn.RefreshToken == "" {
conn.Status = "expired"
s.repo.UpdateConnection(conn)
return "", fmt.Errorf("%s token expired and no refresh token available, please reconnect", provider)
}
refreshToken, err := Decrypt(conn.RefreshToken, config.OAuth.EncryptionKey)
if err != nil {
return "", fmt.Errorf("failed to decrypt refresh token: %w", err)
}
var providerConfig config.OAuthProviderConfig
switch provider {
case "garmin":
providerConfig = config.OAuth.Garmin
case "wahoo":
providerConfig = config.OAuth.Wahoo
default:
return "", errors.New("unknown provider")
}
tokenResp, err := s.RefreshAccessToken(providerConfig.TokenURL, providerConfig.ClientID, providerConfig.ClientSecret, refreshToken)
if err != nil {
conn.Status = "expired"
s.repo.UpdateConnection(conn)
return "", fmt.Errorf("%s token refresh failed, please reconnect: %w", provider, err)
}
// Save new tokens
if err := s.SaveConnection(userID, provider, tokenResp); err != nil {
return "", fmt.Errorf("failed to save refreshed tokens: %w", err)
}
return tokenResp.AccessToken, nil
}
// GetConnectionStatus returns the connection status for a user+provider.
func (s *OAuthService) GetConnectionStatus(userID uint, provider string) (map[string]interface{}, error) {
conn, err := s.repo.GetConnection(userID, provider)
if err != nil {
return map[string]interface{}{
"connected": false,
"provider": provider,
}, nil
}
return map[string]interface{}{
"connected": conn.Status == "active",
"provider": conn.Provider,
"status": conn.Status,
"token_expires_at": conn.TokenExpiresAt,
"connected_at": conn.CreatedAt,
}, nil
}
// Disconnect removes an OAuth connection.
func (s *OAuthService) Disconnect(userID uint, provider string) error {
return s.repo.DeleteConnection(userID, provider)
}
// Encrypt encrypts plaintext using AES-256-GCM with the given hex-encoded key.
func Encrypt(plaintext, hexKey string) (string, error) {
if hexKey == "" {
// No encryption key configured - store as base64 (development mode)
return base64.StdEncoding.EncodeToString([]byte(plaintext)), nil
}
key, err := hex.DecodeString(hexKey)
if err != nil {
return "", fmt.Errorf("invalid encryption key: %w", err)
}
block, err := aes.NewCipher(key)
if err != nil {
return "", err
}
gcm, err := cipher.NewGCM(block)
if err != nil {
return "", err
}
nonce := make([]byte, gcm.NonceSize())
if _, err := rand.Read(nonce); err != nil {
return "", err
}
ciphertext := gcm.Seal(nonce, nonce, []byte(plaintext), nil)
return base64.StdEncoding.EncodeToString(ciphertext), nil
}
// Decrypt decrypts ciphertext that was encrypted with Encrypt.
func Decrypt(encoded, hexKey string) (string, error) {
if hexKey == "" {
// No encryption key - stored as plain base64
decoded, err := base64.StdEncoding.DecodeString(encoded)
if err != nil {
return "", err
}
return string(decoded), nil
}
key, err := hex.DecodeString(hexKey)
if err != nil {
return "", fmt.Errorf("invalid encryption key: %w", err)
}
ciphertext, err := base64.StdEncoding.DecodeString(encoded)
if err != nil {
return "", err
}
block, err := aes.NewCipher(key)
if err != nil {
return "", err
}
gcm, err := cipher.NewGCM(block)
if err != nil {
return "", err
}
nonceSize := gcm.NonceSize()
if len(ciphertext) < nonceSize {
return "", errors.New("ciphertext too short")
}
nonce, ciphertext := ciphertext[:nonceSize], ciphertext[nonceSize:]
plaintext, err := gcm.Open(nil, nonce, ciphertext, nil)
if err != nil {
return "", err
}
return string(plaintext), nil
}

View File

@@ -0,0 +1,93 @@
package integration
import (
"errors"
"rideaware/pkg/database"
"time"
"gorm.io/gorm"
)
type Repository struct{}
func NewRepository() *Repository {
return &Repository{}
}
// UpsertConnection creates or updates an OAuth connection for a user+provider pair.
func (r *Repository) UpsertConnection(conn *OAuthConnection) error {
var existing OAuthConnection
err := database.DB.Where("user_id = ? AND provider = ?", conn.UserID, conn.Provider).
First(&existing).Error
if err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
return database.DB.Create(conn).Error
}
return err
}
existing.AccessToken = conn.AccessToken
existing.RefreshToken = conn.RefreshToken
existing.TokenExpiresAt = conn.TokenExpiresAt
existing.ProviderUserID = conn.ProviderUserID
existing.Scopes = conn.Scopes
existing.Status = "active"
conn.ID = existing.ID
return database.DB.Save(&existing).Error
}
// GetConnection retrieves an active OAuth connection for a user+provider pair.
func (r *Repository) GetConnection(userID uint, provider string) (*OAuthConnection, error) {
var conn OAuthConnection
if err := database.DB.Where("user_id = ? AND provider = ?", userID, provider).
First(&conn).Error; err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
return nil, errors.New("no " + provider + " connection found")
}
return nil, err
}
return &conn, nil
}
// UpdateConnection updates an existing OAuth connection.
func (r *Repository) UpdateConnection(conn *OAuthConnection) error {
return database.DB.Save(conn).Error
}
// DeleteConnection removes an OAuth connection.
func (r *Repository) DeleteConnection(userID uint, provider string) error {
return database.DB.Where("user_id = ? AND provider = ?", userID, provider).
Delete(&OAuthConnection{}).Error
}
// CreateState stores an OAuth state token for CSRF protection.
func (r *Repository) CreateState(state *OAuthState) error {
return database.DB.Create(state).Error
}
// GetAndDeleteState retrieves and deletes an OAuth state token. Returns error if expired or not found.
func (r *Repository) GetAndDeleteState(stateToken string) (*OAuthState, error) {
var state OAuthState
if err := database.DB.Where("state = ?", stateToken).First(&state).Error; err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
return nil, errors.New("invalid or expired state token")
}
return nil, err
}
// Delete the state immediately (single-use)
database.DB.Delete(&state)
if time.Now().After(state.ExpiresAt) {
return nil, errors.New("state token has expired")
}
return &state, nil
}
// CleanupExpiredStates removes expired OAuth state tokens.
func (r *Repository) CleanupExpiredStates() error {
return database.DB.Where("expires_at < ?", time.Now()).Delete(&OAuthState{}).Error
}

View File

@@ -0,0 +1,336 @@
package integration
import (
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
"net/url"
"rideaware/internal/config"
"rideaware/internal/user"
"rideaware/internal/workout"
)
type WahooClient struct {
oauthService *OAuthService
workoutRepo *workout.Repository
userRepo *user.Repository
}
func NewWahooClient() *WahooClient {
return &WahooClient{
oauthService: NewOAuthService(),
workoutRepo: workout.NewRepository(),
userRepo: user.NewRepository(),
}
}
// BuildAuthURL constructs the Wahoo OAuth2 authorization URL.
func (c *WahooClient) BuildAuthURL(userID uint) (string, error) {
cfg := config.OAuth.Wahoo
if cfg.ClientID == "" {
return "", fmt.Errorf("Wahoo OAuth is not configured")
}
stateToken, err := c.oauthService.GenerateState(userID, "wahoo")
if err != nil {
return "", err
}
params := url.Values{
"client_id": {cfg.ClientID},
"response_type": {"code"},
"redirect_uri": {cfg.RedirectURI},
"scope": {"workouts_write plans_write user_read offline_data"},
"state": {stateToken},
}
return cfg.AuthURL + "?" + params.Encode(), nil
}
// HandleCallback exchanges the authorization code for tokens and stores them.
func (c *WahooClient) HandleCallback(code, stateToken string) (uint, error) {
state, err := c.oauthService.ValidateState(stateToken)
if err != nil {
return 0, err
}
if state.Provider != "wahoo" {
return 0, fmt.Errorf("invalid state provider: expected wahoo, got %s", state.Provider)
}
cfg := config.OAuth.Wahoo
params := url.Values{
"grant_type": {"authorization_code"},
"code": {code},
"redirect_uri": {cfg.RedirectURI},
"client_id": {cfg.ClientID},
"client_secret": {cfg.ClientSecret},
}
tokenResp, err := c.oauthService.ExchangeCode(cfg.TokenURL, params)
if err != nil {
return 0, fmt.Errorf("Wahoo token exchange failed: %w", err)
}
if err := c.oauthService.SaveConnection(state.UserID, "wahoo", tokenResp); err != nil {
return 0, err
}
return state.UserID, nil
}
// Wahoo plan JSON structures
type wahooPlanHeader struct {
Version string `json:"version"`
Name string `json:"name"`
Description string `json:"description"`
WorkoutTypeFamily string `json:"workout_type_family"`
WorkoutTypeLocation string `json:"workout_type_location"`
FTP int `json:"ftp"`
TotalDuration int `json:"total_duration"`
}
type wahooPlanTarget struct {
Type string `json:"type"`
Low float64 `json:"low"`
High float64 `json:"high"`
}
type wahooPlanInterval struct {
Name string `json:"name"`
Duration int `json:"duration"`
IntensityType string `json:"intensity_type"`
Targets []wahooPlanTarget `json:"targets"`
}
type wahooPlan struct {
Header wahooPlanHeader `json:"header"`
Intervals []wahooPlanInterval `json:"intervals"`
}
// PushWorkout sends a structured workout to Wahoo as a plan.
func (c *WahooClient) PushWorkout(workoutID, userID uint) error {
accessToken, err := c.oauthService.GetValidToken(userID, "wahoo")
if err != nil {
return err
}
w, err := c.workoutRepo.GetWorkoutByID(workoutID, userID)
if err != nil {
return fmt.Errorf("workout not found: %w", err)
}
u, err := c.userRepo.GetUserByID(userID)
if err != nil {
return fmt.Errorf("user not found: %w", err)
}
ftp := 0
if u.Profile != nil {
ftp = u.Profile.FTP
}
plan := buildWahooPlan(w, ftp)
planJSON, err := json.Marshal(plan)
if err != nil {
return fmt.Errorf("failed to build Wahoo plan: %w", err)
}
// Step 1: Create plan via Wahoo API
planID, err := c.createWahooPlan(accessToken, planJSON, w.Title)
if err != nil {
return err
}
// Step 2: Create workout referencing the plan
if err := c.createWahooWorkout(accessToken, planID, w); err != nil {
return err
}
return nil
}
func buildWahooPlan(w *workout.Workout, ftp int) wahooPlan {
name := w.WorkoutData.Name
if name == "" {
name = w.Title
}
plan := wahooPlan{
Header: wahooPlanHeader{
Version: "1.0",
Name: name,
Description: w.Description,
WorkoutTypeFamily: "CYCLING",
WorkoutTypeLocation: "INDOOR",
FTP: ftp,
TotalDuration: w.WorkoutData.TotalDuration,
},
}
for _, seg := range w.WorkoutData.Segments {
interval := segmentToWahooInterval(seg)
plan.Intervals = append(plan.Intervals, interval)
}
return plan
}
func segmentToWahooInterval(seg workout.WorkoutSegment) wahooPlanInterval {
interval := wahooPlanInterval{
Duration: seg.Duration,
}
switch seg.Type {
case "warmup":
interval.Name = "Warm Up"
interval.IntensityType = "WARMUP"
if seg.PowerLow != 0 || seg.PowerHigh != 0 {
interval.Targets = []wahooPlanTarget{{
Type: "POWER_ZONE",
Low: seg.PowerLow,
High: seg.PowerHigh,
}}
}
case "steadystate":
interval.Name = "Steady State"
interval.IntensityType = "ACTIVE"
if seg.Power != 0 {
interval.Targets = []wahooPlanTarget{{
Type: "POWER_ZONE",
Low: seg.Power,
High: seg.Power,
}}
}
case "interval":
interval.Name = "Interval"
interval.IntensityType = "ACTIVE"
if seg.PowerLow != 0 || seg.PowerHigh != 0 {
interval.Targets = []wahooPlanTarget{{
Type: "POWER_ZONE",
Low: seg.PowerLow,
High: seg.PowerHigh,
}}
}
case "cooldown":
interval.Name = "Cool Down"
interval.IntensityType = "COOLDOWN"
if seg.PowerLow != 0 || seg.PowerHigh != 0 {
interval.Targets = []wahooPlanTarget{{
Type: "POWER_ZONE",
Low: seg.PowerLow,
High: seg.PowerHigh,
}}
}
case "ramp":
interval.Name = "Ramp"
interval.IntensityType = "ACTIVE"
if seg.PowerLow != 0 || seg.PowerHigh != 0 {
interval.Targets = []wahooPlanTarget{{
Type: "POWER_ZONE",
Low: seg.PowerLow,
High: seg.PowerHigh,
}}
}
case "freeride":
interval.Name = "Free Ride"
interval.IntensityType = "REST"
default:
interval.Name = seg.Type
interval.IntensityType = "ACTIVE"
}
return interval
}
func (c *WahooClient) createWahooPlan(accessToken string, planJSON []byte, title string) (string, error) {
apiURL := "https://api.wahooligan.com/v1/plans"
body := map[string]interface{}{
"plan": map[string]interface{}{
"name": title,
"file": planJSON,
},
}
jsonBody, err := json.Marshal(body)
if err != nil {
return "", err
}
req, err := http.NewRequest("POST", apiURL, bytes.NewReader(jsonBody))
if err != nil {
return "", err
}
req.Header.Set("Authorization", "Bearer "+accessToken)
req.Header.Set("Content-Type", "application/json")
resp, err := http.DefaultClient.Do(req)
if err != nil {
return "", fmt.Errorf("failed to create Wahoo plan: %w", err)
}
defer resp.Body.Close()
respBody, err := io.ReadAll(resp.Body)
if err != nil {
return "", err
}
if resp.StatusCode != http.StatusOK && resp.StatusCode != http.StatusCreated {
return "", fmt.Errorf("Wahoo API returned status %d: %s", resp.StatusCode, string(respBody))
}
var result struct {
ID string `json:"id"`
}
if err := json.Unmarshal(respBody, &result); err != nil {
return "", fmt.Errorf("failed to parse Wahoo plan response: %w", err)
}
return result.ID, nil
}
func (c *WahooClient) createWahooWorkout(accessToken, planID string, w *workout.Workout) error {
apiURL := "https://api.wahooligan.com/v1/workouts"
body := map[string]interface{}{
"workout": map[string]interface{}{
"name": w.Title,
"plan_id": planID,
"workout_type": 0, // cycling
"scheduled_date": w.ScheduledDate.Format("2006-01-02"),
},
}
jsonBody, err := json.Marshal(body)
if err != nil {
return err
}
req, err := http.NewRequest("POST", apiURL, bytes.NewReader(jsonBody))
if err != nil {
return err
}
req.Header.Set("Authorization", "Bearer "+accessToken)
req.Header.Set("Content-Type", "application/json")
resp, err := http.DefaultClient.Do(req)
if err != nil {
return fmt.Errorf("failed to create Wahoo workout: %w", err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK && resp.StatusCode != http.StatusCreated {
respBody, _ := io.ReadAll(resp.Body)
return fmt.Errorf("Wahoo API returned status %d: %s", resp.StatusCode, string(respBody))
}
return nil
}

View File

@@ -0,0 +1,158 @@
package integration
import (
"encoding/json"
"log"
"net/http"
"strconv"
"rideaware/internal/config"
"rideaware/internal/middleware"
)
type WahooHandler struct {
client *WahooClient
oauthService *OAuthService
}
func NewWahooHandler() *WahooHandler {
return &WahooHandler{
client: NewWahooClient(),
oauthService: NewOAuthService(),
}
}
// StartAuth GET /api/protected/wahoo/auth - initiates Wahoo OAuth2 flow
func (h *WahooHandler) StartAuth(w http.ResponseWriter, r *http.Request) {
claims := r.Context().Value(middleware.UserContextKey).(*config.CustomClaims)
if claims == nil {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusUnauthorized)
json.NewEncoder(w).Encode(map[string]string{"error": "unauthorized"})
return
}
authURL, err := h.client.BuildAuthURL(claims.UserID)
if err != nil {
log.Printf("Wahoo auth error: %v", err)
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusBadRequest)
json.NewEncoder(w).Encode(map[string]string{"error": err.Error()})
return
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
json.NewEncoder(w).Encode(map[string]string{"auth_url": authURL})
}
// Callback GET /api/wahoo/callback - handles Wahoo OAuth callback (public endpoint)
func (h *WahooHandler) Callback(w http.ResponseWriter, r *http.Request) {
code := r.URL.Query().Get("code")
state := r.URL.Query().Get("state")
if code == "" || state == "" {
errMsg := r.URL.Query().Get("error")
if errMsg == "" {
errMsg = "missing code or state parameter"
}
appURL := config.OAuth.AppURL
http.Redirect(w, r, appURL+"/settings?wahoo=error&message="+errMsg, http.StatusFound)
return
}
_, err := h.client.HandleCallback(code, state)
if err != nil {
log.Printf("Wahoo callback error: %v", err)
appURL := config.OAuth.AppURL
http.Redirect(w, r, appURL+"/settings?wahoo=error&message=auth_failed", http.StatusFound)
return
}
appURL := config.OAuth.AppURL
http.Redirect(w, r, appURL+"/settings?wahoo=connected", http.StatusFound)
}
// PushWorkout POST /api/protected/workouts/push/wahoo?id=X - pushes workout to Wahoo
func (h *WahooHandler) PushWorkout(w http.ResponseWriter, r *http.Request) {
claims := r.Context().Value(middleware.UserContextKey).(*config.CustomClaims)
if claims == nil {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusUnauthorized)
json.NewEncoder(w).Encode(map[string]string{"error": "unauthorized"})
return
}
idStr := r.URL.Query().Get("id")
if idStr == "" {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusBadRequest)
json.NewEncoder(w).Encode(map[string]string{"error": "workout id is required"})
return
}
id, err := strconv.ParseUint(idStr, 10, 64)
if err != nil {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusBadRequest)
json.NewEncoder(w).Encode(map[string]string{"error": "invalid workout id"})
return
}
if err := h.client.PushWorkout(uint(id), claims.UserID); err != nil {
log.Printf("Wahoo push error: %v", err)
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusBadRequest)
json.NewEncoder(w).Encode(map[string]string{"error": err.Error()})
return
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
json.NewEncoder(w).Encode(map[string]string{"message": "workout pushed to Wahoo"})
}
// ConnectionStatus GET /api/protected/wahoo/status - check Wahoo connection status
func (h *WahooHandler) ConnectionStatus(w http.ResponseWriter, r *http.Request) {
claims := r.Context().Value(middleware.UserContextKey).(*config.CustomClaims)
if claims == nil {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusUnauthorized)
json.NewEncoder(w).Encode(map[string]string{"error": "unauthorized"})
return
}
status, err := h.oauthService.GetConnectionStatus(claims.UserID, "wahoo")
if err != nil {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusInternalServerError)
json.NewEncoder(w).Encode(map[string]string{"error": err.Error()})
return
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
json.NewEncoder(w).Encode(status)
}
// Disconnect DELETE /api/protected/wahoo/disconnect - revoke Wahoo connection
func (h *WahooHandler) Disconnect(w http.ResponseWriter, r *http.Request) {
claims := r.Context().Value(middleware.UserContextKey).(*config.CustomClaims)
if claims == nil {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusUnauthorized)
json.NewEncoder(w).Encode(map[string]string{"error": "unauthorized"})
return
}
if err := h.oauthService.Disconnect(claims.UserID, "wahoo"); err != nil {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusInternalServerError)
json.NewEncoder(w).Encode(map[string]string{"error": err.Error()})
return
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
json.NewEncoder(w).Encode(map[string]string{"message": "Wahoo disconnected"})
}