PhoenixApiToolkit.Ecto.Validators.validate_upload

You're seeing just the function validate_upload, go back to PhoenixApiToolkit.Ecto.Validators module for more information.
Link to this function

validate_upload(changeset, field, file_signature)

View Source

Specs

validate_upload(Ecto.Changeset.t(), atom(), binary() | [binary()]) ::
  Ecto.Changeset.t()

For verifying files uploaded as base64-encoded binaries. Attempts to decode field and validate its file signature. The file signature, also known as a file's "magic bytes", can be looked up on the internet (for example here) and may be a list of allowed magic byte types.

Examples

For the implementation of changeset/1, see Elixir.PhoenixApiToolkit.Ecto.Validators.

@pdf_signature "255044462D" |> Base.decode16!()
@png_signature "89504E470D0A1A0A" |> Base.decode16!()
@png_file "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNk+A8AAQUBAScY42YAAAAASUVORK5CYII="
@gif_file "R0lGODlhAQABAIAAAP///wAAACH5BAEAAAAALAAAAAABAAEAAAICRAEAOw=="

# if the signature checks out, the uploaded file is decoded and the changeset valid
iex> cs = changeset(%{file: @png_file}) |> validate_upload(:file, @png_signature)
iex> {cs.valid?, cs.changes.file}
{true, @png_file |> Base.decode64!()}

# multiple signatures can be provided
iex> cs = changeset(%{file: @png_file}) |> validate_upload(:file, [@pdf_signature, @png_signature])
iex> cs.valid?
true

# if the signature does not check out, an error is added to the changeset and the decoded file is discarded
iex> cs = changeset(%{file: @gif_file}) |> validate_upload(:file, [@pdf_signature, @png_signature])
iex> {cs.valid?, cs.errors, cs.changes.file}
{false, [file: {"invalid file type", []}], @gif_file}

# decoding errors are handled gracefully
iex> cs = changeset(%{file: "a"}) |> validate_upload(:file, @pdf_signature)
iex> {cs.valid?, cs.errors}
{false, [file: {"invalid base64 encoding", []}]}