Skip to content

Commit fd0ba23

Browse files
committed
fix: handle existing org case in github installation flow
1 parent 9395374 commit fd0ba23

File tree

1 file changed

+19
-6
lines changed

1 file changed

+19
-6
lines changed

lib/algora_web/controllers/installation_callback_controller.ex

Lines changed: 19 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -155,7 +155,7 @@ defmodule AlgoraWeb.InstallationCallbackController do
155155
{:ok, org} <-
156156
org
157157
|> change(
158-
handle: Organizations.ensure_unique_org_handle(installation["account"]["login"]),
158+
handle: org.handle || Organizations.ensure_unique_org_handle(installation["account"]["login"]),
159159
featured: org.featured || featured,
160160
provider: "github",
161161
provider_id: to_string(installation["account"]["id"]),
@@ -168,13 +168,25 @@ defmodule AlgoraWeb.InstallationCallbackController do
168168
end
169169
end
170170

171-
defp update_user_and_org(conn, %{last_context: last_context} = _user, installation, featured) do
172-
with {:ok, org} <- Organizations.fetch_org_by(handle: last_context),
171+
defp update_user_and_org(conn, %{last_context: last_context} = user, installation, featured) do
172+
existing_org =
173+
Repo.one(
174+
from(u in User,
175+
where: u.provider == "github",
176+
where: u.provider_id == ^to_string(installation["account"]["id"])
177+
)
178+
)
179+
180+
with {:ok, org} <- if(existing_org, do: {:ok, existing_org}, else: Organizations.fetch_org_by(handle: last_context)),
181+
{:ok, _member} <- fetch_or_create_member(user, org),
173182
{:ok, org} <-
174183
org
175184
|> change(
176185
Map.merge(
177-
%{featured: org.featured || featured},
186+
%{
187+
handle: org.handle || Organizations.ensure_unique_org_handle(installation["account"]["login"]),
188+
featured: org.featured || featured
189+
},
178190
if is_nil(org.provider_id) do
179191
%{
180192
provider: "github",
@@ -187,8 +199,9 @@ defmodule AlgoraWeb.InstallationCallbackController do
187199
end
188200
)
189201
)
190-
|> Repo.update() do
191-
{:ok, conn, org}
202+
|> Repo.update(),
203+
{:ok, user} <- user |> change(last_context: org.handle) |> Repo.update() do
204+
{:ok, UserAuth.put_current_user(conn, user), org}
192205
end
193206
end
194207
end

0 commit comments

Comments
 (0)