Login with email or username implementation

I have login method

def login(conn, %{"username or email" => username or email, "password" => password})  do
end        

The problem is getting users record because I don’t know if email will come or username .

Any ideas?

Thanks

You can check by regex if passed params looks like an email, otherwise use it as name…

1 Like

HI Thanks for your suggestion.
I had that idea but what if user uses @ in its username.
It will break the code.
Need to think of all possibilities.

There are many regex available for email, some more complicated than others…

In case You don’t want to use this, You could use a multi condition query to retrieve user.

Something like

where username … or email …

1 Like

I am thinking about this:

 def user_username(params) do
   case Repo.get_by(User, username: params) do
    nil -> check_email_for_user(params)
   

    user ->
      {:ok, user}
   end
 end

def check_email_for_user(params) do
  case Repo.get_by(User, email_address: params) do
    nil ->
      {:error, :user_not_found}

    user ->
      {:ok, user}
   end
end

What you think about this approach?

You probably don’t wanna allow special characters in username. Look at how twitter, Facebook and other big sites do it. If you limit username strictly to alphanumeric then its just matter of checking @ in string to distinguish between email and username.

2 Likes

Could you just do something like

Repo.one(from u in User, where: u.username == ^username or u.email == ^username, limit: 1)

Then your password check if there is a return. You should probably remove the ability to use @ characters in usernames though.

Yes. Dump the idea of “username” as a login token.

I personally hate being asked to “pick a username” when my email
is absolutely guaranteed to be unique in your system, and a value
I’ll remember easily.

What value does your bifurcated login path provide?

2 Likes