Created
March 23, 2019 10:50
-
-
Save zoltanarvai/58613f940590e1e8b4757e5236346f94 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
defmodule Auth.Credentials do | |
@moduledoc """ | |
This module represents and validates the credentials | |
""" | |
use Ecto.Schema | |
import Ecto.Changeset | |
alias Auth.Credentials | |
@primary_key false | |
embedded_schema do | |
field :username, :string | |
field :password, :string | |
end | |
@allowed_fields [:username, :password] | |
@required_fields [:username, :password] | |
@type t :: %__MODULE__{ | |
username: String.t(), | |
password: String.t() | |
} | |
@doc """ | |
Validates the credentials object | |
Returns: {:ok, %Credentials{}} | {:error, Ecto.Changeset.t(Credentials)} | |
""" | |
@spec validate(map()) :: {:ok, Credentials.t()} | {:error, Ecto.Changeset.t(__MODULE__)} | |
def validate(%{} = params \\ %{}) do | |
%Credentials{} | |
|> cast(params, @allowed_fields) | |
|> validate_required(@required_fields) | |
|> validate_password() | |
|> apply_action(:insert) | |
end | |
defp validate_password(changeset) do | |
validate_change(changeset, :password, fn _field, password -> | |
case Base.decode64(password, ignore: :whitespace) do | |
{:ok, _decoded_password} -> | |
[] | |
:error -> | |
[password: "Must be base64 encoded"] | |
end | |
end) | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment