Skip to content

Instantly share code, notes, and snippets.

@jclem
Created December 30, 2016 15:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jclem/b8e0547cfed23413856b0ce3a4f618ae to your computer and use it in GitHub Desktop.
Save jclem/b8e0547cfed23413856b0ce3a4f618ae to your computer and use it in GitHub Desktop.
defmodule API.EncryptedField do
@moduledoc """
A field that is encrypted in the database and decrypted when read out of it
"""
import API.Encryption
@behaviour Ecto.Type
@spec type() :: :string
def type, do: :string
@spec cast(any) :: {:ok, String.t}
def cast(nil), do: {:ok, nil}
def cast(value), do: {:ok, to_string(value)}
@spec dump(String.t) :: {:ok, String.t}
def dump(nil), do: {:ok, nil}
def dump(value), do: {:ok, value |> encrypt}
@spec load(String.t) :: {:ok, String.t}
def load(nil), do: {:ok, nil}
def load(value), do: {:ok, value |> decrypt}
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment