feat: replace server password with API token for authentication across the application
This commit is contained in:
1 parent
a52ded8936
commit
cd72558db8
7 files changed
+44
-44
No files matched your search
@@ -25,16 +25,16 @@ object ApiClient {
|
||||
private val authInterceptor =
|
||||
Interceptor { chain ->
|
||||
val request = chain.request()
|
||||
val password =
|
||||
val apiToken =
|
||||
context?.let {
|
||||
PreferencesManager.getInstance(it).getServerPassword()?.trim()
|
||||
PreferencesManager.getInstance(it).getApiToken()?.trim()
|
||||
}
|
||||
|
||||
val newRequest =
|
||||
if (!password.isNullOrBlank() && password != "\$password") {
|
||||
if (!apiToken.isNullOrBlank() && apiToken != "\$apiToken") {
|
||||
request
|
||||
.newBuilder()
|
||||
.header("Authorization", "Bearer $password")
|
||||
.header("Authorization", "Bearer $apiToken")
|
||||
.build()
|
||||
} else {
|
||||
request
|
||||
|
||||
+7
-7
@@ -70,13 +70,13 @@ class PreferencesManager(
|
||||
_isFirstRunFlow.value = isFirstRun
|
||||
}
|
||||
|
||||
fun getServerPassword(): String? = prefs.getString(KEY_SERVER_PASSWORD, null)
|
||||
fun getApiToken(): String? = prefs.getString(KEY_API_TOKEN, null)
|
||||
|
||||
fun setServerPassword(password: String) {
|
||||
if (password.isBlank()) {
|
||||
prefs.edit().remove(KEY_SERVER_PASSWORD).apply()
|
||||
fun setApiToken(apiToken: String) {
|
||||
if (apiToken.isBlank()) {
|
||||
prefs.edit().remove(KEY_API_TOKEN).apply()
|
||||
} else {
|
||||
prefs.edit().putString(KEY_SERVER_PASSWORD, password).apply()
|
||||
prefs.edit().putString(KEY_API_TOKEN, apiToken).apply()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -89,7 +89,7 @@ class PreferencesManager(
|
||||
prefs
|
||||
.edit()
|
||||
.remove(KEY_SERVER_URL)
|
||||
.remove(KEY_SERVER_PASSWORD)
|
||||
.remove(KEY_API_TOKEN)
|
||||
.remove(KEY_LAST_SYNC_TIMESTAMP)
|
||||
.apply()
|
||||
_serverUrl.value = getServerUrl()
|
||||
@@ -280,7 +280,7 @@ class PreferencesManager(
|
||||
private const val KEY_SERVER_URL = "server_url"
|
||||
private const val KEY_DEVICE_ID = "device_id"
|
||||
private const val KEY_FIRST_RUN = "first_run"
|
||||
private const val KEY_SERVER_PASSWORD = "server_password"
|
||||
private const val KEY_API_TOKEN = "api_token"
|
||||
private const val KEY_LAST_SYNC_TIMESTAMP = "last_sync_timestamp"
|
||||
private const val KEY_THEME_MODE = "theme_mode" // system|light|dark
|
||||
private const val KEY_DYNAMIC_COLOR = "dynamic_color"
|
||||
|
||||
+4
-4
@@ -86,8 +86,8 @@ class SyncRepository(
|
||||
}
|
||||
// If not authenticated, skip making network calls (e.g., after leaving server)
|
||||
val prefMgr = PreferencesManager.getInstance(appContext)
|
||||
val currentPassword = prefMgr.getServerPassword()?.trim()
|
||||
if (currentPassword.isNullOrBlank() || currentPassword == "\$password") {
|
||||
val currentApiToken = prefMgr.getApiToken()?.trim()
|
||||
if (currentApiToken.isNullOrBlank() || currentApiToken == "\$apiToken") {
|
||||
// Quietly skip to avoid spamming server with missing Authorization
|
||||
return@withContext Result.success(Unit)
|
||||
}
|
||||
@@ -193,13 +193,13 @@ class SyncRepository(
|
||||
}
|
||||
if (!response.isSuccessful) {
|
||||
if (response.code() == 401) {
|
||||
// Unauthorized: likely bad/missing password. Reset sync baseline and surface a clear error.
|
||||
// Unauthorized: likely bad/missing API token. Reset sync baseline and surface a clear error.
|
||||
setLastServerSyncTs(0)
|
||||
setLastLocalSyncTs(0)
|
||||
// Apply exponential backoff on repeated auth failures
|
||||
authBackoffMs = if (authBackoffMs == 0L) 2_000L else (authBackoffMs * 2).coerceAtMost(300_000L)
|
||||
authBackoffUntil = System.currentTimeMillis() + authBackoffMs
|
||||
return@withContext Result.failure(Exception("Unauthorized (401). Please verify server password."))
|
||||
return@withContext Result.failure(Exception("Unauthorized (401). Please verify server API token."))
|
||||
}
|
||||
return@withContext Result.failure(Exception("Sync failed: ${response.code()}"))
|
||||
}
|
||||
|
||||
+3
-3
@@ -26,9 +26,9 @@ object NotificationPoller {
|
||||
CoroutineScope(Dispatchers.IO).launch {
|
||||
while (isActive) {
|
||||
try {
|
||||
// Skip if password missing (auth disabled)
|
||||
val pwd = prefs.getServerPassword()?.trim()
|
||||
if (pwd.isNullOrBlank() || pwd == "\$password") {
|
||||
// Skip if API token missing (auth disabled)
|
||||
val apiToken = prefs.getApiToken()?.trim()
|
||||
if (apiToken.isNullOrBlank() || apiToken == "\$apiToken") {
|
||||
delay(2_000)
|
||||
continue
|
||||
}
|
||||
|
||||
+13
-13
@@ -57,8 +57,8 @@ fun ServerSetupScreen(onSetupComplete: () -> Unit) {
|
||||
val viewModel = remember { ServerSetupViewModel(preferencesManager) }
|
||||
|
||||
var serverUrl by remember { mutableStateOf("") }
|
||||
var serverPassword by remember { mutableStateOf("") }
|
||||
var passwordVisible by remember { mutableStateOf(false) }
|
||||
var apiToken by remember { mutableStateOf("") }
|
||||
var tokenVisible by remember { mutableStateOf(false) }
|
||||
val isValidating by viewModel.isValidating.collectAsState()
|
||||
val validationResult by viewModel.validationResult.collectAsState()
|
||||
val validationError by viewModel.validationError.collectAsState()
|
||||
@@ -197,26 +197,26 @@ fun ServerSetupScreen(onSetupComplete: () -> Unit) {
|
||||
)
|
||||
|
||||
OutlinedTextField(
|
||||
value = serverPassword,
|
||||
value = apiToken,
|
||||
onValueChange = {
|
||||
serverPassword = it
|
||||
apiToken = it
|
||||
viewModel.clearValidationState()
|
||||
},
|
||||
label = { Text("Server Password") },
|
||||
placeholder = { Text("Enter server password") },
|
||||
label = { Text("API Token") },
|
||||
placeholder = { Text("Paste API token") },
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
enabled = !isValidating,
|
||||
visualTransformation = if (passwordVisible) VisualTransformation.None else PasswordVisualTransformation(),
|
||||
visualTransformation = if (tokenVisible) VisualTransformation.None else PasswordVisualTransformation(),
|
||||
keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Password),
|
||||
trailingIcon = {
|
||||
IconButton(onClick = { passwordVisible = !passwordVisible }) {
|
||||
IconButton(onClick = { tokenVisible = !tokenVisible }) {
|
||||
Icon(
|
||||
imageVector = if (passwordVisible) Icons.Default.Visibility else Icons.Default.VisibilityOff,
|
||||
contentDescription = if (passwordVisible) "Hide password" else "Show password",
|
||||
imageVector = if (tokenVisible) Icons.Default.Visibility else Icons.Default.VisibilityOff,
|
||||
contentDescription = if (tokenVisible) "Hide token" else "Show token",
|
||||
)
|
||||
}
|
||||
},
|
||||
supportingText = { Text("Server password for authentication") },
|
||||
supportingText = { Text("Generated from the server dashboard's Settings page") },
|
||||
)
|
||||
|
||||
Button(
|
||||
@@ -224,11 +224,11 @@ fun ServerSetupScreen(onSetupComplete: () -> Unit) {
|
||||
if (validationResult == true) {
|
||||
startCompletionFlow()
|
||||
} else {
|
||||
viewModel.validateAndSaveServerUrl(serverUrl.trim(), serverPassword.trim())
|
||||
viewModel.validateAndSaveServerUrl(serverUrl.trim(), apiToken.trim())
|
||||
}
|
||||
},
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
enabled = (serverUrl.isNotBlank() && serverPassword.isNotBlank() && !isValidating) || validationResult == true,
|
||||
enabled = (serverUrl.isNotBlank() && apiToken.isNotBlank() && !isValidating) || validationResult == true,
|
||||
) {
|
||||
if (isValidating) {
|
||||
CircularProgressIndicator(
|
||||
|
||||
+12
-12
@@ -44,7 +44,7 @@ class ServerSetupViewModel(
|
||||
|
||||
fun validateAndSaveServerUrl(
|
||||
url: String,
|
||||
password: String,
|
||||
apiToken: String,
|
||||
) {
|
||||
viewModelScope.launch {
|
||||
_isValidating.value = true
|
||||
@@ -88,15 +88,15 @@ class ServerSetupViewModel(
|
||||
// Ensure it ends with /
|
||||
normalizedUrl = if (normalizedUrl.endsWith("/")) normalizedUrl else "$normalizedUrl/"
|
||||
|
||||
// Validate password is not empty (trim leading/trailing spaces) and not a placeholder
|
||||
val trimmedPassword = password.trim()
|
||||
if (trimmedPassword.isBlank()) {
|
||||
_validationError.value = "Password cannot be empty"
|
||||
// Validate API token is not empty (trim leading/trailing spaces) and not a placeholder
|
||||
val trimmedToken = apiToken.trim()
|
||||
if (trimmedToken.isBlank()) {
|
||||
_validationError.value = "API token cannot be empty"
|
||||
_isValidating.value = false
|
||||
return@launch
|
||||
}
|
||||
if (trimmedPassword == "\$password") {
|
||||
_validationError.value = "Enter the actual server password, not the placeholder $password"
|
||||
if (trimmedToken == "\$apiToken") {
|
||||
_validationError.value = "Enter the actual API token, not the placeholder $apiToken"
|
||||
_isValidating.value = false
|
||||
return@launch
|
||||
}
|
||||
@@ -195,13 +195,13 @@ class ServerSetupViewModel(
|
||||
}
|
||||
}
|
||||
|
||||
// Now validate the password by making an authenticated request
|
||||
// Now validate the API token by making an authenticated request
|
||||
val testUrl = "${finalUrl}lists"
|
||||
val authRequest =
|
||||
Request
|
||||
.Builder()
|
||||
.url(testUrl)
|
||||
.header("Authorization", "Bearer $trimmedPassword")
|
||||
.header("Authorization", "Bearer $trimmedToken")
|
||||
.get()
|
||||
.build()
|
||||
|
||||
@@ -212,16 +212,16 @@ class ServerSetupViewModel(
|
||||
}
|
||||
|
||||
if (authResponse.isSuccessful) {
|
||||
// Password is valid, save both URL and password
|
||||
// Token is valid, save both URL and API token
|
||||
preferencesManager.setServerUrl(finalUrl)
|
||||
preferencesManager.setServerPassword(trimmedPassword)
|
||||
preferencesManager.setApiToken(trimmedToken)
|
||||
// Reset sync baseline for a fresh initial sync on new server
|
||||
preferencesManager.clearSyncState()
|
||||
preferencesManager.setIsFirstRun(false)
|
||||
ApiClient.setBaseUrl(finalUrl)
|
||||
_validationResult.value = true
|
||||
} else if (authResponse.code == 401) {
|
||||
_validationError.value = "Invalid password. Please check and try again."
|
||||
_validationError.value = "Invalid API token. Please check and try again."
|
||||
} else {
|
||||
val errorMessage =
|
||||
when (authResponse.code) {
|
||||
|
||||
+1
-1
@@ -626,7 +626,7 @@ fun SettingsScreen(
|
||||
CollabTableDatabase.clearDatabase(context)
|
||||
}
|
||||
|
||||
// Clear preferences (URL, password, last sync)
|
||||
// Clear preferences (URL, API token, last sync)
|
||||
preferencesManager.clearServerSettings()
|
||||
preferencesManager.setIsFirstRun(true)
|
||||
// Clear in-memory logs as part of local data
|
||||
|
||||
Reference in new issue
Block a user