1package api
2
3import (
4 "crypto/hmac"
5 "crypto/sha256"
6 "encoding/hex"
7 "fmt"
8 "net/http"
9 "net/url"
10 "os"
11
12 "github.com/go-chi/chi/v5"
13)
14
15func (h *Handler) HandleAvatarProxy(w http.ResponseWriter, r *http.Request) {
16 did := chi.URLParam(r, "did")
17 if did == "" {
18 http.Error(w, "DID required", http.StatusBadRequest)
19 return
20 }
21
22 if decoded, err := url.QueryUnescape(did); err == nil {
23 did = decoded
24 }
25
26 cdnURL := os.Getenv("AVATAR_CDN_URL")
27 if cdnURL == "" {
28 cdnURL = "https://avatars.margin.at"
29 }
30
31 secret := os.Getenv("AVATAR_SHARED_SECRET")
32 if secret != "" {
33 mac := hmac.New(sha256.New, []byte(secret))
34 mac.Write([]byte(did))
35 sig := hex.EncodeToString(mac.Sum(nil))
36 http.Redirect(w, r, fmt.Sprintf("%s/%s/%s", cdnURL, sig, did), http.StatusMovedPermanently)
37 return
38 }
39
40 http.Redirect(w, r, fmt.Sprintf("%s/unsigned/%s", cdnURL, did), http.StatusMovedPermanently)
41}
42
43func getProxiedAvatarURL(did, originalURL string) string {
44 if originalURL == "" {
45 return ""
46 }
47
48 baseURL := os.Getenv("BASE_URL")
49 if baseURL == "" {
50 return originalURL
51 }
52
53 return baseURL + "/api/avatar/" + url.PathEscape(did)
54}