suspend fun onAppInstalledToSlackTeam()

in space-slack-sync/src/main/kotlin/org/jetbrains/spaceSlackSync/slack/SlackOAuthFlow.kt [25:71]


suspend fun onAppInstalledToSlackTeam(call: ApplicationCall, spaceOrgId: String, params: Routes.SlackOAuthCallback) {
    if (params.code.isNullOrBlank()) {
        log.info("Authentication in Slack returned no auth code")
        val spaceAppInstance = getSpaceAppInstance(spaceOrgId, call) ?: return
        redirectBackToHomepageInSpace(spaceAppInstance, call)
        return
    }

    val response = requestOAuthToken(params.code)
    val accessToken = response?.accessToken
    val refreshToken = response?.refreshToken
    val accessTokenExpiresAt = LocalDateTime.now().plusSeconds(response?.expiresIn?.toLong() ?: 43200L)
    val teamId = response?.team?.id

    withContext(MDCContext(mapOf(MDCParams.SLACK_TEAM_ID to teamId.orEmpty(), MDCParams.SPACE_CLIENT_ID to spaceOrgId))) {
        if (accessToken.isNullOrBlank() || refreshToken.isNullOrBlank() || teamId.isNullOrBlank()) {
            val message = "Could not fetch OAuth token from Slack. " +
                    "Team id = $teamId, " +
                    "access token is ${if (accessToken.isNullOrBlank()) "empty" else "provided"}, " +
                    "refresh token is ${if (refreshToken.isNullOrBlank()) "empty" else "provided"}, " +
                    "code = ${params.code}"
            call.respondError(HttpStatusCode.Unauthorized, log, message)
            return@withContext
        }

        val teamResponse = slackApiClient.methods(accessToken).teamInfo { it.team(teamId) }
        if (teamResponse.team == null) {
            call.respondError(
                HttpStatusCode.Unauthorized, log, "Could not fetch team info from Slack - ${teamResponse.error}"
            )
            return@withContext
        }

        val spaceAppInstance = getSpaceAppInstance(spaceOrgId, call) ?: return@withContext
        db.slackTeams.createOrUpdate(
            teamId,
            teamResponse.team.domain,
            spaceOrgId,
            accessToken.encrypted(),
            refreshToken.encrypted(),
            accessTokenExpiresAt
        )

        log.info("Slack team connected to Space org")
        redirectBackToHomepageInSpace(spaceAppInstance, call)
    }
}