Skip to content

Colota - Android GPS Location tracker

feat(auth): add encrypted auth storage and settings screen

Max Dietrichd308b48c1e97
diff --git a/App.tsx b/App.tsx
index 469603da..fb11280f 100644
--- a/App.tsx
+++ b/App.tsx
@@ -14,6 +14,7 @@ import {
DashboardScreen,
SettingsScreen,
ApiSettingsScreen,
+ AuthSettingsScreen,
GeofenceScreen,
DataManagementScreen,
LocationInspectorScreen,
@@ -39,6 +40,11 @@ const SCREEN_CONFIG = [
component: ApiSettingsScreen,
title: "API Config",
},
+ {
+ name: "Auth Settings",
+ component: AuthSettingsScreen,
+ title: "Auth Settings",
+ },
{
name: "Geofences",
component: GeofenceScreen,
diff --git a/android/app/build.gradle b/android/app/build.gradle
index 4cabc75a..7d30d352 100644
--- a/android/app/build.gradle
+++ b/android/app/build.gradle
@@ -146,6 +146,7 @@ dependencies {
implementation("com.facebook.react:react-android")
implementation 'com.google.android.gms:play-services-location:21.0.1'
implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-android:1.7.3'
+ implementation 'androidx.security:security-crypto:1.1.0'
if (isHermesEnabled) {
implementation("com.facebook.react:hermes-android")
diff --git a/android/app/src/main/java/com/colota/BootReceiver.kt b/android/app/src/main/java/com/colota/BootReceiver.kt
index fa097af2..92202759 100644
--- a/android/app/src/main/java/com/colota/BootReceiver.kt
+++ b/android/app/src/main/java/com/colota/BootReceiver.kt
@@ -99,8 +99,14 @@ class LocationBootReceiver : BroadcastReceiver() {
}
// Load config using ServiceConfig (eliminates duplication)
- val config = ServiceConfig.fromDatabase(dbHelper)
-
+ var config = ServiceConfig.fromDatabase(dbHelper)
+
+ // Override endpoint from encrypted storage if available
+ val secureEndpoint = SecureStorageHelper.getInstance(context).getEndpoint()
+ if (!secureEndpoint.isNullOrBlank()) {
+ config = config.copy(endpoint = secureEndpoint)
+ }
+
// Create service intent with config
val serviceIntent = Intent(context, LocationForegroundService::class.java)
config.toIntent(serviceIntent)
diff --git a/android/app/src/main/java/com/colota/LocationForegroundService.kt b/android/app/src/main/java/com/colota/LocationForegroundService.kt
index f73902c8..460273ff 100644
--- a/android/app/src/main/java/com/colota/LocationForegroundService.kt
+++ b/android/app/src/main/java/com/colota/LocationForegroundService.kt
@@ -27,6 +27,7 @@ class LocationForegroundService : Service() {
private lateinit var deviceInfoHelper: DeviceInfoHelper
private lateinit var networkManager: NetworkManager
private lateinit var geofenceHelper: GeofenceHelper
+ private lateinit var secureStorage: SecureStorageHelper
// Properly manage scope lifecycle to prevent memory leak
private var serviceScope: CoroutineScope? = null
@@ -60,6 +61,7 @@ class LocationForegroundService : Service() {
// --- Configuration (use ServiceConfig) ---
private lateinit var config: ServiceConfig
private var fieldMap: Map<String, String>? = null
+ private var authHeaders: Map<String, String> = emptyMap()
private var consecutiveFailures = 0
private val CHANNEL_ID = "location_service_channel"
@@ -91,6 +93,7 @@ class LocationForegroundService : Service() {
deviceInfoHelper = DeviceInfoHelper(this)
networkManager = NetworkManager(this)
geofenceHelper = GeofenceHelper(this)
+ secureStorage = SecureStorageHelper.getInstance(this)
createNotificationChannel()
}
@@ -571,7 +574,8 @@ class LocationForegroundService : Service() {
async {
val success = networkManager.sendToEndpoint(
JSONObject(item.payload),
- endpoint
+ endpoint,
+ authHeaders
)
item.queueId to success
}
@@ -643,7 +647,7 @@ class LocationForegroundService : Service() {
// Immediate send mode (syncInterval = 0)
if (config.syncIntervalSeconds == 0) {
Log.d(TAG, "Instant send")
- val success = networkManager.sendToEndpoint(payload, endpoint)
+ val success = networkManager.sendToEndpoint(payload, endpoint, authHeaders)
if (success) {
dbHelper.removeFromQueueByLocationId(locationId)
@@ -871,7 +875,16 @@ class LocationForegroundService : Service() {
} else {
ServiceConfig.fromDatabase(dbHelper)
}
-
+
+ // Override endpoint from encrypted storage if available
+ val secureEndpoint = secureStorage.getEndpoint()
+ if (!secureEndpoint.isNullOrBlank()) {
+ config = config.copy(endpoint = secureEndpoint)
+ }
+
+ // Load auth headers from encrypted storage
+ authHeaders = secureStorage.getAuthHeaders()
+
// Parse fieldMap separately (remains as Map for payload building)
config.fieldMap?.let {
if (it.isNotBlank()) fieldMap = locationUtils.parseFieldMap(it)
diff --git a/android/app/src/main/java/com/colota/LocationServiceModule.kt b/android/app/src/main/java/com/colota/LocationServiceModule.kt
index fbaa4d29..faf545cb 100644
--- a/android/app/src/main/java/com/colota/LocationServiceModule.kt
+++ b/android/app/src/main/java/com/colota/LocationServiceModule.kt
@@ -29,8 +29,9 @@ class LocationServiceModule(reactContext: ReactApplicationContext) :
private val locationUtils = LocationUtils(reactContext)
private val dbHelper = DatabaseHelper.getInstance(reactContext)
private val fileOps = FileOperations(reactContext)
- private val deviceInfo = DeviceInfoHelper(reactContext)
+ private val deviceInfo = DeviceInfoHelper(reactContext)
private val geofenceHelper = GeofenceHelper(reactContext)
+ private val secureStorage = SecureStorageHelper.getInstance(reactContext)
// Coroutine scope for async operations
private val moduleScope = CoroutineScope(Dispatchers.IO + SupervisorJob())
@@ -570,8 +571,55 @@ class LocationServiceModule(reactContext: ReactApplicationContext) :
executeAsync(promise) { fileOps.deleteFile(filePath) }
@ReactMethod
- fun getCacheDirectory(promise: Promise) =
+ fun getCacheDirectory(promise: Promise) =
executeAsync(promise) { fileOps.getCacheDirectory() }
+
+ // ==============================================================
+ // SECURE STORAGE (Delegated to SecureStorageHelper)
+ // ==============================================================
+
+ @ReactMethod
+ fun getAllAuthConfig(promise: Promise) = executeAsync(promise) {
+ Arguments.createMap().apply {
+ putString("authType", secureStorage.getString(SecureStorageHelper.KEY_AUTH_TYPE, "none"))
+ putString("username", secureStorage.getString(SecureStorageHelper.KEY_USERNAME, ""))
+ putString("password", secureStorage.getString(SecureStorageHelper.KEY_PASSWORD, ""))
+ putString("bearerToken", secureStorage.getString(SecureStorageHelper.KEY_BEARER_TOKEN, ""))
+ putString("endpoint", secureStorage.getString(SecureStorageHelper.KEY_ENDPOINT, ""))
+ putString("customHeaders", secureStorage.getString(SecureStorageHelper.KEY_CUSTOM_HEADERS, "{}"))
+ }
+ }
+
+ @ReactMethod
+ fun saveAuthConfig(config: ReadableMap, promise: Promise) = executeAsync(promise) {
+ config.getString("authType")?.let {
+ secureStorage.putString(SecureStorageHelper.KEY_AUTH_TYPE, it)
+ }
+ config.getString("username")?.let {
+ secureStorage.putString(SecureStorageHelper.KEY_USERNAME, it)
+ }
+ config.getString("password")?.let {
+ secureStorage.putString(SecureStorageHelper.KEY_PASSWORD, it)
+ }
+ config.getString("bearerToken")?.let {
+ secureStorage.putString(SecureStorageHelper.KEY_BEARER_TOKEN, it)
+ }
+ config.getString("endpoint")?.let {
+ secureStorage.putString(SecureStorageHelper.KEY_ENDPOINT, it)
+ }
+ config.getString("customHeaders")?.let {
+ secureStorage.putString(SecureStorageHelper.KEY_CUSTOM_HEADERS, it)
+ }
+ true
+ }
+
+ @ReactMethod
+ fun getAuthHeaders(promise: Promise) = executeAsync(promise) {
+ val headers = secureStorage.getAuthHeaders()
+ Arguments.createMap().apply {
+ headers.forEach { (k, v) -> putString(k, v) }
+ }
+ }
}
// Extension functions for safer ReadableMap access
diff --git a/android/app/src/main/java/com/colota/NetworkManager.kt b/android/app/src/main/java/com/colota/NetworkManager.kt
index 45d5f1d5..2a4f3e03 100644
--- a/android/app/src/main/java/com/colota/NetworkManager.kt
+++ b/android/app/src/main/java/com/colota/NetworkManager.kt
@@ -32,7 +32,11 @@ class NetworkManager(private val context: Context) {
/**
* Executes an asynchronous POST request to the server.
*/
- suspend fun sendToEndpoint(payload: JSONObject, endpoint: String): Boolean = withContext(Dispatchers.IO) {
+ suspend fun sendToEndpoint(
+ payload: JSONObject,
+ endpoint: String,
+ extraHeaders: Map<String, String> = emptyMap()
+ ): Boolean = withContext(Dispatchers.IO) {
if (endpoint.isBlank()) {
if (BuildConfig.DEBUG) Log.d(TAG, "Empty endpoint provided")
return@withContext false
@@ -62,12 +66,28 @@ class NetworkManager(private val context: Context) {
requestMethod = "POST"
setRequestProperty("Content-Type", "application/json; charset=UTF-8")
setRequestProperty("Accept", "application/json")
+ extraHeaders.forEach { (key, value) ->
+ setRequestProperty(key, value)
+ }
doOutput = true
connectTimeout = CONNECTION_TIMEOUT
readTimeout = READ_TIMEOUT
useCaches = false
}
+ // Log request details
+ if (BuildConfig.DEBUG) {
+ Log.d(TAG, "=== HTTP REQUEST ===")
+ Log.d(TAG, "Endpoint: $endpoint")
+ Log.d(TAG, "Method: POST")
+ Log.d(TAG, "Headers:")
+ connection.requestProperties.forEach { (key, values) ->
+ Log.d(TAG, "$key: ${values.joinToString()}")
+ }
+ Log.d(TAG, "Body: ${payload.toString(2)}") // Pretty print JSON
+ Log.d(TAG, "===================")
+ }
+
// Write payload
val bodyBytes = payload.toString().toByteArray(StandardCharsets.UTF_8)
connection.setFixedLengthStreamingMode(bodyBytes.size)
diff --git a/android/app/src/main/java/com/colota/SecureStorageHelper.kt b/android/app/src/main/java/com/colota/SecureStorageHelper.kt
new file mode 100644
index 00000000..a918b4f5
--- /dev/null
+++ b/android/app/src/main/java/com/colota/SecureStorageHelper.kt
@@ -0,0 +1,119 @@
+/**
+ * Copyright (C) 2026 Max Dietrich
+ * Licensed under the GNU AGPLv3. See LICENSE in the project root for details.
+ */
+
+package com.Colota
+
+import android.content.Context
+import android.content.SharedPreferences
+import android.util.Base64
+import android.util.Log
+import androidx.security.crypto.EncryptedSharedPreferences
+import androidx.security.crypto.MasterKey
+import org.json.JSONObject
+
+/**
+ * Singleton wrapper around EncryptedSharedPreferences for storing
+ * sensitive connection data (credentials, tokens, headers, endpoint).
+ */
+class SecureStorageHelper private constructor(context: Context) {
+
+ companion object {
+ private const val TAG = "SecureStorageHelper"
+ private const val PREFS_NAME = "colota_secure_prefs"
+
+ const val KEY_AUTH_TYPE = "auth_type"
+ const val KEY_USERNAME = "auth_username"
+ const val KEY_PASSWORD = "auth_password"
+ const val KEY_BEARER_TOKEN = "auth_bearer_token"
+ const val KEY_ENDPOINT = "endpoint"
+ const val KEY_CUSTOM_HEADERS = "custom_headers"
+
+ @Volatile
+ private var INSTANCE: SecureStorageHelper? = null
+
+ @JvmStatic
+ fun getInstance(context: Context): SecureStorageHelper {
+ return INSTANCE ?: synchronized(this) {
+ INSTANCE ?: SecureStorageHelper(context.applicationContext).also {
+ INSTANCE = it
+ }
+ }
+ }
+ }
+
+ private val prefs: SharedPreferences
+
+ init {
+ val masterKey = MasterKey.Builder(context.applicationContext)
+ .setKeyScheme(MasterKey.KeyScheme.AES256_GCM)
+ .build()
+
+ prefs = EncryptedSharedPreferences.create(
+ context.applicationContext,
+ PREFS_NAME,
+ masterKey,
+ EncryptedSharedPreferences.PrefKeyEncryptionScheme.AES256_SIV,
+ EncryptedSharedPreferences.PrefValueEncryptionScheme.AES256_GCM
+ )
+ }
+
+ fun getString(key: String, default: String? = null): String? = prefs.getString(key, default)
+
+ fun putString(key: String, value: String) {
+ prefs.edit().putString(key, value).apply()
+ }
+
+ fun remove(key: String) {
+ prefs.edit().remove(key).apply()
+ }
+
+ /**
+ * Builds the full set of auth + custom headers for HTTP requests.
+ */
+ fun getAuthHeaders(): Map<String, String> {
+ val headers = mutableMapOf<String, String>()
+
+ when (getString(KEY_AUTH_TYPE, "none")) {
+ "basic" -> {
+ val user = getString(KEY_USERNAME, "") ?: ""
+ val pass = getString(KEY_PASSWORD, "") ?: ""
+ if (user.isNotBlank()) {
+ val encoded = Base64.encodeToString(
+ "$user:$pass".toByteArray(),
+ Base64.NO_WRAP
+ )
+ headers["Authorization"] = "Basic $encoded"
+ }
+ }
+ "bearer" -> {
+ val token = getString(KEY_BEARER_TOKEN, "") ?: ""
+ if (token.isNotBlank()) {
+ headers["Authorization"] = "Bearer $token"
+ }
+ }
+ }
+
+ val customJson = getString(KEY_CUSTOM_HEADERS, null)
+ if (!customJson.isNullOrBlank()) {
+ try {
+ val jsonObj = JSONObject(customJson)
+ val keys = jsonObj.keys()
+ while (keys.hasNext()) {
+ val k = keys.next()
+ val v = jsonObj.getString(k)
+ if (k.isNotBlank() && v.isNotBlank()) {
+ headers[k] = v
+ }
+ }
+ } catch (e: Exception) {
+ Log.w(TAG, "Failed to parse custom headers", e)
+ }
+ }
+
+ return headers
+ }
+
+ fun getEndpoint(): String? = getString(KEY_ENDPOINT, null)
+}
diff --git a/src/components/features/settings/ServerConnection.tsx b/src/components/features/settings/ServerConnection.tsx
index edb18760..6ee3c53a 100644
--- a/src/components/features/settings/ServerConnection.tsx
+++ b/src/components/features/settings/ServerConnection.tsx
@@ -9,6 +9,7 @@ import { useFocusEffect } from "@react-navigation/native";
import { useTheme } from "../../../hooks/useTheme";
import { useTracking } from "../../../contexts/TrackingProvider";
import { ServerStatus, ServerConnectionProps } from "../../../types/global";
+import NativeLocationService from "../../../services/NativeLocationService";
const SERVER_TIMEOUT = 5000;
const SERVER_CHECK_INTERVAL = 5 * 60 * 1000;
@@ -46,12 +47,20 @@ export function ServerConnection({
const timeoutId = setTimeout(() => controller.abort(), SERVER_TIMEOUT);
try {
+ let authHeaders: Record<string, string> = {};
+ try {
+ authHeaders = await NativeLocationService.getAuthHeaders();
+ } catch {
+ // proceed without auth headers
+ }
+
// Strategy 1: Try dedicated health endpoint
const healthUrl = endpoint.replace(/\/api\/locations$/, "/health");
let response = await fetch(healthUrl, {
method: "HEAD",
signal: controller.signal,
+ headers: authHeaders,
});
// Strategy 2: If health endpoint doesn't exist, try HEAD on main endpoint
@@ -59,6 +68,7 @@ export function ServerConnection({
response = await fetch(endpoint, {
method: "HEAD",
signal: controller.signal,
+ headers: authHeaders,
});
}
@@ -70,6 +80,7 @@ export function ServerConnection({
response = await fetch(rootUrl, {
method: "GET",
signal: controller.signal,
+ headers: authHeaders,
});
}
}
diff --git a/src/screens/AuthSettingsScreen.tsx b/src/screens/AuthSettingsScreen.tsx
new file mode 100644
index 00000000..3641b230
--- /dev/null
+++ b/src/screens/AuthSettingsScreen.tsx
@@ -0,0 +1,541 @@
+/**
+ * Copyright (C) 2026 Max Dietrich
+ * Licensed under the GNU AGPLv3. See LICENSE in the project root for details.
+ */
+
+import React, { useState, useCallback, useEffect, useRef } from "react";
+import {
+ Text,
+ StyleSheet,
+ TextInput,
+ View,
+ ScrollView,
+ TouchableOpacity,
+} from "react-native";
+import {
+ AuthConfig,
+ AuthType,
+ DEFAULT_AUTH_CONFIG,
+ ScreenProps,
+} from "../types/global";
+import { useTheme } from "../hooks/useTheme";
+import { useTracking } from "../contexts/TrackingProvider";
+import {
+ SectionTitle,
+ FloatingSaveIndicator,
+ Container,
+ Card,
+ Divider,
+} from "../components";
+import NativeLocationService from "../services/NativeLocationService";
+
+const AUTOSAVE_DEBOUNCE_MS = 1500;
+
+const AUTH_TYPES: { value: AuthType; label: string }[] = [
+ { value: "none", label: "None" },
+ { value: "basic", label: "Basic Auth" },
+ { value: "bearer", label: "Bearer Token" },
+];
+
+/**
+ * Screen for configuring endpoint authentication and custom headers.
+ */
+export function AuthSettingsScreen({}: ScreenProps) {
+ const { colors } = useTheme();
+ const { restartTracking, settings } = useTracking();
+
+ const [config, setConfig] = useState<AuthConfig>(DEFAULT_AUTH_CONFIG);
+ const [loading, setLoading] = useState(true);
+ const [saving, setSaving] = useState(false);
+ const [saveSuccess, setSaveSuccess] = useState(false);
+ const saveTimeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);
+
+ // Load config on mount
+ useEffect(() => {
+ (async () => {
+ try {
+ const saved = await NativeLocationService.getAuthConfig();
+ setConfig(saved);
+ } catch (err) {
+ console.error("[AuthSettingsScreen] Failed to load auth config:", err);
+ } finally {
+ setLoading(false);
+ }
+ })();
+ }, []);
+
+ // Cleanup
+ useEffect(() => {
+ return () => {
+ if (saveTimeoutRef.current) clearTimeout(saveTimeoutRef.current);
+ };
+ }, []);
+
+ const saveConfig = useCallback(
+ async (newConfig: AuthConfig) => {
+ setSaving(true);
+ try {
+ await NativeLocationService.saveAuthConfig(newConfig);
+ await restartTracking(settings);
+ setSaveSuccess(true);
+ setTimeout(() => setSaveSuccess(false), 2000);
+ } catch (err) {
+ console.error("[AuthSettingsScreen] Save failed:", err);
+ } finally {
+ setSaving(false);
+ }
+ },
+ [restartTracking, settings]
+ );
+
+ const debouncedSave = useCallback(
+ (newConfig: AuthConfig) => {
+ if (saveTimeoutRef.current) clearTimeout(saveTimeoutRef.current);
+ saveTimeoutRef.current = setTimeout(
+ () => saveConfig(newConfig),
+ AUTOSAVE_DEBOUNCE_MS
+ );
+ },
+ [saveConfig]
+ );
+
+ const updateConfig = useCallback(
+ (partial: Partial<AuthConfig>) => {
+ const next = { ...config, ...partial };
+ setConfig(next);
+ debouncedSave(next);
+ },
+ [config, debouncedSave]
+ );
+
+ const handleAuthTypeChange = useCallback(
+ (authType: AuthType) => {
+ const next = { ...config, authType };
+ setConfig(next);
+ // Immediate save for auth type change
+ if (saveTimeoutRef.current) clearTimeout(saveTimeoutRef.current);
+ saveConfig(next);
+ },
+ [config, saveConfig]
+ );
+
+ // Custom headers as array for rendering
+ const headerEntries = Object.entries(config.customHeaders);
+
+ const addHeader = useCallback(() => {
+ updateConfig({
+ customHeaders: { ...config.customHeaders, "": "" },
+ });
+ }, [config, updateConfig]);
+
+ const updateHeaderKey = useCallback(
+ (oldKey: string, newKey: string, index: number) => {
+ const entries = Object.entries(config.customHeaders);
+ entries[index] = [newKey, entries[index][1]];
+ const newHeaders = Object.fromEntries(entries);
+ updateConfig({ customHeaders: newHeaders });
+ },
+ [config, updateConfig]
+ );
+
+ const updateHeaderValue = useCallback(
+ (key: string, value: string, index: number) => {
+ const entries = Object.entries(config.customHeaders);
+ entries[index] = [entries[index][0], value];
+ const newHeaders = Object.fromEntries(entries);
+ updateConfig({ customHeaders: newHeaders });
+ },
+ [config, updateConfig]
+ );
+
+ const removeHeader = useCallback(
+ (index: number) => {
+ const entries = Object.entries(config.customHeaders);
+ entries.splice(index, 1);
+ const next = { ...config, customHeaders: Object.fromEntries(entries) };
+ setConfig(next);
+ if (saveTimeoutRef.current) clearTimeout(saveTimeoutRef.current);
+ saveConfig(next);
+ },
+ [config, saveConfig]
+ );
+
+ if (loading) {
+ return (
+ <Container>
+ <View style={styles.loadingContainer}>
+ <Text style={[styles.loadingText, { color: colors.textSecondary }]}>
+ Loading...
+ </Text>
+ </View>
+ </Container>
+ );
+ }
+
+ return (
+ <Container>
+ <ScrollView
+ contentContainerStyle={styles.scrollContent}
+ keyboardShouldPersistTaps="handled"
+ showsVerticalScrollIndicator={false}
+ >
+ {/* Header */}
+ <View style={styles.header}>
+ <Text style={[styles.title, { color: colors.text }]}>
+ Authentication & Headers
+ </Text>
+ <Text style={[styles.subtitle, { color: colors.textSecondary }]}>
+ Secure your endpoint connection
+ </Text>
+ </View>
+
+ {/* Authentication Section */}
+ <View style={styles.section}>
+ <SectionTitle>Authentication</SectionTitle>
+ <Card>
+ {/* Auth type picker */}
+ <View style={styles.chipRow}>
+ {AUTH_TYPES.map(({ value, label }) => {
+ const isSelected = config.authType === value;
+ return (
+ <TouchableOpacity
+ key={value}
+ style={[
+ styles.chip,
+ {
+ borderColor: colors.border,
+ backgroundColor: colors.background,
+ },
+ isSelected && {
+ borderColor: colors.primary,
+ backgroundColor: colors.primary + "20",
+ },
+ ]}
+ onPress={() => handleAuthTypeChange(value)}
+ activeOpacity={0.7}
+ >
+ <Text
+ style={[
+ styles.chipText,
+ {
+ color: isSelected ? colors.primary : colors.text,
+ },
+ ]}
+ >
+ {label}
+ </Text>
+ </TouchableOpacity>
+ );
+ })}
+ </View>
+
+ {/* Basic Auth fields */}
+ {config.authType === "basic" && (
+ <>
+ <Divider />
+ <View style={styles.fieldGroup}>
+ <Text style={[styles.fieldLabel, { color: colors.text }]}>
+ Username
+ </Text>
+ <TextInput
+ style={[
+ styles.input,
+ {
+ borderColor: colors.border,
+ color: colors.text,
+ backgroundColor: colors.background,
+ },
+ ]}
+ value={config.username}
+ onChangeText={(v) => updateConfig({ username: v })}
+ placeholder="Username"
+ placeholderTextColor={colors.placeholder}
+ autoCapitalize="none"
+ autoCorrect={false}
+ />
+
+ <Text
+ style={[
+ styles.fieldLabel,
+ styles.fieldLabelSpaced,
+ { color: colors.text },
+ ]}
+ >
+ Password
+ </Text>
+ <TextInput
+ style={[
+ styles.input,
+ {
+ borderColor: colors.border,
+ color: colors.text,
+ backgroundColor: colors.background,
+ },
+ ]}
+ value={config.password}
+ onChangeText={(v) => updateConfig({ password: v })}
+ placeholder="Password"
+ placeholderTextColor={colors.placeholder}
+ autoCapitalize="none"
+ autoCorrect={false}
+ secureTextEntry
+ />
+ </View>
+ </>
+ )}
+
+ {/* Bearer Token field */}
+ {config.authType === "bearer" && (
+ <>
+ <Divider />
+ <View style={styles.fieldGroup}>
+ <Text style={[styles.fieldLabel, { color: colors.text }]}>
+ Token
+ </Text>
+ <TextInput
+ style={[
+ styles.input,
+ {
+ borderColor: colors.border,
+ color: colors.text,
+ backgroundColor: colors.background,
+ },
+ ]}
+ value={config.bearerToken}
+ onChangeText={(v) => updateConfig({ bearerToken: v })}
+ placeholder="Bearer token"
+ placeholderTextColor={colors.placeholder}
+ autoCapitalize="none"
+ autoCorrect={false}
+ secureTextEntry
+ />
+ </View>
+ </>
+ )}
+ </Card>
+ </View>
+
+ {/* Custom Headers Section */}
+ <View style={styles.section}>
+ <SectionTitle>Custom Headers</SectionTitle>
+ <Card>
+ {headerEntries.length === 0 ? (
+ <Text style={[styles.emptyHint, { color: colors.textSecondary }]}>
+ No custom headers configured
+ </Text>
+ ) : (
+ headerEntries.map(([key, value], index) => (
+ <View key={index}>
+ {index > 0 && <Divider />}
+ <View style={styles.headerRow}>
+ <View style={styles.headerInputs}>
+ <TextInput
+ style={[
+ styles.headerInput,
+ {
+ borderColor: colors.border,
+ color: colors.text,
+ backgroundColor: colors.background,
+ },
+ ]}
+ value={key}
+ onChangeText={(v) => updateHeaderKey(key, v, index)}
+ placeholder="Header name"
+ placeholderTextColor={colors.placeholder}
+ autoCapitalize="none"
+ autoCorrect={false}
+ />
+ <TextInput
+ style={[
+ styles.headerInput,
+ {
+ borderColor: colors.border,
+ color: colors.text,
+ backgroundColor: colors.background,
+ },
+ ]}
+ value={value}
+ onChangeText={(v) => updateHeaderValue(key, v, index)}
+ placeholder="Value"
+ placeholderTextColor={colors.placeholder}
+ autoCapitalize="none"
+ autoCorrect={false}
+ />
+ </View>
+ <TouchableOpacity
+ onPress={() => removeHeader(index)}
+ style={[
+ styles.removeButton,
+ { backgroundColor: colors.error + "15" },
+ ]}
+ activeOpacity={0.7}
+ >
+ <Text
+ style={[
+ styles.removeButtonText,
+ { color: colors.error },
+ ]}
+ >
+ X
+ </Text>
+ </TouchableOpacity>
+ </View>
+ </View>
+ ))
+ )}
+
+ {headerEntries.length > 0 && <Divider />}
+
+ <TouchableOpacity
+ style={[styles.addButton, { borderColor: colors.primary }]}
+ onPress={addHeader}
+ activeOpacity={0.7}
+ >
+ <Text style={[styles.addButtonText, { color: colors.primary }]}>
+ + Add Header
+ </Text>
+ </TouchableOpacity>
+
+ <Text style={[styles.hint, { color: colors.textSecondary }]}>
+ e.g., CF-Access-Client-Id for Cloudflare Access
+ </Text>
+ </Card>
+ </View>
+
+ {/* Footer */}
+ <View style={styles.footer}>
+ <Text style={[styles.footerText, { color: colors.textLight }]}>
+ Credentials are stored encrypted on device
+ </Text>
+ </View>
+ </ScrollView>
+
+ <FloatingSaveIndicator
+ saving={saving}
+ success={saveSuccess}
+ colors={colors}
+ />
+ </Container>
+ );
+}
+
+const styles = StyleSheet.create({
+ scrollContent: {
+ paddingHorizontal: 20,
+ paddingTop: 16,
+ paddingBottom: 40,
+ },
+ loadingContainer: {
+ flex: 1,
+ justifyContent: "center",
+ alignItems: "center",
+ },
+ loadingText: {
+ fontSize: 15,
+ },
+ header: {
+ marginBottom: 20,
+ },
+ title: {
+ fontSize: 28,
+ fontWeight: "700",
+ letterSpacing: -0.5,
+ marginBottom: 4,
+ },
+ subtitle: {
+ fontSize: 14,
+ lineHeight: 20,
+ },
+ section: {
+ marginBottom: 24,
+ },
+ chipRow: {
+ flexDirection: "row",
+ gap: 10,
+ },
+ chip: {
+ flex: 1,
+ borderWidth: 2,
+ borderRadius: 10,
+ paddingVertical: 12,
+ alignItems: "center",
+ },
+ chipText: {
+ fontSize: 13,
+ fontWeight: "700",
+ },
+ fieldGroup: {
+ marginTop: 4,
+ },
+ fieldLabel: {
+ fontSize: 15,
+ fontWeight: "600",
+ marginBottom: 8,
+ },
+ fieldLabelSpaced: {
+ marginTop: 14,
+ },
+ input: {
+ borderWidth: 1.5,
+ padding: 14,
+ borderRadius: 12,
+ fontSize: 15,
+ },
+ emptyHint: {
+ fontSize: 14,
+ textAlign: "center",
+ paddingVertical: 8,
+ },
+ headerRow: {
+ flexDirection: "row",
+ alignItems: "center",
+ gap: 8,
+ paddingVertical: 8,
+ },
+ headerInputs: {
+ flex: 1,
+ gap: 8,
+ },
+ headerInput: {
+ borderWidth: 1.5,
+ padding: 12,
+ borderRadius: 10,
+ fontSize: 14,
+ },
+ removeButton: {
+ width: 36,
+ height: 36,
+ borderRadius: 18,
+ justifyContent: "center",
+ alignItems: "center",
+ },
+ removeButtonText: {
+ fontSize: 14,
+ fontWeight: "700",
+ },
+ addButton: {
+ paddingVertical: 14,
+ alignItems: "center",
+ borderRadius: 12,
+ borderWidth: 1.5,
+ borderStyle: "dashed",
+ marginTop: 4,
+ },
+ addButtonText: {
+ fontSize: 15,
+ fontWeight: "600",
+ },
+ hint: {
+ fontSize: 12,
+ marginTop: 10,
+ textAlign: "center",
+ },
+ footer: {
+ paddingVertical: 16,
+ alignItems: "center",
+ },
+ footerText: {
+ fontSize: 11,
+ textAlign: "center",
+ },
+});
diff --git a/src/screens/SettingsScreen.tsx b/src/screens/SettingsScreen.tsx
index ca906c78..d1911a56 100644
--- a/src/screens/SettingsScreen.tsx
+++ b/src/screens/SettingsScreen.tsx
@@ -145,6 +145,17 @@ export function SettingsScreen({ navigation }: ScreenProps) {
try {
await setSettings(newSettings);
await restartTracking(newSettings);
+
+ // Sync endpoint to encrypted storage
+ if (newSettings.endpoint) {
+ NativeLocationService.getAuthConfig().then((authConfig) => {
+ NativeLocationService.saveAuthConfig({
+ ...authConfig,
+ endpoint: newSettings.endpoint,
+ });
+ });
+ }
+
setSaveSuccess(true);
setTimeout(() => setSaveSuccess(false), 2000);
} catch (err) {
@@ -297,9 +308,16 @@ export function SettingsScreen({ navigation }: ScreenProps) {
payload[fieldMap.tst] = Math.floor(Date.now() / 1000);
}
+ let authHeaders: Record<string, string> = {};
+ try {
+ authHeaders = await NativeLocationService.getAuthHeaders();
+ } catch {
+ // proceed without auth headers
+ }
+
const response = await fetch(endpointInput, {
method: "POST",
- headers: { "Content-Type": "application/json" },
+ headers: { "Content-Type": "application/json", ...authHeaders },
body: JSON.stringify(payload),
});
@@ -486,6 +504,28 @@ export function SettingsScreen({ navigation }: ScreenProps) {
</Text>
</View>
)}
+
+ <Divider />
+
+ <TouchableOpacity
+ style={styles.linkRow}
+ onPress={() => navigation.navigate("Auth Settings")}
+ activeOpacity={0.6}
+ >
+ <View style={styles.linkContent}>
+ <Text style={[styles.linkLabel, { color: colors.text }]}>
+ Authentication & Headers
+ </Text>
+ <Text
+ style={[styles.linkSub, { color: colors.textSecondary }]}
+ >
+ Basic auth, bearer tokens, custom headers
+ </Text>
+ </View>
+ <Text style={[styles.linkArrow, { color: colors.textLight }]}>
+ ›
+ </Text>
+ </TouchableOpacity>
</>
)}
</Card>
diff --git a/src/screens/index.ts b/src/screens/index.ts
index 888bf5f2..82293c46 100644
--- a/src/screens/index.ts
+++ b/src/screens/index.ts
@@ -4,6 +4,7 @@
*/
export { ApiSettingsScreen } from "./ApiSettingsScreen";
+export { AuthSettingsScreen } from "./AuthSettingsScreen";
export { DashboardScreen } from "./DashboardScreen";
export { DataManagementScreen } from "./DataManagementScreen";
export { ExportDataScreen } from "./ExportDataScreen";
diff --git a/src/services/NativeLocationService.ts b/src/services/NativeLocationService.ts
index 53484724..c238e975 100644
--- a/src/services/NativeLocationService.ts
+++ b/src/services/NativeLocationService.ts
@@ -4,7 +4,7 @@
*/
import { NativeModules } from "react-native";
-import { DatabaseStats, Geofence, Settings } from "../types/global";
+import { AuthConfig, DatabaseStats, Geofence, Settings } from "../types/global";
const { LocationServiceModule, BuildConfigModule } = NativeModules;
@@ -76,9 +76,9 @@ class NativeLocationService {
try {
await LocationServiceModule.startService(config);
- console.log("[NativeLocationService] ✅ Service started");
+ console.log("[NativeLocationService] Service started");
} catch (error) {
- console.error("[NativeLocationService] ❌ Start failed:", error);
+ console.error("[NativeLocationService] Start failed:", error);
throw error;
}
}
@@ -130,10 +130,10 @@ class NativeLocationService {
console.log("[NativeLocationService] Triggering manual flush");
try {
const result = await LocationServiceModule.manualFlush();
- console.log("[NativeLocationService] ✅ Flush completed");
+ console.log("[NativeLocationService] Flush completed");
return result;
} catch (error) {
- console.error("[NativeLocationService] ❌ Flush failed:", error);
+ console.error("[NativeLocationService] Flush failed:", error);
throw error;
}
}
@@ -569,6 +569,49 @@ class NativeLocationService {
this.ensureModule();
return LocationServiceModule.getCacheDirectory();
}
+
+ // ============================================================================
+ // SECURE STORAGE (Auth & Headers)
+ // ============================================================================
+
+ /**
+ * Retrieves the full auth configuration from encrypted storage
+ */
+ static async getAuthConfig(): Promise<AuthConfig> {
+ this.ensureModule();
+ const raw = await LocationServiceModule.getAllAuthConfig();
+ return {
+ authType: raw.authType || "none",
+ username: raw.username || "",
+ password: raw.password || "",
+ bearerToken: raw.bearerToken || "",
+ endpoint: raw.endpoint || "",
+ customHeaders: raw.customHeaders ? JSON.parse(raw.customHeaders) : {},
+ };
+ }
+
+ /**
+ * Saves auth configuration to encrypted storage
+ */
+ static async saveAuthConfig(config: AuthConfig): Promise<boolean> {
+ this.ensureModule();
+ return LocationServiceModule.saveAuthConfig({
+ authType: config.authType,
+ username: config.username,
+ password: config.password,
+ bearerToken: config.bearerToken,
+ endpoint: config.endpoint,
+ customHeaders: JSON.stringify(config.customHeaders),
+ });
+ }
+
+ /**
+ * Returns computed auth + custom headers for HTTP requests
+ */
+ static async getAuthHeaders(): Promise<Record<string, string>> {
+ this.ensureModule();
+ return LocationServiceModule.getAuthHeaders();
+ }
}
export default NativeLocationService;
diff --git a/src/types/global.ts b/src/types/global.ts
index 155a7361..dfd51bd4 100644
--- a/src/types/global.ts
+++ b/src/types/global.ts
@@ -235,6 +235,30 @@ export const DEFAULT_SETTINGS: Settings = {
isOfflineMode: false,
} as const;
+// ============================================================================
+// AUTHENTICATION
+// ============================================================================
+
+export type AuthType = "none" | "basic" | "bearer";
+
+export interface AuthConfig {
+ authType: AuthType;
+ username: string;
+ password: string;
+ bearerToken: string;
+ endpoint: string;
+ customHeaders: Record<string, string>;
+}
+
+export const DEFAULT_AUTH_CONFIG: AuthConfig = {
+ authType: "none",
+ username: "",
+ password: "",
+ bearerToken: "",
+ endpoint: "",
+ customHeaders: {},
+};
+
// ============================================================================
// DATABASE
// ============================================================================