suspend fun onAppInstalledToSlackTeam()

in src/main/kotlin/org/jetbrains/slackUnfurls/slackUnfurlsInSpace/SlackOAuthFlow.kt [103:151]


suspend fun onAppInstalledToSlackTeam(call: ApplicationCall, spaceOrgId: String, params: Routes.SlackOAuthCallback) {
    if (params.code.isNullOrBlank()) {
        call.respondError(HttpStatusCode.BadRequest, log, "Expected code query string parameter in request")
        return
    }

    val response = requestOAuthToken(params.code)
    val accessToken = response?.accessToken
    val refreshToken = response?.refreshToken
    val teamId = response?.team?.id
    withContext(MDCContext(mapOf(MDCParams.SLACK_TEAM to teamId.orEmpty(), MDCParams.SPACE_ORG 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 spaceOrg = db.spaceOrgs.getById(spaceOrgId) ?: run {
            call.respondError(
                HttpStatusCode.BadRequest,
                log,
                "Unexpected value of the state query string parameter (flow id = $spaceOrgId)"
            )
            return@withContext
        }
        val spaceApp = getSpaceClient(spaceOrg).applications.getApplication(ApplicationIdentifier.Me)

        db.slackTeams.create(teamId, teamResponse.team.domain, spaceOrgId, encrypt(accessToken), encrypt(refreshToken), teamResponse.team.icon?.image44, teamResponse.team.name)

        log.info("Slack team connected to Space org")
        val backUrl = URLBuilder(spaceOrg.url).run {
            path("extensions", "installedApplications", "${spaceApp.name}-${spaceApp.id}", "homepage")
            buildString()
        }
        call.respondRedirect(backUrl)
    }
}