funkwhale-app-android/app/src/main/java/audio/funkwhale/ffa/utils/OAuth.kt

255 lines
6.8 KiB
Kotlin
Raw Normal View History

2021-07-23 14:10:13 +02:00
package audio.funkwhale.ffa.utils
import android.app.Activity
import android.content.Context
import android.content.Intent
import android.net.Uri
import com.github.kittinunf.fuel.Fuel
2021-08-03 10:28:17 +02:00
import com.github.kittinunf.fuel.core.FuelError
2021-07-23 14:10:13 +02:00
import com.github.kittinunf.fuel.coroutines.awaitObjectResponseResult
import com.github.kittinunf.fuel.gson.gsonDeserializerOf
import com.github.kittinunf.fuel.gson.jsonBody
import com.github.kittinunf.result.Result
import com.preference.PowerPreference
import kotlinx.coroutines.runBlocking
import net.openid.appauth.AuthState
import net.openid.appauth.AuthorizationException
import net.openid.appauth.AuthorizationRequest
import net.openid.appauth.AuthorizationResponse
import net.openid.appauth.AuthorizationService
import net.openid.appauth.AuthorizationServiceConfiguration
import net.openid.appauth.ClientSecretPost
import net.openid.appauth.RegistrationRequest
import net.openid.appauth.RegistrationResponse
import net.openid.appauth.ResponseTypeValues
fun AuthState.save() {
PowerPreference.getFileByName(AppContext.PREFS_CREDENTIALS).apply {
val value = jsonSerializeString()
setString("state", value)
}
}
2021-07-30 10:57:49 +02:00
interface OAuth {
2021-08-03 10:28:17 +02:00
fun exchange(context: Context, authorization: Intent, success: () -> Unit, error: () -> Unit)
2021-07-30 10:57:49 +02:00
2021-08-02 13:24:12 +02:00
fun init(hostname: String): AuthState
2021-07-30 10:57:49 +02:00
2021-08-02 13:24:12 +02:00
fun register(authState: AuthState? = null, callback: () -> Unit)
2021-07-30 10:57:49 +02:00
2021-08-03 10:28:17 +02:00
fun authorize(activity: Activity)
2021-07-30 10:57:49 +02:00
fun isAuthorized(context: Context): Boolean
2021-08-02 13:24:12 +02:00
fun tryRefreshAccessToken(context: Context): Boolean
2021-07-30 10:57:49 +02:00
fun tryState(): AuthState?
fun state(): AuthState
fun service(context: Context): AuthorizationService
}
object OAuthFactory {
private val oAuth: OAuth
init {
2021-08-02 13:24:12 +02:00
oAuth = DefaultOAuth(AuthorizationServiceFactory())
2021-07-30 10:57:49 +02:00
}
fun instance() = oAuth
}
2021-08-02 13:24:12 +02:00
class AuthorizationServiceFactory {
fun create(context: Context): AuthorizationService {
return AuthorizationService(context)
}
}
class DefaultOAuth(private val authorizationServiceFactory: AuthorizationServiceFactory) : OAuth {
2021-07-30 10:57:49 +02:00
companion object {
private val REDIRECT_URI =
Uri.parse("urn:/audio.funkwhale.funkwhale-android/oauth/callback")
}
2021-07-23 14:10:13 +02:00
data class App(val client_id: String, val client_secret: String)
2021-07-30 10:57:49 +02:00
override fun tryState(): AuthState? {
val savedState = PowerPreference
.getFileByName(AppContext.PREFS_CREDENTIALS)
.getString("state")
return if (savedState != null && savedState.isNotEmpty()) {
return AuthState.jsonDeserialize(savedState)
} else {
null
}
}
2021-08-02 13:24:12 +02:00
override fun state(): AuthState =
tryState() ?: throw IllegalStateException("Couldn't find saved state")
2021-07-23 14:10:13 +02:00
2021-07-30 10:57:49 +02:00
override fun isAuthorized(context: Context): Boolean {
2021-07-23 14:10:13 +02:00
val state = tryState()
return if (state != null) {
2021-08-02 13:24:12 +02:00
state.isAuthorized || doTryRefreshAccessToken(state, context)
2021-07-23 14:10:13 +02:00
} else {
false
}.also {
it.log("isAuthorized()")
}
}
2021-08-02 13:24:12 +02:00
override fun tryRefreshAccessToken(context: Context): Boolean {
2021-07-23 14:10:13 +02:00
tryState()?.let { state ->
2021-08-02 13:24:12 +02:00
return doTryRefreshAccessToken(state, context)
}
return false
}
private fun doTryRefreshAccessToken(
state: AuthState,
context: Context
): Boolean {
if (state.needsTokenRefresh && state.refreshToken != null) {
val refreshRequest = state.createTokenRefreshRequest()
val auth = ClientSecretPost(state.clientSecret)
runBlocking {
service(context).performTokenRequest(refreshRequest, auth) { response, e ->
state.apply {
update(response, e)
save()
2021-07-23 14:10:13 +02:00
}
}
}
}
2021-08-02 13:24:12 +02:00
return (state.isAuthorized)
2021-07-23 14:10:13 +02:00
.also {
it.log("tryRefreshAccessToken()")
}
}
2021-08-02 13:24:12 +02:00
override fun init(hostname: String): AuthState {
return AuthState(
AuthorizationServiceConfiguration(
Uri.parse("$hostname/authorize"),
Uri.parse("$hostname/api/v1/oauth/token/"),
Uri.parse("$hostname/api/v1/oauth/apps/")
)
)
.also {
it.save()
}
2021-07-23 14:10:13 +02:00
}
2021-08-02 13:24:12 +02:00
override fun service(context: Context): AuthorizationService =
authorizationServiceFactory.create(context)
2021-07-23 14:10:13 +02:00
2021-08-02 13:24:12 +02:00
override fun register(authState: AuthState?, callback: () -> Unit) {
(authState ?: state()).authorizationServiceConfiguration?.let { config ->
2021-07-23 14:10:13 +02:00
runBlocking {
2021-08-03 10:28:17 +02:00
val (_, _, result: Result<App, FuelError>) = Fuel.post(config.registrationEndpoint.toString())
2021-07-23 14:10:13 +02:00
.header("Content-Type", "application/json")
.jsonBody(registrationBody())
.awaitObjectResponseResult(gsonDeserializerOf(App::class.java))
when (result) {
is Result.Success -> {
val app = result.get()
val response = RegistrationResponse.Builder(registration()!!)
.setClientId(app.client_id)
.setClientSecret(app.client_secret)
.setClientIdIssuedAt(0)
.setClientSecretExpiresAt(null)
.build()
state().apply {
update(response)
save()
callback()
}
}
is Result.Failure -> {
2021-08-03 10:28:17 +02:00
result.log("register()")
2021-07-23 14:10:13 +02:00
}
}
}
}
}
private fun registrationBody(): Map<String, String> {
return mapOf(
"name" to "Funkwhale for Android (${android.os.Build.MODEL})",
"redirect_uris" to REDIRECT_URI.toString(),
"scopes" to "read write"
)
}
2021-08-03 10:28:17 +02:00
override fun authorize(activity: Activity) {
val authService = service(activity)
authorizationRequest()?.let { it ->
val intent = authService.getAuthorizationRequestIntent(it)
activity.startActivityForResult(intent, 0)
2021-07-23 14:10:13 +02:00
}
}
2021-07-30 10:57:49 +02:00
override fun exchange(
2021-08-03 10:28:17 +02:00
context: Context,
2021-07-30 10:57:49 +02:00
authorization: Intent,
success: () -> Unit,
error: () -> Unit
) {
2021-07-23 14:10:13 +02:00
state().let { state ->
state.apply {
update(
AuthorizationResponse.fromIntent(authorization),
AuthorizationException.fromIntent(authorization)
)
save()
}
AuthorizationResponse.fromIntent(authorization)?.let {
val auth = ClientSecretPost(state().clientSecret)
service(context).performTokenRequest(it.createTokenExchangeRequest(), auth) { response, e ->
state
.apply {
update(response, e)
save()
}
if (response != null) success()
else error()
}
}
}
}
private fun registration() =
state().authorizationServiceConfiguration?.let { config ->
RegistrationRequest.Builder(config, listOf(REDIRECT_URI)).build()
}
private fun authorizationRequest() = state().let { state ->
state.authorizationServiceConfiguration?.let { config ->
AuthorizationRequest.Builder(
config,
state.lastRegistrationResponse?.clientId ?: "",
ResponseTypeValues.CODE,
REDIRECT_URI
)
.setScopes("read", "write")
.build()
}
}
}