Backend/src/main/kotlin/dev/fyloz/musicplayer/modules/spotify/SpotifyModule.kt
2022-12-17 21:26:30 -05:00

77 lines
2.7 KiB
Kotlin

package dev.fyloz.musicplayer.modules.spotify
import dev.fyloz.musicplayer.core.KoinModule
import dev.fyloz.musicplayer.modules.Module
import dev.fyloz.musicplayer.modules.spotify.config.SpotifyConfiguration
import io.ktor.client.*
import io.ktor.http.*
import io.ktor.server.application.*
import io.ktor.server.auth.*
import io.ktor.server.config.*
import io.ktor.server.response.*
import io.ktor.server.routing.*
import org.koin.ktor.ext.inject
class SpotifyModule : Module(moduleName) {
override fun setupDependencyInjection(module: KoinModule, config: ApplicationConfig) {
with(module) {
single { SpotifyConfiguration.fromEnvironment(config) }
}
}
override fun configure(app: Application) {
super.configure(app)
val httpClient by app.inject<HttpClient>()
val config by app.inject<SpotifyConfiguration>()
with(app) {
authentication {
oauth(oauthName) {
urlProvider = { "http://localhost:8080/module/spotify/login-callback" }
providerLookup = {
OAuthServerSettings.OAuth2ServerSettings(
name = moduleName,
authorizeUrl = "https://accounts.spotify.com/authorize",
accessTokenUrl = "https://accounts.spotify.com/api/token",
requestMethod = HttpMethod.Post,
clientId = config.clientId,
clientSecret = config.clientSecret,
defaultScopes = listOf("user-read-private user-read-email")
)
}
client = httpClient
}
}
}
}
override fun getAuthorizationData(call: ApplicationCall) = SpotifyAuthorizationData(
call.request.cookies["Spotify-Access-Token"]!!
)
override fun Route.configureModuleRoutes() {
authenticate(oauthName) {
get("/login") {
call.respondRedirect("https://accounts.spotify.com/authorize")
}
get("/login-callback") {
call.principal<OAuthAccessTokenResponse.OAuth2>()?.let {
with(call.response.cookies) {
append("Spotify-Access-Token", it.accessToken, maxAge = it.expiresIn)
append("Spotify-Refresh-Token", it.refreshToken!!)
}
}
}
}
}
override fun getTrackFactory() = SpotifyTrackFactory()
companion object {
const val moduleName = "spotify"
const val oauthName = "auth-oauth-spotify"
}
}