File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1+ defmodule Fields.EncryptedBase64 do
2+ @ moduledoc """
3+ An Ecto Type for encrypted fields.
4+ See `Fields.AES` for details on encryption/decryption.
5+
6+ ## Example
7+
8+ schema "users" do
9+ field :name, Fields.EncryptedBase64
10+ end
11+ """
12+ use Ecto.Type
13+ alias Fields.AES
14+ require Logger
15+
16+ def type ( ) ,
17+ do: :string
18+
19+ def cast ( value ) ,
20+ do: { :ok , to_string ( value ) }
21+
22+ def dump ( value ) ,
23+ do:
24+ value
25+ |> then ( fn
26+ # Input value is nil. Store as-is. It's the developer's job
27+ # to run validations if they don't want that.
28+ nil -> value
29+ # Value is any kind of binary. Encrypt, and base64 encode.
30+ << >> <> _ -> value |> to_string |> AES . encrypt ( ) |> Base . encode64 ( padding: true )
31+ end )
32+ |> then ( & { :ok , & 1 } )
33+
34+ def load ( value ) ,
35+ do:
36+ value
37+ |> then ( fn
38+ # We got nil from the database... Just use that.
39+ nil -> value
40+ # We got any binary. Decode64 and decrypt.
41+ << >> <> _ -> value |> Base . decode64! ( padding: true ) |> AES . decrypt ( )
42+ end )
43+ |> then ( & { :ok , & 1 } )
44+
45+ def embed_as ( _ ) ,
46+ do: :dump
47+
48+ def equal? ( term1 , term2 ) ,
49+ do: term1 == term2
50+ end
You can’t perform that action at this time.
0 commit comments