@@ -33,13 +33,9 @@ def save(self, installation: Installation):
3333 i = installation .to_dict ()
3434 if is_naive (i ["installed_at" ]):
3535 i ["installed_at" ] = make_aware (i ["installed_at" ])
36- if i .get ("bot_token_expires_at" ) is not None and is_naive (
37- i ["bot_token_expires_at" ]
38- ):
36+ if i .get ("bot_token_expires_at" ) is not None and is_naive (i ["bot_token_expires_at" ]):
3937 i ["bot_token_expires_at" ] = make_aware (i ["bot_token_expires_at" ])
40- if i .get ("user_token_expires_at" ) is not None and is_naive (
41- i ["user_token_expires_at" ]
42- ):
38+ if i .get ("user_token_expires_at" ) is not None and is_naive (i ["user_token_expires_at" ]):
4339 i ["user_token_expires_at" ] = make_aware (i ["user_token_expires_at" ])
4440 i ["client_id" ] = self .client_id
4541 row_to_update = (
@@ -62,9 +58,7 @@ def save_bot(self, bot: Bot):
6258 b = bot .to_dict ()
6359 if is_naive (b ["installed_at" ]):
6460 b ["installed_at" ] = make_aware (b ["installed_at" ])
65- if b .get ("bot_token_expires_at" ) is not None and is_naive (
66- b ["bot_token_expires_at" ]
67- ):
61+ if b .get ("bot_token_expires_at" ) is not None and is_naive (b ["bot_token_expires_at" ]):
6862 b ["bot_token_expires_at" ] = make_aware (b ["bot_token_expires_at" ])
6963 b ["client_id" ] = self .client_id
7064
@@ -145,6 +139,24 @@ def find_installation(
145139
146140 if len (rows ) > 0 :
147141 i = rows [0 ]
142+ if user_id is not None :
143+ # Fetch the latest bot token
144+ latest_bot_rows = (
145+ SlackInstallation .objects .filter (client_id = self .client_id )
146+ .exclude (bot_token__isnull = True )
147+ .filter (enterprise_id = e_id )
148+ .filter (team_id = t_id )
149+ .order_by (F ("installed_at" ).desc ())[:1 ]
150+ )
151+ if len (latest_bot_rows ) > 0 :
152+ b = latest_bot_rows [0 ]
153+ i .bot_id = b .bot_id
154+ i .bot_user_id = b .bot_user_id
155+ i .bot_scopes = b .bot_scopes
156+ i .bot_token = b .bot_token
157+ i .bot_refresh_token = b .bot_refresh_token
158+ i .bot_token_expires_at = b .bot_token_expires_at
159+
148160 return Installation (
149161 app_id = i .app_id ,
150162 enterprise_id = i .enterprise_id ,
@@ -191,9 +203,7 @@ def issue(self) -> str:
191203 return state
192204
193205 def consume (self , state : str ) -> bool :
194- rows = SlackOAuthState .objects .filter (state = state ).filter (
195- expire_at__gte = timezone .now ()
196- )
206+ rows = SlackOAuthState .objects .filter (state = state ).filter (expire_at__gte = timezone .now ())
197207 if len (rows ) > 0 :
198208 for row in rows :
199209 row .delete ()
0 commit comments