Colota - Android GPS Location tracker
Fix header bugs and clean up AuthSettingsScreen
Max Dietrichfa9c79eef9fc
diff --git a/apps/mobile/src/screens/AuthSettingsScreen.tsx b/apps/mobile/src/screens/AuthSettingsScreen.tsxindex f1108d67..69348bbf 100644--- a/apps/mobile/src/screens/AuthSettingsScreen.tsx+++ b/apps/mobile/src/screens/AuthSettingsScreen.tsx@@ -3,14 +3,14 @@* Licensed under the GNU AGPLv3. See LICENSE in the project root for details.*/-import React, { useState, useCallback, useEffect } from "react"+import React, { useState, useCallback, useEffect, useRef, useMemo } 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 { useAutoSave } from "../hooks/useAutoSave"import { useTracking } from "../contexts/TrackingProvider"import { fonts, fontSizes } from "../styles/typography"-import { SectionTitle, FloatingSaveIndicator, Container, Card, Divider } from "../components"+import { SectionTitle, FloatingSaveIndicator, Container, Card, Divider, ChipGroup } from "../components"import NativeLocationService from "../services/NativeLocationService"import { logger } from "../utils/logger"@@ -20,6 +20,8 @@ const AUTH_TYPES: { value: AuthType; label: string }[] = [{ value: "bearer", label: "Bearer Token" }]+type LocalHeader = { key: string; value: string; id: number }+/*** Screen for configuring endpoint authentication and custom headers.*/@@ -31,12 +33,18 @@ export function AuthSettingsScreen({}: ScreenProps) {const [loading, setLoading] = useState(true)const { saving, saveSuccess, debouncedSaveAndRestart, immediateSaveAndRestart } = useAutoSave()+ const nextIdRef = useRef(0)+ const assignId = () => nextIdRef.current++++ const [localHeaders, setLocalHeaders] = useState<LocalHeader[]>([])+// Load config on mountuseEffect(() => {;(async () => {try {const saved = await NativeLocationService.getAuthConfig()setConfig(saved)+ setLocalHeaders(Object.entries(saved.customHeaders).map(([key, value]) => ({ key, value, id: assignId() })))} catch (err) {logger.error("[AuthSettingsScreen] Failed to load auth config:", err)} finally {@@ -45,6 +53,29 @@ export function AuthSettingsScreen({}: ScreenProps) {})()}, [])+ /** Detect duplicate header keys */+ const duplicateKeys = useMemo(() => {+ const seen = new Set<string>()+ const dupes = new Set<string>()+ for (const h of localHeaders) {+ const k = h.key.trim()+ if (!k) continue+ if (seen.has(k)) dupes.add(k)+ seen.add(k)+ }+ return dupes+ }, [localHeaders])++ /** Convert local headers array to Record for saving */+ const headersToRecord = useCallback((headers: LocalHeader[]): Record<string, string> => {+ const record: Record<string, string> = {}+ for (const h of headers) {+ const k = h.key.trim()+ if (k) record[k] = h.value.trim()+ }+ return record+ }, [])+const debouncedSave = useCallback((newConfig: AuthConfig) => {debouncedSaveAndRestart(@@ -80,55 +111,33 @@ export function AuthSettingsScreen({}: ScreenProps) {[config, immediateSaveAndRestart, restartTracking, settings])- // Custom headers as array for rendering- const headerEntries = Object.entries(config.customHeaders)-const addHeader = useCallback(() => {- // Use a unique placeholder key to avoid overwriting existing empty entries- let key = ""- let i = 1- while (key in config.customHeaders) {- key = `Header-${i++}`- }- updateConfig({- customHeaders: { ...config.customHeaders, [key]: "" }- })- }, [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]- )+ setLocalHeaders((prev) => [...prev, { key: "", value: "", id: assignId() }])+ }, [])- 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 })+ const updateHeaderField = useCallback(+ (id: number, field: "key" | "value", text: string) => {+ const next = localHeaders.map((h) => (h.id === id ? { ...h, [field]: text } : h))+ setLocalHeaders(next)+ updateConfig({ customHeaders: headersToRecord(next) })},- [config, updateConfig]+ [localHeaders, updateConfig, headersToRecord])const removeHeader = useCallback(- (index: number) => {- const entries = Object.entries(config.customHeaders)- entries.splice(index, 1)- const next = { ...config, customHeaders: Object.fromEntries(entries) }- setConfig(next)+ (id: number) => {+ const next = localHeaders.filter((h) => h.id !== id)+ setLocalHeaders(next)+ const nextConfig = { ...config, customHeaders: headersToRecord(next) }+ setConfig(nextConfig)immediateSaveAndRestart(async () => {- await NativeLocationService.saveAuthConfig(next)+ await NativeLocationService.saveAuthConfig(nextConfig)},() => restartTracking(settings))},- [config, immediateSaveAndRestart, restartTracking, settings]+ [localHeaders, config, headersToRecord, immediateSaveAndRestart, restartTracking, settings])if (loading) {@@ -158,41 +167,12 @@ export function AuthSettingsScreen({}: ScreenProps) {<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.primaryDark : colors.text- }- ]}- >- {label}- </Text>- </TouchableOpacity>- )- })}- </View>+ <ChipGroup+ options={AUTH_TYPES}+ selected={config.authType}+ onSelect={handleAuthTypeChange}+ colors={colors}+ />{/* Basic Auth fields */}{config.authType === "basic" && (@@ -248,6 +228,7 @@ export function AuthSettingsScreen({}: ScreenProps) {<TextInputstyle={[styles.input,+ styles.tokenInput,{borderColor: colors.border,color: colors.text,@@ -260,7 +241,8 @@ export function AuthSettingsScreen({}: ScreenProps) {placeholderTextColor={colors.placeholder}autoCapitalize="none"autoCorrect={false}- secureTextEntry+ multiline+ textAlignVertical="top"/></View></>@@ -272,60 +254,63 @@ export function AuthSettingsScreen({}: ScreenProps) {<View style={styles.section}><SectionTitle>Custom Headers</SectionTitle><Card>- {headerEntries.length === 0 ? (+ {localHeaders.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}- />+ localHeaders.map((header, index) => {+ const isDuplicate = header.key.trim() !== "" && duplicateKeys.has(header.key.trim())+ return (+ <View key={header.id}>+ {index > 0 && <Divider />}+ <View style={styles.headerRow}>+ <View style={styles.headerInputs}>+ <TextInput+ style={[+ styles.headerInput,+ {+ borderColor: isDuplicate ? colors.error : colors.border,+ color: colors.text,+ backgroundColor: colors.background+ }+ ]}+ value={header.key}+ onChangeText={(v) => updateHeaderField(header.id, "key", v)}+ placeholder="Header name"+ placeholderTextColor={colors.placeholder}+ autoCapitalize="none"+ autoCorrect={false}+ />+ <TextInput+ style={[+ styles.headerInput,+ {+ borderColor: colors.border,+ color: colors.text,+ backgroundColor: colors.background+ }+ ]}+ value={header.value}+ onChangeText={(v) => updateHeaderField(header.id, "value", v)}+ placeholder="Value"+ placeholderTextColor={colors.placeholder}+ autoCapitalize="none"+ autoCorrect={false}+ />+ </View>+ <TouchableOpacity+ onPress={() => removeHeader(header.id)}+ style={[styles.removeButton, { backgroundColor: colors.error + "15" }]}+ activeOpacity={0.7}+ >+ <Text style={[styles.removeButtonText, { color: colors.error }]}>X</Text>+ </TouchableOpacity></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 />}+ {localHeaders.length > 0 && <Divider />}<TouchableOpacitystyle={[styles.addButton, { borderColor: colors.primary }]}@@ -341,6 +326,17 @@ export function AuthSettingsScreen({}: ScreenProps) {</Card></View>+ {/* Duplicate key warning */}+ {duplicateKeys.size > 0 && (+ <View+ style={[styles.warningBanner, { backgroundColor: colors.error + "15", borderColor: colors.error + "40" }]}+ >+ <Text style={[styles.warningText, { color: colors.error }]}>+ Duplicate header names: {[...duplicateKeys].join(", ")}. Only the last value will be sent.+ </Text>+ </View>+ )}+{/* Footer */}<View style={styles.footer}><Text style={[styles.footerText, { color: colors.textLight }]}>@@ -386,21 +382,6 @@ const styles = StyleSheet.create({section: {marginBottom: 24},- chipRow: {- flexDirection: "row",- gap: 10- },- chip: {- flex: 1,- borderWidth: 2,- borderRadius: 10,- paddingVertical: 12,- alignItems: "center"- },- chipText: {- fontSize: 13,- ...fonts.bold- },fieldGroup: {marginTop: 4},@@ -418,6 +399,11 @@ const styles = StyleSheet.create({borderRadius: 12,fontSize: 15},+ tokenInput: {+ minHeight: 80,+ fontFamily: "monospace",+ fontSize: 13+ },emptyHint: {fontSize: 14,textAlign: "center",@@ -467,6 +453,16 @@ const styles = StyleSheet.create({marginTop: 10,textAlign: "center"},+ warningBanner: {+ padding: 12,+ borderRadius: 8,+ borderWidth: 1,+ marginBottom: 20+ },+ warningText: {+ fontSize: 12,+ lineHeight: 18+ },footer: {paddingVertical: 16,alignItems: "center"diff --git a/apps/mobile/src/screens/__tests__/AuthSettingsScreen.test.tsx b/apps/mobile/src/screens/__tests__/AuthSettingsScreen.test.tsxindex 116a8520..ba628cf2 100644--- a/apps/mobile/src/screens/__tests__/AuthSettingsScreen.test.tsx+++ b/apps/mobile/src/screens/__tests__/AuthSettingsScreen.test.tsx@@ -59,13 +59,25 @@ jest.mock("../../hooks/useAutoSave", () => ({jest.mock("../../components", () => {const R = require("react")- const { View, Text } = require("react-native")+ const { View, Text, TouchableOpacity } = require("react-native")return {SectionTitle: ({ children }: any) => R.createElement(Text, null, children),FloatingSaveIndicator: () => null,Container: ({ children }: any) => R.createElement(View, null, children),Card: ({ children }: any) => R.createElement(View, null, children),- Divider: () => R.createElement(View, null)+ Divider: () => R.createElement(View, null),+ ChipGroup: ({ options, onSelect }: any) =>+ R.createElement(+ View,+ null,+ options.map((opt: any) =>+ R.createElement(+ TouchableOpacity,+ { key: opt.value, onPress: () => onSelect(opt.value) },+ R.createElement(Text, null, opt.label)+ )+ )+ )}})@@ -297,5 +309,28 @@ describe("AuthSettingsScreen", () => {expect(queryByDisplayValue("X-Custom")).toBeNull()expect(mockImmediateSaveAndRestart).toHaveBeenCalled()})++ it("shows duplicate key warning when header names collide", async () => {+ mockAuthConfig = {+ ...DEFAULT_AUTH_CONFIG,+ customHeaders: { "X-One": "a" }+ }++ const { getByText, getAllByPlaceholderText, queryByText } = renderScreen()++ await waitFor(() => {+ expect(getByText("+ Add Header")).toBeTruthy()+ })++ // No warning initially+ expect(queryByText(/Duplicate header names/)).toBeNull()++ // Add second header and type same key+ fireEvent.press(getByText("+ Add Header"))+ const nameInputs = getAllByPlaceholderText("Header name")+ fireEvent.changeText(nameInputs[1], "X-One")++ expect(getByText(/Duplicate header names/)).toBeTruthy()+ })})})