pollo/api/webhooks/clerk.go

78 lines
1.6 KiB
Go
Raw Normal View History

2023-05-18 20:04:55 -06:00
package webhooks
import (
"encoding/json"
"io"
"net/http"
"os"
"github.com/labstack/echo/v4"
svix "github.com/svix/svix-webhooks/go"
2024-06-27 13:13:46 -06:00
"pollo/lib"
2023-05-18 20:04:55 -06:00
)
// Types
type ClerkEventEmail struct {
EmailAddress string `json:"email_address"`
}
type ClerkEventData struct {
EmailAddresses []ClerkEventEmail `json:"email_addresses,omitempty"`
Id string `json:"id"`
}
type ClerkEvent struct {
Data ClerkEventData
Type string
}
// Event Handlers
func userCreatedHandler(event ClerkEvent) {
welcomeEmail := `
2024-06-27 13:13:46 -06:00
<h1>Thank you for making an pollo account!</h1>
2023-05-18 20:04:55 -06:00
<h2>There are a number of apps this account give you access to!</h2>
<br/>
<ul>
2024-06-27 13:13:46 -06:00
<li>Pollo: https://pollo.pollo/</li>
2023-05-18 20:04:55 -06:00
</ul>
`
lib.SendEmail(event.Data.EmailAddresses[0].EmailAddress, "apps@atri.dad", "Atri's Apps", welcomeEmail, "Welcome to Atri's Apps!")
}
// Main Handler/Router
func ClerkWebhookHandler(c echo.Context) error {
secret := os.Getenv("CLERK_WEBHOOK_SECRET")
wh, err := svix.NewWebhook(secret)
if err != nil {
return c.String(http.StatusBadRequest, "Unknown Validation Error")
}
headers := c.Request().Header
payload, err := io.ReadAll(c.Request().Body)
if err != nil {
return c.String(http.StatusBadRequest, "Failed to read request body!")
}
err = wh.Verify(payload, headers)
if err != nil {
return c.String(http.StatusBadRequest, "Cannot validate webhook authenticity!")
}
var parsed ClerkEvent
err = json.Unmarshal(payload, &parsed)
if err != nil {
return c.String(http.StatusBadRequest, "Invalid Json!")
}
switch parsed.Type {
case "user.created":
userCreatedHandler(parsed)
}
return c.String(http.StatusOK, "Success!")
}