84 lines
2.3 KiB
Go
84 lines
2.3 KiB
Go
package fbhttp
|
|
|
|
import (
|
|
"bytes"
|
|
"context"
|
|
"encoding/base64"
|
|
"image"
|
|
_ "image/jpeg"
|
|
"image/png"
|
|
"io"
|
|
"net/http"
|
|
"net/url"
|
|
"path"
|
|
"strings"
|
|
"time"
|
|
|
|
"golang.org/x/image/draw"
|
|
_ "golang.org/x/image/webp"
|
|
)
|
|
|
|
// Fetch only public avatar images on the configured identity provider, without
|
|
// credentials or redirects. Keep a small raster thumbnail in the local session.
|
|
func (s *SSO) loadAvatar(ctx context.Context, picture string) string {
|
|
if picture == "" {
|
|
return ""
|
|
}
|
|
issuer, err := url.Parse(s.issuer)
|
|
if err != nil {
|
|
return ""
|
|
}
|
|
target, err := url.Parse(picture)
|
|
if err != nil {
|
|
return ""
|
|
}
|
|
target = issuer.ResolveReference(target)
|
|
prefix := strings.TrimRight(issuer.Path, "/") + "/avatars/"
|
|
if target.Scheme != issuer.Scheme || !strings.EqualFold(target.Host, issuer.Host) || target.User != nil || target.Fragment != "" || !strings.HasPrefix(path.Clean(target.Path), prefix) {
|
|
return ""
|
|
}
|
|
client := &http.Client{Timeout: 3 * time.Second, CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }}
|
|
req, err := http.NewRequestWithContext(ctx, http.MethodGet, target.String(), nil)
|
|
if err != nil {
|
|
return ""
|
|
}
|
|
response, err := client.Do(req)
|
|
if err != nil {
|
|
return ""
|
|
}
|
|
defer response.Body.Close()
|
|
if response.StatusCode != http.StatusOK {
|
|
return ""
|
|
}
|
|
const limit = 256 * 1024
|
|
raw, err := io.ReadAll(io.LimitReader(response.Body, limit+1))
|
|
if err != nil || len(raw) > limit {
|
|
return ""
|
|
}
|
|
config, format, err := image.DecodeConfig(bytes.NewReader(raw))
|
|
if err != nil || (format != "png" && format != "jpeg" && format != "webp") || config.Width < 1 || config.Height < 1 || config.Width > 1024 || config.Height > 1024 {
|
|
return ""
|
|
}
|
|
original, _, err := image.Decode(bytes.NewReader(raw))
|
|
if err != nil {
|
|
return ""
|
|
}
|
|
width, height := config.Width, config.Height
|
|
if width > 128 || height > 128 {
|
|
if width >= height {
|
|
height = max(1, height*128/width)
|
|
width = 128
|
|
} else {
|
|
width = max(1, width*128/height)
|
|
height = 128
|
|
}
|
|
}
|
|
thumbnail := image.NewRGBA(image.Rect(0, 0, width, height))
|
|
draw.ApproxBiLinear.Scale(thumbnail, thumbnail.Bounds(), original, original.Bounds(), draw.Src, nil)
|
|
var output bytes.Buffer
|
|
if png.Encode(&output, thumbnail) != nil {
|
|
return ""
|
|
}
|
|
return "data:image/png;base64," + base64.StdEncoding.EncodeToString(output.Bytes())
|
|
}
|