Skip to content

Commit

Permalink
Make /u/<username> work same way as /u/<id>
Browse files Browse the repository at this point in the history
  • Loading branch information
ku1ik committed Aug 25, 2023
1 parent 2c6f28a commit 41d6fdb
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 14 deletions.
19 changes: 10 additions & 9 deletions lib/asciinema/accounts.ex
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,14 @@ defmodule Asciinema.Accounts do

def get_user(id), do: Repo.get(User, id)

def find_user_by_username(username) do
Repo.one(
from(u in User,
where: fragment("lower(?)", u.username) == ^String.downcase(username)
)
)
end

def find_user_by_auth_token(auth_token) do
Repo.get_by(User, auth_token: auth_token)
end
Expand Down Expand Up @@ -120,18 +128,11 @@ defmodule Asciinema.Accounts do
end
end

def lookup_user(identifier) do
def lookup_user(identifier) when is_binary(identifier) do
if String.contains?(identifier, "@") do
{:email, Repo.get_by(User, email: identifier)}
else
user =
Repo.one(
from(u in User,
where: fragment("lower(?)", u.username) == ^String.downcase(identifier)
)
)

{:username, user}
{:username, find_user_by_username(identifier)}
end
end

Expand Down
13 changes: 8 additions & 5 deletions lib/asciinema_web/controllers/user_controller.ex
Original file line number Diff line number Diff line change
Expand Up @@ -47,8 +47,10 @@ defmodule AsciinemaWeb.UserController do
end

def show(conn, params) do
with {:ok, user} <- fetch_user(params) do
if user = fetch_user(params) do
do_show(conn, params, user)
else
{:error, :not_found}
end
end

Expand Down Expand Up @@ -84,14 +86,15 @@ defmodule AsciinemaWeb.UserController do
end

defp fetch_user(%{"id" => id}) do
case Integer.parse(id) do
{id, ""} -> Accounts.fetch_user(id)
_ -> {:error, :not_found}
if String.match?(id, ~r/^\d+$/) do
Accounts.get_user(id)
else
Accounts.find_user_by_username(id)
end
end

defp fetch_user(%{"username" => username}) do
Accounts.fetch_user(username: username)
Accounts.find_user_by_username(username)
end

def edit(conn, _params) do
Expand Down

0 comments on commit 41d6fdb

Please sign in to comment.