signature.ex 1.0 KB

12345678910111213141516171819202122232425262728293031323334353637
  1. defmodule App.Imgproxy do
  2. @prefix "https://imgproxy.mybiz.xyz"
  3. @key Base.decode16!("943b421c9eb07c830af81030552c86009268de4e532ba2ee2eab8247c6da0881", case: :lower)
  4. @salt Base.decode16!("520f986b998545b4785e0defbc4f3c1203f22de2374a3d53cb7a7fe9fea309c5", case: :lower)
  5. def build_url(img_url, opts) do
  6. path = build_path(img_url, opts)
  7. signature = gen_signature(path)
  8. Path.join([@prefix, signature, path])
  9. end
  10. defp build_path(img_url, opts) do
  11. Path.join([
  12. "/",
  13. opts.resize,
  14. to_string(opts.width),
  15. to_string(opts.height),
  16. opts.gravity,
  17. to_string(opts.enlarge),
  18. Base.url_encode64(img_url, padding: false) <> "." <> opts.extension
  19. ])
  20. end
  21. defp gen_signature(path) do
  22. :sha256
  23. |> :crypto.hmac(@key, @salt <> path)
  24. |> Base.url_encode64(padding: false)
  25. end
  26. end
  27. # Usage
  28. #
  29. # App.Imgproxy.build_url(
  30. # "https://myawesomedomain.com/raw-image.png",
  31. # %{resize: "fit", width: 1000, height: 400, gravity: "ce", enlarge: 0, extension: "jpg"}
  32. # )