From 41d6fdb876f05b1bed870924c100a0f9e7ac31d4 Mon Sep 17 00:00:00 2001 From: Marcin Kulik Date: Fri, 25 Aug 2023 16:11:18 +0200 Subject: [PATCH] Make /u/ work same way as /u/ --- lib/asciinema/accounts.ex | 19 ++++++++++--------- .../controllers/user_controller.ex | 13 ++++++++----- 2 files changed, 18 insertions(+), 14 deletions(-) diff --git a/lib/asciinema/accounts.ex b/lib/asciinema/accounts.ex index 94bc1ea74..b8a8a64a5 100644 --- a/lib/asciinema/accounts.ex +++ b/lib/asciinema/accounts.ex @@ -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 @@ -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 diff --git a/lib/asciinema_web/controllers/user_controller.ex b/lib/asciinema_web/controllers/user_controller.ex index a0fa68a0b..62d3757bc 100644 --- a/lib/asciinema_web/controllers/user_controller.ex +++ b/lib/asciinema_web/controllers/user_controller.ex @@ -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 @@ -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