Skip to content

Instantly share code, notes, and snippets.

@maxme
Last active September 25, 2024 09:14
Show Gist options
  • Save maxme/2b6348da457aae2b330de681308e2a06 to your computer and use it in GitHub Desktop.
Save maxme/2b6348da457aae2b330de681308e2a06 to your computer and use it in GitHub Desktop.
This Pocketbase hook demonstrates how to fetch a Gravatar image for a user's email and save it to the filesystem after user creation. If the associated email has no Gravatar image, the hook will do nothing.
package main
import (
"crypto/sha256"
"encoding/hex"
"fmt"
"io"
"net/http"
"os"
"path/filepath"
"github.com/pocketbase/pocketbase"
"github.com/pocketbase/pocketbase/core"
"github.com/pocketbase/pocketbase/tools/filesystem"
)
func main() {
app := pocketbase.New()
app.OnRecordAfterCreateRequest("users").Add(func(event *core.RecordCreateEvent) error {
user := event.Record
// Generate SHA256 hash of the user's email for Gravatar URL
email := user.GetString("email")
emailHash := sha256.New()
emailHash.Write([]byte(email))
emailHashHex := hex.EncodeToString(emailHash.Sum(nil))
gravatarUrl := fmt.Sprintf("https://gravatar.com/avatar/%s?s=512&d=404", emailHashHex)
// Retrieve the image from Gravatar
resp, err := http.Get(gravatarUrl)
if err != nil {
fmt.Printf("Warning: failed to fetch gravatar for email %s: %v\n", email, err)
return nil
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
fmt.Printf("no Gravatar found for email: %s", email)
return nil
}
// Read the image data
fileData, err := io.ReadAll(resp.Body)
if err != nil {
return fmt.Errorf("failed to read gravatar image: %v", err)
}
// Define the file path
baseFilesPath := user.BaseFilesPath()
fileName := "avatar.jpg" // You can change this to dynamic file names if needed
filePath := filepath.Join(baseFilesPath, fileName)
// Save the image to the filesystem
fs, err := app.NewFilesystem()
if err != nil {
return fmt.Errorf("failed to create filesystem")
}
newFile, err := filesystem.NewFileFromBytes(fileData, fileName)
if err != nil {
return fmt.Errorf("failed to create fileFromBytes")
}
if err := fs.UploadFile(newFile, filePath); err != nil {
return fmt.Errorf("failed to upload file: %v", err)
}
// Update the user record with the avatar file name
user.Set("avatar", fileName)
// Save the updated user record
if err := app.Dao().SaveRecord(user); err != nil {
return fmt.Errorf("failed to save user record: %v", err)
}
return nil
})
if err := app.Start(); err != nil {
fmt.Println("Error starting PocketBase server:", err)
os.Exit(1)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment