signature.ex 998 B

12345678910111213141516171819202122232425262728293031323334
  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. "rs:#{opts.resize}:#{opts.width}:#{opts.height}:#{opts.enlarge}",
  14. "g:#{opts.gravity}",
  15. Base.url_encode64(img_url, padding: false) <> "." <> opts.extension
  16. ])
  17. end
  18. defp gen_signature(path) do
  19. :sha256
  20. |> :crypto.hmac(@key, @salt <> path)
  21. |> Base.url_encode64(padding: false)
  22. end
  23. end
  24. # Usage
  25. #
  26. # App.Imgproxy.build_url(
  27. # "https://myawesomedomain.com/raw-image.png",
  28. # %{resize: "fit", width: 1000, height: 400, gravity: "ce", enlarge: 0, extension: "jpg"}
  29. # )