0
votes

I have the following action in My Phoenix app controller:

defmodule TattooBackend.Web.API.V1.TokenController do
  use TattooBackend.Web, :controller

  alias TattooBackend.Accounts.Account
  alias TattooBackend.Repo
  alias TattooBackend.Web.Endpoint
  alias Comeonin.Bcrypt
  alias Phoenix.Token

  action_fallback TattooBackend.Web.FallbackController

  def create(conn, params) do
    email = to_string(params["email"])
    password = to_string(params["password"])

    account = Repo.get_by(Account, email: String.downcase(email))

    case account && Bcrypt.checkpw(password, account.crypted_password) do
      true ->  render conn, token:  Token.sign(Endpoint, "user", account.id)
      _    ->  {:error, :wrong_credentials}
    end
  end
end

On these lines:

email = to_string(params["email"])
password = to_string(params["password"])

on these lines I'm converting my params to empty string if they are nil. I do that because when I for example pass nil to String.downcase method, app will break. And the question is, is there any "Phoenix way" of handling such a case?

1

1 Answers

2
votes

I'd use the || operator, which returns the RHS if the LHS is nil or false, or Map.get/3 with a default value:

email = params["email"] || ""
password = params["password"] || ""

or

email = Map.get(params, "email", "")
password = Map.get(params, "password", "")