Skip to content

Colota - Android GPS Location tracker

12.0 KB
Raw Blame
/**
 * 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 { StyleSheet, View, ScrollView, ActivityIndicator } from "react-native"
import { X } from "lucide-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 {
  SectionTitle,
  FloatingSaveIndicator,
  Container,
  Card,
  Divider,
  RadioRow,
  Button,
  TextField,
  FieldMessage,
  IconButton
} from "../components"
import NativeLocationService from "../services/NativeLocationService"
import { logger } from "../utils/logger"
import { size, space } from "../constants"
import { useTranslation } from "../i18n/useTranslation"
import type { TranslationKey } from "../i18n/options"

const METHODS: { value: AuthType; labelKey: TranslationKey; subKey: TranslationKey }[] = [
  { value: "none", labelKey: "auth.none", subKey: "auth.none.sub" },
  { value: "basic", labelKey: "auth.basic", subKey: "auth.basic.sub" },
  { value: "bearer", labelKey: "auth.bearer", subKey: "auth.bearer.sub" }
]

const SENSITIVE_HEADER = /authorization|cookie|token|key|secret/i

type LocalHeader = { key: string; value: string; id: number }

/** A method owns its credentials: choosing one drops the others', so a never-echoed secret can still be cleared. */
export function withMethod(config: AuthConfig, authType: AuthType): AuthConfig {
  return {
    ...config,
    authType,
    username: authType === "basic" ? config.username : "",
    password: authType === "basic" ? config.password : "",
    bearerToken: authType === "bearer" ? config.bearerToken : ""
  }
}

export function AuthSettingsScreen({}: ScreenProps) {
  const { colors } = useTheme()
  const { t } = useTranslation()
  const { restartTracking, settings } = useTracking()

  const [config, setConfig] = useState<AuthConfig>(DEFAULT_AUTH_CONFIG)
  const configRef = useRef(config)
  configRef.current = config
  const [loading, setLoading] = useState(true)
  const [passwordDraft, setPasswordDraft] = useState("")
  const [tokenDraft, setTokenDraft] = useState("")
  const {
    saving,
    message: saveMessage,
    isError: saveIsError,
    debouncedSaveAndRestart,
    immediateSaveAndRestart
  } = useAutoSave()

  const nextIdRef = useRef(0)
  const assignId = () => nextIdRef.current++

  const [localHeaders, setLocalHeaders] = useState<LocalHeader[]>([])

  useEffect(() => {
    ;(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 {
        setLoading(false)
      }
    })()
  }, [])

  const headersToRecord = (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 saveNow = useCallback(
    (next: AuthConfig) => {
      setConfig(next)
      immediateSaveAndRestart(
        async () => {
          await NativeLocationService.saveAuthConfig(next)
        },
        () => restartTracking(settings)
      )
    },
    [immediateSaveAndRestart, restartTracking, settings]
  )

  const saveSoon = useCallback(
    (partial: Partial<AuthConfig>) => {
      const next = { ...configRef.current, ...partial }
      setConfig(next)
      debouncedSaveAndRestart(
        async () => {
          await NativeLocationService.saveAuthConfig(next)
        },
        () => restartTracking(settings)
      )
    },
    [debouncedSaveAndRestart, restartTracking, settings]
  )

  const handleMethod = (authType: AuthType) => {
    if (authType === config.authType) return
    setPasswordDraft("")
    setTokenDraft("")
    saveNow(withMethod(config, authType))
  }

  const handleSecret = (key: "password" | "bearerToken", text: string) => {
    if (key === "password") setPasswordDraft(text)
    else setTokenDraft(text)
    // An empty draft keeps the stored value; choosing another method is how a secret is cleared.
    if (text !== "") saveSoon({ [key]: text })
  }

  const addHeader = () => setLocalHeaders((prev) => [...prev, { key: "", value: "", id: assignId() }])

  const updateHeaderField = (id: number, field: "key" | "value", text: string) => {
    const next = localHeaders.map((h) => (h.id === id ? { ...h, [field]: text } : h))
    setLocalHeaders(next)
    saveSoon({ customHeaders: headersToRecord(next) })
  }

  const removeHeader = (id: number) => {
    const next = localHeaders.filter((h) => h.id !== id)
    setLocalHeaders(next)
    saveNow({ ...configRef.current, customHeaders: headersToRecord(next) })
  }

  if (loading) {
    return (
      <Container>
        <View style={styles.loadingContainer}>
          <ActivityIndicator size="large" color={colors.primary} />
        </View>
      </Container>
    )
  }

  const secretHint = (stored: string) => (stored !== "" ? t("auth.secretSet") : t("auth.secretUnset"))
  const holdsCredentials =
    (config.authType === "basic" && (config.username !== "" || config.password !== "")) ||
    (config.authType === "bearer" && config.bearerToken !== "")

  return (
    <Container>
      <ScrollView
        contentContainerStyle={styles.scrollContent}
        keyboardShouldPersistTaps="handled"
        showsVerticalScrollIndicator={false}
      >
        <SectionTitle>{t("auth.section.method")}</SectionTitle>
        <Card rows>
          <View accessibilityRole="radiogroup" style={styles.group}>
            {METHODS.map(({ value, labelKey, subKey }) => (
              <React.Fragment key={value}>
                <RadioRow
                  testID={`auth-${value}`}
                  label={t(labelKey)}
                  sub={t(subKey)}
                  selected={config.authType === value}
                  onPress={() => handleMethod(value)}
                />
                {value === "basic" && config.authType === "basic" && (
                  <View style={styles.reveal}>
                    <TextField
                      label={t("auth.username")}
                      testID="basic-username"
                      value={config.username}
                      onChangeText={(v) => saveSoon({ username: v })}
                      placeholder={t("auth.username")}
                      autoCapitalize="none"
                      autoCorrect={false}
                      autoComplete="username"
                    />
                    <View>
                      <TextField
                        label={t("auth.password")}
                        testID="basic-password"
                        value={passwordDraft}
                        onChangeText={(v) => handleSecret("password", v)}
                        placeholder={t("auth.password")}
                        autoCapitalize="none"
                        autoCorrect={false}
                        autoComplete="password"
                        secure
                      />
                      <FieldMessage>{secretHint(config.password)}</FieldMessage>
                    </View>
                  </View>
                )}
                {value === "bearer" && config.authType === "bearer" && (
                  <View style={styles.reveal}>
                    <View>
                      <TextField
                        label={t("auth.token")}
                        testID="bearer-token"
                        mono
                        value={tokenDraft}
                        onChangeText={(v) => handleSecret("bearerToken", v)}
                        placeholder={t("auth.token.placeholder")}
                        autoCapitalize="none"
                        autoCorrect={false}
                        autoComplete="off"
                        importantForAutofill="no"
                        secure
                      />
                      <FieldMessage>{secretHint(config.bearerToken)}</FieldMessage>
                    </View>
                  </View>
                )}
              </React.Fragment>
            ))}
          </View>
          {holdsCredentials && (
            <>
              <Divider tight />
              <View style={styles.footer}>
                <FieldMessage>{t("auth.removedOnSwitch")}</FieldMessage>
              </View>
            </>
          )}
        </Card>

        <SectionTitle style={styles.groupTop}>{t("auth.section.headers")}</SectionTitle>
        <Card rows>
          {localHeaders.map((header, index) => {
            const name = header.key.trim()
            const isDuplicate = name !== "" && localHeaders.slice(0, index).some((h) => h.key.trim() === name)
            return (
              <View key={header.id}>
                {index > 0 && <Divider tight />}
                <View style={styles.headerRow}>
                  <View style={styles.headerInputs}>
                    <TextField
                      accessibilityLabel={t("auth.header.nameLabel")}
                      testID={`header-key-${header.id}`}
                      mono
                      error={isDuplicate ? t("auth.duplicateHeader") : undefined}
                      value={header.key}
                      onChangeText={(v) => updateHeaderField(header.id, "key", v)}
                      placeholder={t("auth.header.namePlaceholder")}
                      autoCapitalize="none"
                      autoCorrect={false}
                    />
                    <TextField
                      accessibilityLabel={t("auth.header.valueLabel")}
                      testID={`header-value-${header.id}`}
                      value={header.value}
                      onChangeText={(v) => updateHeaderField(header.id, "value", v)}
                      placeholder={t("auth.header.valuePlaceholder")}
                      autoCapitalize="none"
                      autoCorrect={false}
                      secure={SENSITIVE_HEADER.test(name)}
                    />
                  </View>
                  <IconButton
                    icon={X}
                    tone="danger"
                    testID={`remove-header-${header.id}`}
                    accessibilityLabel={name ? t("auth.header.remove", { name }) : t("auth.header.removeUnnamed")}
                    onPress={() => removeHeader(header.id)}
                  />
                </View>
              </View>
            )
          })}
          {localHeaders.length > 0 && <Divider tight />}
          <View style={[styles.footer, localHeaders.length === 0 && styles.footerFirst]}>
            <Button title={t("auth.header.add")} onPress={addHeader} variant="secondary" testID="add-header-btn" />
            {localHeaders.length === 0 && <FieldMessage>{t("auth.headersHint")}</FieldMessage>}
          </View>
        </Card>
      </ScrollView>

      <FloatingSaveIndicator saving={saving} message={saveMessage} isError={saveIsError} />
    </Container>
  )
}

const styles = StyleSheet.create({
  scrollContent: {
    paddingHorizontal: space.lg,
    paddingTop: space.lg,
    paddingBottom: space.xxl
  },
  loadingContainer: {
    flex: 1,
    justifyContent: "center",
    alignItems: "center"
  },
  group: {
    marginTop: -space.sm
  },
  groupTop: {
    marginTop: space.xl
  },
  // The row above already pays space.lg below it; the fields' gap is the rhythm to the next row.
  reveal: {
    paddingLeft: size.iconColumn,
    marginTop: -space.xs,
    paddingBottom: space.lg,
    gap: space.lg
  },
  footer: {
    paddingTop: space.xs,
    paddingBottom: space.lg
  },
  // With no header rows above, the button's own sm margin plus this matches the lg below the caption.
  footerFirst: {
    paddingTop: space.sm
  },
  headerRow: {
    flexDirection: "row",
    alignItems: "center",
    gap: space.sm,
    paddingVertical: space.md
  },
  headerInputs: {
    flex: 1,
    gap: space.sm
  }
})