feat(channels): align email oauth authorization

This commit is contained in:
2026-06-06 18:53:04 +08:00
parent 5b143b6da7
commit 7c0a67a850
9 changed files with 247 additions and 8 deletions
@@ -0,0 +1,54 @@
package v1
import (
"fmt"
"net/url"
"os"
"strings"
"time"
"github.com/golang-jwt/jwt/v5"
)
type chatwootEmailOAuthAuthorizationConfig struct {
ClientIDEnv string
ClientSecretEnv string
AuthorizeURL string
RedirectPath string
Scope string
ExtraParams map[string]string
}
func buildChatwootEmailOAuthAuthorizationURL(accountID uint, cfg chatwootEmailOAuthAuthorizationConfig) (string, error) {
clientID := strings.TrimSpace(os.Getenv(cfg.ClientIDEnv))
clientSecret := strings.TrimSpace(os.Getenv(cfg.ClientSecretEnv))
if clientID == "" || clientSecret == "" {
return "", fmt.Errorf("email OAuth is not configured")
}
state, err := signedChatwootOAuthState(accountID, clientSecret)
if err != nil {
return "", err
}
frontendURL := strings.TrimRight(envOrDefaultV1("FRONTEND_URL", "http://localhost:3000"), "/")
params := url.Values{}
params.Set("client_id", clientID)
params.Set("redirect_uri", frontendURL+cfg.RedirectPath)
params.Set("response_type", "code")
params.Set("scope", cfg.Scope)
params.Set("state", state)
for key, value := range cfg.ExtraParams {
params.Set(key, value)
}
return cfg.AuthorizeURL + "?" + params.Encode(), nil
}
func signedChatwootOAuthState(accountID uint, secret string) (string, error) {
token := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{
"sub": accountID,
"iat": time.Now().Unix(),
})
return token.SignedString([]byte(secret))
}