File tree Expand file tree Collapse file tree 1 file changed +47
-0
lines changed
Expand file tree Collapse file tree 1 file changed +47
-0
lines changed 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+ alias Fields.AES
13+ use Ecto.Type
14+ def type , do: :binary
15+
16+ def cast ( value ) ,
17+ do: { :ok , to_string ( value ) }
18+
19+ def dump ( value ) ,
20+ do:
21+ value
22+ |> then ( fn
23+ # Input value is nil. Store as-is. It's the developer's job
24+ # to run validations if they don't want that.
25+ nil -> value
26+ # Value is any kind of binary. Encrypt, and base64 encode.
27+ << >> <> _ -> value |> to_string |> AES . encrypt ( ) |> Base . encode64 ( )
28+ end )
29+ |> then ( & { :ok , & 1 } )
30+
31+ def load ( value ) ,
32+ do:
33+ value
34+ |> then ( fn
35+ # We got nil from the database... Just use that.
36+ nil -> value
37+ # We got any binary. Decode64 and decrypt.
38+ << >> <> _ -> value |> Base . decode64! ( ) |> AES . decrypt ( )
39+ end )
40+ |> then ( & { :ok , & 1 } )
41+
42+ def embed_as ( _ ) ,
43+ do: :self
44+
45+ def equal? ( term1 , term2 ) ,
46+ do: term1 == term2
47+ end
You can’t perform that action at this time.
0 commit comments