Add connect flow: login, API app provisioning and secure storage
CI / test (push) Successful in 2m17s
CI / test (push) Successful in 2m17s
DefaultAuthRepository logs in for a bearer token, finds or creates the "Scrobbled Android" API app (reused on reconnect), then obtains a Last.fm session key via auth.getMobileSession. Credentials are encrypted with an Android Keystore AES-GCM key. Adds ScrobblerApi (/api/v1), a Connect screen + ViewModel, and gates the main shell on stored credentials. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
5200ebdb2d
commit
36399be147
13 files changed
+613
-1
No files matched your search
@@ -42,6 +42,7 @@ dependencies {
|
||||
implementation(libs.androidx.core.ktx)
|
||||
implementation(libs.androidx.activity.compose)
|
||||
implementation(libs.androidx.lifecycle.runtime.compose)
|
||||
implementation(libs.androidx.lifecycle.viewmodel.compose)
|
||||
implementation(platform(libs.androidx.compose.bom))
|
||||
implementation(libs.androidx.compose.ui)
|
||||
implementation(libs.androidx.compose.ui.tooling.preview)
|
||||
|
||||
@@ -4,6 +4,7 @@
|
||||
<uses-permission android:name="android.permission.INTERNET" />
|
||||
|
||||
<application
|
||||
android:name=".ScrobbledApplication"
|
||||
android:allowBackup="true"
|
||||
android:dataExtractionRules="@xml/data_extraction_rules"
|
||||
android:fullBackupContent="@xml/backup_rules"
|
||||
|
||||
@@ -3,12 +3,32 @@ package dev.daubney.scrobbled
|
||||
import android.os.Bundle
|
||||
import androidx.activity.ComponentActivity
|
||||
import androidx.activity.compose.setContent
|
||||
import androidx.activity.viewModels
|
||||
import androidx.compose.runtime.collectAsState
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.lifecycle.ViewModel
|
||||
import androidx.lifecycle.ViewModelProvider
|
||||
import dev.daubney.scrobbled.ui.ScrobbledApp
|
||||
import dev.daubney.scrobbled.ui.connect.ConnectScreen
|
||||
import dev.daubney.scrobbled.ui.connect.ConnectViewModel
|
||||
import dev.daubney.scrobbled.ui.theme.ScrobbledTheme
|
||||
|
||||
class MainActivity : ComponentActivity() {
|
||||
private val connectVm by viewModels<ConnectViewModel> {
|
||||
object : ViewModelProvider.Factory {
|
||||
@Suppress("UNCHECKED_CAST")
|
||||
override fun <T : ViewModel> create(modelClass: Class<T>): T =
|
||||
ConnectViewModel((application as ScrobbledApplication).auth) as T
|
||||
}
|
||||
}
|
||||
|
||||
override fun onCreate(savedInstanceState: Bundle?) {
|
||||
super.onCreate(savedInstanceState)
|
||||
setContent { ScrobbledTheme { ScrobbledApp() } }
|
||||
setContent {
|
||||
ScrobbledTheme {
|
||||
val state by connectVm.state.collectAsState()
|
||||
if (state.connected) ScrobbledApp() else ConnectScreen(connectVm)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
package dev.daubney.scrobbled
|
||||
|
||||
import android.app.Application
|
||||
import dev.daubney.scrobbled.data.auth.AuthRepository
|
||||
import dev.daubney.scrobbled.data.auth.DefaultAuthRepository
|
||||
import dev.daubney.scrobbled.data.auth.KeystoreCredentialStore
|
||||
|
||||
/** Hand-rolled service locator; small enough that a DI framework isn't worth it yet. */
|
||||
class ScrobbledApplication : Application() {
|
||||
val auth: AuthRepository by lazy { DefaultAuthRepository(KeystoreCredentialStore(this)) }
|
||||
}
|
||||
@@ -0,0 +1,81 @@
|
||||
package dev.daubney.scrobbled.data.api
|
||||
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.withContext
|
||||
import kotlinx.serialization.json.Json
|
||||
import kotlinx.serialization.json.JsonArray
|
||||
import kotlinx.serialization.json.JsonElement
|
||||
import kotlinx.serialization.json.JsonObject
|
||||
import kotlinx.serialization.json.buildJsonObject
|
||||
import kotlinx.serialization.json.jsonArray
|
||||
import kotlinx.serialization.json.jsonObject
|
||||
import kotlinx.serialization.json.jsonPrimitive
|
||||
import kotlinx.serialization.json.put
|
||||
import okhttp3.HttpUrl.Companion.toHttpUrl
|
||||
import okhttp3.MediaType.Companion.toMediaType
|
||||
import okhttp3.OkHttpClient
|
||||
import okhttp3.Request
|
||||
import okhttp3.RequestBody.Companion.toRequestBody
|
||||
import java.io.IOException
|
||||
|
||||
data class ApiApp(val name: String, val apiKey: String, val sharedSecret: String)
|
||||
|
||||
data class Login(val token: String, val username: String)
|
||||
|
||||
/** [status] is the HTTP status, or -1 for transport/parse failures. */
|
||||
class ApiException(val status: Int, val code: String?, message: String) : Exception(message)
|
||||
|
||||
/** Client for the server's bearer-token `/api/v1` JSON API. */
|
||||
class ScrobblerApi(
|
||||
baseUrl: String,
|
||||
private val http: OkHttpClient = OkHttpClient(),
|
||||
) {
|
||||
private val base = baseUrl.trimEnd('/') + "/api/v1/"
|
||||
|
||||
suspend fun login(username: String, password: String): Login {
|
||||
val body = buildJsonObject { put("username", username); put("password", password) }
|
||||
val user = send("auth/login", null, body).jsonObject
|
||||
return Login(
|
||||
token = user.str("token") ?: throw ApiException(-1, null, "Login response had no token"),
|
||||
username = user["user"]?.jsonObject?.str("username") ?: username,
|
||||
)
|
||||
}
|
||||
|
||||
suspend fun listApps(token: String): List<ApiApp> =
|
||||
send("apps", token, null).jsonArray.map { it.jsonObject.toApp() }
|
||||
|
||||
suspend fun createApp(token: String, name: String): ApiApp =
|
||||
send("apps", token, buildJsonObject { put("name", name) }).jsonObject.toApp()
|
||||
|
||||
private fun JsonObject.toApp() = ApiApp(
|
||||
name = str("name").orEmpty(),
|
||||
apiKey = str("api_key") ?: throw ApiException(-1, null, "App had no api_key"),
|
||||
sharedSecret = str("shared_secret") ?: throw ApiException(-1, null, "App had no shared_secret"),
|
||||
)
|
||||
|
||||
private fun JsonObject.str(key: String) = this[key]?.jsonPrimitive?.content
|
||||
|
||||
/** GET when [body] is null, otherwise POST JSON. */
|
||||
private suspend fun send(path: String, token: String?, body: JsonObject?): JsonElement =
|
||||
withContext(Dispatchers.IO) {
|
||||
val request = Request.Builder().url((base + path).toHttpUrl()).apply {
|
||||
token?.let { header("Authorization", "Bearer $it") }
|
||||
if (body != null) post(body.toString().toRequestBody("application/json".toMediaType()))
|
||||
}.build()
|
||||
val (status, text) = try {
|
||||
http.newCall(request).execute().use { it.code to it.body?.string().orEmpty() }
|
||||
} catch (e: IOException) {
|
||||
throw ApiException(-1, null, e.message ?: "Network error")
|
||||
}
|
||||
val parsed = try {
|
||||
Json.parseToJsonElement(text)
|
||||
} catch (e: Exception) {
|
||||
null
|
||||
}
|
||||
if (status !in 200..299) {
|
||||
val err = (parsed as? JsonObject)?.get("error") as? JsonObject
|
||||
throw ApiException(status, err?.str("code"), err?.str("message") ?: "Request failed ($status)")
|
||||
}
|
||||
parsed ?: throw ApiException(-1, null, "Unexpected response from server")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
package dev.daubney.scrobbled.data.auth
|
||||
|
||||
import dev.daubney.scrobbled.data.api.ApiException
|
||||
import dev.daubney.scrobbled.data.api.LastFmClient
|
||||
import dev.daubney.scrobbled.data.api.LastFmException
|
||||
import dev.daubney.scrobbled.data.api.ScrobblerApi
|
||||
import okhttp3.HttpUrl.Companion.toHttpUrlOrNull
|
||||
|
||||
/** Why a connect attempt failed, in terms the UI can show. */
|
||||
class ConnectException(message: String) : Exception(message)
|
||||
|
||||
interface AuthRepository {
|
||||
fun current(): Credentials?
|
||||
suspend fun connect(serverUrl: String, username: String, password: String): Credentials
|
||||
fun disconnect()
|
||||
}
|
||||
|
||||
/**
|
||||
* Connect = log in for a bearer token, find or create this app's API key/secret, then use the
|
||||
* key to get a Last.fm session key (the only credential that can write scrobbles).
|
||||
*/
|
||||
class DefaultAuthRepository(
|
||||
private val store: CredentialStore,
|
||||
private val apiFor: (String) -> ScrobblerApi = { ScrobblerApi(it) },
|
||||
private val lastFmFor: (url: String, key: String, secret: String) -> LastFmClient =
|
||||
{ url, key, secret -> LastFmClient(url, key, secret) },
|
||||
) : AuthRepository {
|
||||
|
||||
override fun current(): Credentials? = store.load()
|
||||
|
||||
override suspend fun connect(serverUrl: String, username: String, password: String): Credentials {
|
||||
val url = normalizeServerUrl(serverUrl) ?: throw ConnectException("Enter a valid server address")
|
||||
try {
|
||||
val api = apiFor(url)
|
||||
val login = api.login(username, password)
|
||||
// Reuse our app on reconnect so repeated logins don't pile up API apps on the server.
|
||||
val app = api.listApps(login.token).firstOrNull { it.name == APP_NAME }
|
||||
?: api.createApp(login.token, APP_NAME)
|
||||
val session = lastFmFor(url, app.apiKey, app.sharedSecret).getMobileSession(username, password)
|
||||
return Credentials(url, login.username, login.token, app.apiKey, app.sharedSecret, session.key)
|
||||
.also(store::save)
|
||||
} catch (e: ApiException) {
|
||||
throw ConnectException(
|
||||
when {
|
||||
e.status == 401 -> "Wrong username or password"
|
||||
e.status == -1 -> "Couldn't reach the server: ${e.message}"
|
||||
else -> e.message.orEmpty()
|
||||
},
|
||||
)
|
||||
} catch (e: LastFmException) {
|
||||
throw ConnectException(if (e.code == -1) "Couldn't reach the server: ${e.message}" else e.message.orEmpty())
|
||||
}
|
||||
}
|
||||
|
||||
override fun disconnect() = store.clear()
|
||||
|
||||
companion object {
|
||||
const val APP_NAME = "Scrobbled Android"
|
||||
}
|
||||
}
|
||||
|
||||
/** Adds a scheme if missing (https) and strips trailing slashes; null if it isn't a usable URL. */
|
||||
fun normalizeServerUrl(input: String): String? {
|
||||
val trimmed = input.trim()
|
||||
if (trimmed.isEmpty()) return null
|
||||
val withScheme = if ("://" in trimmed) trimmed else "https://$trimmed"
|
||||
val url = withScheme.toHttpUrlOrNull() ?: return null
|
||||
if (url.scheme != "http" && url.scheme != "https") return null
|
||||
return withScheme.trimEnd('/')
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
package dev.daubney.scrobbled.data.auth
|
||||
|
||||
import kotlinx.serialization.Serializable
|
||||
|
||||
/** Everything needed to talk to the server after a successful connect. */
|
||||
@Serializable
|
||||
data class Credentials(
|
||||
val serverUrl: String,
|
||||
val username: String,
|
||||
/** Bearer token for `/api/v1` (30-day lifetime, no refresh). */
|
||||
val bearerToken: String,
|
||||
val apiKey: String,
|
||||
val apiSecret: String,
|
||||
/** Last.fm session key for `/2.0/` writes; does not expire. */
|
||||
val sessionKey: String,
|
||||
)
|
||||
|
||||
interface CredentialStore {
|
||||
fun load(): Credentials?
|
||||
fun save(credentials: Credentials)
|
||||
fun clear()
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
package dev.daubney.scrobbled.data.auth
|
||||
|
||||
import android.content.Context
|
||||
import android.security.keystore.KeyGenParameterSpec
|
||||
import android.security.keystore.KeyProperties
|
||||
import android.util.Base64
|
||||
import kotlinx.serialization.json.Json
|
||||
import java.security.KeyStore
|
||||
import javax.crypto.Cipher
|
||||
import javax.crypto.KeyGenerator
|
||||
import javax.crypto.SecretKey
|
||||
import javax.crypto.spec.GCMParameterSpec
|
||||
|
||||
/** Stores [Credentials] encrypted with an AES-GCM key held in the Android Keystore. */
|
||||
class KeystoreCredentialStore(context: Context) : CredentialStore {
|
||||
private val prefs = context.getSharedPreferences("credentials", Context.MODE_PRIVATE)
|
||||
|
||||
override fun load(): Credentials? {
|
||||
val encoded = prefs.getString(KEY_BLOB, null) ?: return null
|
||||
return try {
|
||||
val blob = Base64.decode(encoded, Base64.NO_WRAP)
|
||||
val cipher = Cipher.getInstance(TRANSFORM)
|
||||
cipher.init(Cipher.DECRYPT_MODE, secretKey(), GCMParameterSpec(128, blob.copyOfRange(0, IV_SIZE)))
|
||||
Json.decodeFromString<Credentials>(String(cipher.doFinal(blob, IV_SIZE, blob.size - IV_SIZE)))
|
||||
} catch (e: Exception) {
|
||||
// Key invalidated or data corrupt: treat as signed out rather than crash.
|
||||
clear()
|
||||
null
|
||||
}
|
||||
}
|
||||
|
||||
override fun save(credentials: Credentials) {
|
||||
val cipher = Cipher.getInstance(TRANSFORM).apply { init(Cipher.ENCRYPT_MODE, secretKey()) }
|
||||
val blob = cipher.iv + cipher.doFinal(Json.encodeToString(Credentials.serializer(), credentials).toByteArray())
|
||||
prefs.edit().putString(KEY_BLOB, Base64.encodeToString(blob, Base64.NO_WRAP)).apply()
|
||||
}
|
||||
|
||||
override fun clear() {
|
||||
prefs.edit().remove(KEY_BLOB).apply()
|
||||
}
|
||||
|
||||
private fun secretKey(): SecretKey {
|
||||
val ks = KeyStore.getInstance("AndroidKeyStore").apply { load(null) }
|
||||
(ks.getKey(ALIAS, null) as? SecretKey)?.let { return it }
|
||||
return KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES, "AndroidKeyStore").apply {
|
||||
init(
|
||||
KeyGenParameterSpec.Builder(ALIAS, KeyProperties.PURPOSE_ENCRYPT or KeyProperties.PURPOSE_DECRYPT)
|
||||
.setBlockModes(KeyProperties.BLOCK_MODE_GCM)
|
||||
.setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_NONE)
|
||||
.build(),
|
||||
)
|
||||
}.generateKey()
|
||||
}
|
||||
|
||||
private companion object {
|
||||
const val ALIAS = "scrobbled_credentials"
|
||||
const val KEY_BLOB = "blob"
|
||||
const val TRANSFORM = "AES/GCM/NoPadding"
|
||||
const val IV_SIZE = 12
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
package dev.daubney.scrobbled.ui.connect
|
||||
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.text.KeyboardOptions
|
||||
import androidx.compose.material3.Button
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.OutlinedTextField
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.collectAsState
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.text.input.KeyboardType
|
||||
import androidx.compose.ui.text.input.PasswordVisualTransformation
|
||||
import androidx.compose.ui.unit.dp
|
||||
|
||||
@Composable
|
||||
fun ConnectScreen(vm: ConnectViewModel) {
|
||||
val s by vm.state.collectAsState()
|
||||
Column(
|
||||
Modifier.fillMaxSize().padding(24.dp),
|
||||
verticalArrangement = Arrangement.spacedBy(12.dp, androidx.compose.ui.Alignment.CenterVertically),
|
||||
) {
|
||||
Text("Scrobbled", style = MaterialTheme.typography.headlineMedium)
|
||||
Text("Connect to your scrobbling server", color = MaterialTheme.colorScheme.onSurfaceVariant)
|
||||
OutlinedTextField(
|
||||
s.serverUrl, vm::onServerUrl, Modifier.fillMaxWidth(), singleLine = true,
|
||||
label = { Text("Server address") }, placeholder = { Text("https://scrobbler.example.com") },
|
||||
keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Uri),
|
||||
)
|
||||
OutlinedTextField(
|
||||
s.username, vm::onUsername, Modifier.fillMaxWidth(), singleLine = true,
|
||||
label = { Text("Username") },
|
||||
)
|
||||
OutlinedTextField(
|
||||
s.password, vm::onPassword, Modifier.fillMaxWidth(), singleLine = true,
|
||||
label = { Text("Password") }, visualTransformation = PasswordVisualTransformation(),
|
||||
keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Password),
|
||||
)
|
||||
s.error?.let { Text(it, color = MaterialTheme.colorScheme.error) }
|
||||
Button(vm::connect, Modifier.fillMaxWidth(), enabled = s.canSubmit) {
|
||||
Text(if (s.busy) "Connecting…" else "Connect")
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
package dev.daubney.scrobbled.ui.connect
|
||||
|
||||
import androidx.lifecycle.ViewModel
|
||||
import androidx.lifecycle.viewModelScope
|
||||
import dev.daubney.scrobbled.data.auth.AuthRepository
|
||||
import dev.daubney.scrobbled.data.auth.ConnectException
|
||||
import kotlinx.coroutines.flow.MutableStateFlow
|
||||
import kotlinx.coroutines.flow.StateFlow
|
||||
import kotlinx.coroutines.flow.asStateFlow
|
||||
import kotlinx.coroutines.flow.update
|
||||
import kotlinx.coroutines.launch
|
||||
|
||||
data class ConnectState(
|
||||
val serverUrl: String = "",
|
||||
val username: String = "",
|
||||
val password: String = "",
|
||||
val busy: Boolean = false,
|
||||
val error: String? = null,
|
||||
val connected: Boolean = false,
|
||||
) {
|
||||
val canSubmit get() = !busy && serverUrl.isNotBlank() && username.isNotBlank() && password.isNotEmpty()
|
||||
}
|
||||
|
||||
class ConnectViewModel(private val auth: AuthRepository) : ViewModel() {
|
||||
private val _state = MutableStateFlow(
|
||||
ConnectState(serverUrl = auth.current()?.serverUrl.orEmpty(), connected = auth.current() != null),
|
||||
)
|
||||
val state: StateFlow<ConnectState> = _state.asStateFlow()
|
||||
|
||||
fun onServerUrl(v: String) = _state.update { it.copy(serverUrl = v, error = null) }
|
||||
fun onUsername(v: String) = _state.update { it.copy(username = v, error = null) }
|
||||
fun onPassword(v: String) = _state.update { it.copy(password = v, error = null) }
|
||||
|
||||
fun connect() {
|
||||
val s = _state.value
|
||||
if (!s.canSubmit) return
|
||||
_state.update { it.copy(busy = true, error = null) }
|
||||
viewModelScope.launch {
|
||||
try {
|
||||
auth.connect(s.serverUrl, s.username.trim(), s.password)
|
||||
_state.update { it.copy(busy = false, password = "", connected = true) }
|
||||
} catch (e: ConnectException) {
|
||||
_state.update { it.copy(busy = false, error = e.message) }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun disconnect() {
|
||||
auth.disconnect()
|
||||
_state.update { it.copy(connected = false, password = "") }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,152 @@
|
||||
package dev.daubney.scrobbled.data.auth
|
||||
|
||||
import kotlinx.coroutines.test.runTest
|
||||
import okhttp3.mockwebserver.Dispatcher
|
||||
import okhttp3.mockwebserver.MockResponse
|
||||
import okhttp3.mockwebserver.MockWebServer
|
||||
import okhttp3.mockwebserver.RecordedRequest
|
||||
import org.junit.After
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertNotNull
|
||||
import org.junit.Assert.assertNull
|
||||
import org.junit.Assert.fail
|
||||
import org.junit.Before
|
||||
import org.junit.Test
|
||||
|
||||
class FakeStore : CredentialStore {
|
||||
var saved: Credentials? = null
|
||||
override fun load() = saved
|
||||
override fun save(credentials: Credentials) { saved = credentials }
|
||||
override fun clear() { saved = null }
|
||||
}
|
||||
|
||||
class AuthRepositoryTest {
|
||||
private lateinit var server: MockWebServer
|
||||
private val store = FakeStore()
|
||||
private val requests = mutableListOf<String>()
|
||||
private var existingApps = """[]"""
|
||||
private var loginResponse = MockResponse().setBody("""{"token":"bearer1","user":{"id":1,"username":"alice"}}""")
|
||||
private var sessionResponse = MockResponse().setBody("""{"session":{"name":"alice","key":"sess1"}}""")
|
||||
|
||||
private lateinit var repo: DefaultAuthRepository
|
||||
|
||||
@Before
|
||||
fun setUp() {
|
||||
server = MockWebServer().apply {
|
||||
dispatcher = object : Dispatcher() {
|
||||
override fun dispatch(request: RecordedRequest): MockResponse {
|
||||
requests += "${request.method} ${request.path}"
|
||||
return when {
|
||||
request.path == "/api/v1/auth/login" -> loginResponse
|
||||
request.path == "/api/v1/apps" && request.method == "GET" -> {
|
||||
assertEquals("Bearer bearer1", request.getHeader("Authorization"))
|
||||
MockResponse().setBody(existingApps)
|
||||
}
|
||||
request.path == "/api/v1/apps" ->
|
||||
MockResponse().setResponseCode(201)
|
||||
.setBody("""{"name":"Scrobbled Android","api_key":"newkey","shared_secret":"newsecret","created_at":"x"}""")
|
||||
request.path == "/2.0/" -> sessionResponse
|
||||
else -> MockResponse().setResponseCode(404)
|
||||
}
|
||||
}
|
||||
}
|
||||
start()
|
||||
}
|
||||
repo = DefaultAuthRepository(store)
|
||||
}
|
||||
|
||||
@After
|
||||
fun tearDown() = server.shutdown()
|
||||
|
||||
private val url get() = server.url("/").toString()
|
||||
|
||||
@Test
|
||||
fun connectCreatesAppAndStoresCredentials() = runTest {
|
||||
val creds = repo.connect(url, "alice", "pw")
|
||||
assertEquals(
|
||||
Credentials(url.trimEnd('/'), "alice", "bearer1", "newkey", "newsecret", "sess1"),
|
||||
creds,
|
||||
)
|
||||
assertEquals(creds, store.saved)
|
||||
assertEquals(
|
||||
listOf("POST /api/v1/auth/login", "GET /api/v1/apps", "POST /api/v1/apps", "POST /2.0/"),
|
||||
requests,
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun connectReusesExistingApp() = runTest {
|
||||
existingApps = """[{"name":"Other","api_key":"o","shared_secret":"os","created_at":"x"},
|
||||
{"name":"Scrobbled Android","api_key":"oldkey","shared_secret":"oldsecret","created_at":"x"}]"""
|
||||
val creds = repo.connect(url, "alice", "pw")
|
||||
assertEquals("oldkey", creds.apiKey)
|
||||
assertEquals("oldsecret", creds.apiSecret)
|
||||
assertEquals(false, requests.contains("POST /api/v1/apps"))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun wrongPasswordGivesFriendlyErrorAndStoresNothing() = runTest {
|
||||
loginResponse = MockResponse().setResponseCode(401)
|
||||
.setBody("""{"error":{"code":"invalid_credentials","message":"Bad login"}}""")
|
||||
try {
|
||||
repo.connect(url, "alice", "nope")
|
||||
fail("expected exception")
|
||||
} catch (e: ConnectException) {
|
||||
assertEquals("Wrong username or password", e.message)
|
||||
}
|
||||
assertNull(store.saved)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun sessionFailureIsReportedAndStoresNothing() = runTest {
|
||||
sessionResponse = MockResponse().setResponseCode(403).setBody("""{"error":4,"message":"Authentication Failed"}""")
|
||||
try {
|
||||
repo.connect(url, "alice", "pw")
|
||||
fail("expected exception")
|
||||
} catch (e: ConnectException) {
|
||||
assertEquals("Authentication Failed", e.message)
|
||||
}
|
||||
assertNull(store.saved)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun unreachableServerIsReported() = runTest {
|
||||
val dead = url
|
||||
server.shutdown()
|
||||
try {
|
||||
repo.connect(dead, "alice", "pw")
|
||||
fail("expected exception")
|
||||
} catch (e: ConnectException) {
|
||||
assertNotNull(e.message)
|
||||
assert(e.message!!.startsWith("Couldn't reach the server"))
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun invalidUrlIsRejectedBeforeAnyRequest() = runTest {
|
||||
try {
|
||||
repo.connect(" ", "alice", "pw")
|
||||
fail("expected exception")
|
||||
} catch (e: ConnectException) {
|
||||
assertEquals("Enter a valid server address", e.message)
|
||||
}
|
||||
assertEquals(emptyList<String>(), requests)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun disconnectClearsStore() = runTest {
|
||||
repo.connect(url, "alice", "pw")
|
||||
repo.disconnect()
|
||||
assertNull(repo.current())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun normalizeServerUrl() {
|
||||
assertEquals("https://music.example.com", normalizeServerUrl(" music.example.com/ "))
|
||||
assertEquals("http://10.0.2.2:5050", normalizeServerUrl("http://10.0.2.2:5050/"))
|
||||
assertEquals("https://h/sub", normalizeServerUrl("https://h/sub/"))
|
||||
assertNull(normalizeServerUrl(""))
|
||||
assertNull(normalizeServerUrl("ftp://host"))
|
||||
assertNull(normalizeServerUrl("http://"))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,91 @@
|
||||
package dev.daubney.scrobbled.ui.connect
|
||||
|
||||
import dev.daubney.scrobbled.data.auth.AuthRepository
|
||||
import dev.daubney.scrobbled.data.auth.ConnectException
|
||||
import dev.daubney.scrobbled.data.auth.Credentials
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.ExperimentalCoroutinesApi
|
||||
import kotlinx.coroutines.test.UnconfinedTestDispatcher
|
||||
import kotlinx.coroutines.test.resetMain
|
||||
import kotlinx.coroutines.test.setMain
|
||||
import org.junit.After
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Assert.assertNull
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Before
|
||||
import org.junit.Test
|
||||
|
||||
private class FakeAuth(var stored: Credentials? = null, var failure: ConnectException? = null) : AuthRepository {
|
||||
var connectCalls = 0
|
||||
override fun current() = stored
|
||||
override suspend fun connect(serverUrl: String, username: String, password: String): Credentials {
|
||||
connectCalls++
|
||||
failure?.let { throw it }
|
||||
return Credentials(serverUrl, username, "t", "k", "s", "sk").also { stored = it }
|
||||
}
|
||||
override fun disconnect() { stored = null }
|
||||
}
|
||||
|
||||
@OptIn(ExperimentalCoroutinesApi::class)
|
||||
class ConnectViewModelTest {
|
||||
@Before fun setUp() = Dispatchers.setMain(UnconfinedTestDispatcher())
|
||||
@After fun tearDown() = Dispatchers.resetMain()
|
||||
|
||||
private fun filled(vm: ConnectViewModel) {
|
||||
vm.onServerUrl("host"); vm.onUsername("alice"); vm.onPassword("pw")
|
||||
}
|
||||
|
||||
@Test
|
||||
fun startsDisconnectedAndCannotSubmitUntilFilled() {
|
||||
val vm = ConnectViewModel(FakeAuth())
|
||||
assertFalse(vm.state.value.connected)
|
||||
assertFalse(vm.state.value.canSubmit)
|
||||
filled(vm)
|
||||
assertTrue(vm.state.value.canSubmit)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun startsConnectedWhenCredentialsStored() {
|
||||
val vm = ConnectViewModel(FakeAuth(Credentials("https://h", "a", "t", "k", "s", "sk")))
|
||||
assertTrue(vm.state.value.connected)
|
||||
assertEquals("https://h", vm.state.value.serverUrl)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun successfulConnectClearsPassword() {
|
||||
val vm = ConnectViewModel(FakeAuth())
|
||||
filled(vm)
|
||||
vm.connect()
|
||||
assertTrue(vm.state.value.connected)
|
||||
assertEquals("", vm.state.value.password)
|
||||
assertFalse(vm.state.value.busy)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun failureShowsErrorAndStaysDisconnected() {
|
||||
val vm = ConnectViewModel(FakeAuth(failure = ConnectException("Wrong username or password")))
|
||||
filled(vm)
|
||||
vm.connect()
|
||||
assertEquals("Wrong username or password", vm.state.value.error)
|
||||
assertFalse(vm.state.value.connected)
|
||||
vm.onPassword("again")
|
||||
assertNull(vm.state.value.error)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun connectIgnoredWhenFormIncomplete() {
|
||||
val auth = FakeAuth()
|
||||
ConnectViewModel(auth).connect()
|
||||
assertEquals(0, auth.connectCalls)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun disconnectReturnsToForm() {
|
||||
val auth = FakeAuth(Credentials("https://h", "a", "t", "k", "s", "sk"))
|
||||
val vm = ConnectViewModel(auth)
|
||||
vm.disconnect()
|
||||
assertFalse(vm.state.value.connected)
|
||||
assertNull(auth.stored)
|
||||
}
|
||||
}
|
||||
@@ -16,6 +16,7 @@ coroutines = "1.10.2"
|
||||
[libraries]
|
||||
androidx-core-ktx = { group = "androidx.core", name = "core-ktx", version.ref = "coreKtx" }
|
||||
androidx-activity-compose = { group = "androidx.activity", name = "activity-compose", version.ref = "activityCompose" }
|
||||
androidx-lifecycle-viewmodel-compose = { group = "androidx.lifecycle", name = "lifecycle-viewmodel-compose", version.ref = "lifecycle" }
|
||||
androidx-lifecycle-runtime-compose = { group = "androidx.lifecycle", name = "lifecycle-runtime-compose", version.ref = "lifecycle" }
|
||||
androidx-compose-bom = { group = "androidx.compose", name = "compose-bom", version.ref = "composeBom" }
|
||||
androidx-compose-ui = { group = "androidx.compose.ui", name = "ui" }
|
||||
|
||||
Reference in new issue
Block a user