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