@@ -155,7 +155,7 @@ defmodule AlgoraWeb.InstallationCallbackController do
155
155
{ :ok , org } <-
156
156
org
157
157
|> change (
158
- handle: Organizations . ensure_unique_org_handle ( installation [ "account" ] [ "login" ] ) ,
158
+ handle: org . handle || Organizations . ensure_unique_org_handle ( installation [ "account" ] [ "login" ] ) ,
159
159
featured: org . featured || featured ,
160
160
provider: "github" ,
161
161
provider_id: to_string ( installation [ "account" ] [ "id" ] ) ,
@@ -168,13 +168,25 @@ defmodule AlgoraWeb.InstallationCallbackController do
168
168
end
169
169
end
170
170
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 ) ,
173
182
{ :ok , org } <-
174
183
org
175
184
|> change (
176
185
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
+ } ,
178
190
if is_nil ( org . provider_id ) do
179
191
% {
180
192
provider: "github" ,
@@ -187,8 +199,9 @@ defmodule AlgoraWeb.InstallationCallbackController do
187
199
end
188
200
)
189
201
)
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 }
192
205
end
193
206
end
194
207
end
0 commit comments