Replace Basic-auth login with an API token set in Settings
Some checks failed
Build & Release APK / build (push) Has been cancelled
Some checks failed
Build & Release APK / build (push) Has been cancelled
The app no longer shows a login screen. It opens straight to the Today screen, which shows nothing until a bearer API token is saved in the new Settings screen. The token is verified against health-meta.json before it is stored in the keychain, and can be removed from the same screen. Server side: health-auth accepts Authorization: Bearer <HEALTH_APP_TOKEN> (read + write for the Fitbit sync, but not admin-only /life/* paths). Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -4,7 +4,7 @@ Cross-platform (iOS + Android) Expo app — native front end for the private
|
||||
health dashboard at **https://health.rehbock.xyz**.
|
||||
|
||||
The app is a pure client: all data lives on the server and is fetched live over
|
||||
HTTPS with HTTP Basic auth. Nothing is stored on the device except the auth
|
||||
HTTPS with a bearer API token. Nothing is stored on the device except the auth
|
||||
token (in the platform keychain via `expo-secure-store`).
|
||||
|
||||
## Screens
|
||||
@@ -30,7 +30,10 @@ npm install
|
||||
npx expo start # scan the QR with Expo Go (iOS or Android)
|
||||
```
|
||||
|
||||
Log in with the same Basic-auth credentials as the website.
|
||||
There is no login screen. Open **Settings** (⚙️ on the Today screen) and paste the API token;
|
||||
without one the app has no data. The server accepts it via `HEALTH_APP_TOKEN` in
|
||||
`health-auth` (`~/personal/health-auth/.env` on the VPS, passed through `docker-compose.yml`).
|
||||
Rotate it by changing that value and running `docker compose up -d`.
|
||||
|
||||
## Android release APK
|
||||
|
||||
|
||||
@@ -4,12 +4,10 @@ import React from 'react';
|
||||
import { View } from 'react-native';
|
||||
import { AuthProvider, useAuth } from '../lib/api';
|
||||
import { C } from '../lib/theme';
|
||||
import { LoginScreen } from '../components/login';
|
||||
|
||||
function Gate() {
|
||||
const { ready, authed } = useAuth();
|
||||
const { ready } = useAuth();
|
||||
if (!ready) return <View style={{ flex: 1, backgroundColor: C.bg }} />;
|
||||
if (!authed) return <LoginScreen />;
|
||||
return (
|
||||
<Stack
|
||||
screenOptions={{
|
||||
@@ -27,6 +25,7 @@ function Gate() {
|
||||
<Stack.Screen name="body" options={{ title: 'Body Composition' }} />
|
||||
<Stack.Screen name="mind" options={{ title: 'Meditation' }} />
|
||||
<Stack.Screen name="dna" options={{ title: 'Genetic Traits' }} />
|
||||
<Stack.Screen name="settings" options={{ title: 'Settings' }} />
|
||||
</Stack>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { Stack } from 'expo-router';
|
||||
import { Link, Stack } from 'expo-router';
|
||||
import React from 'react';
|
||||
import { Alert, Pressable, Text, View } from 'react-native';
|
||||
import { Text, View } from 'react-native';
|
||||
import { NavCard, PriorityCard, Screen, Sec } from '../components/ui';
|
||||
import { useAuth } from '../lib/api';
|
||||
import { agoTxt, fmtD, fmtDY, hm, num, cap } from '../lib/format';
|
||||
@@ -13,7 +13,7 @@ import type {
|
||||
import { loadAll, useLoad } from '../lib/use-load';
|
||||
|
||||
export default function Today() {
|
||||
const { logout } = useAuth();
|
||||
const { hasToken } = useAuth();
|
||||
const { data, loading, refresh } = useLoad(() =>
|
||||
loadAll({
|
||||
meta: 'meta', bio: 'biomarkers', wo: 'workouts', sApi: 'sleepApi',
|
||||
@@ -120,16 +120,9 @@ export default function Today() {
|
||||
<Stack.Screen
|
||||
options={{
|
||||
headerRight: () => (
|
||||
<Pressable
|
||||
hitSlop={10}
|
||||
onPress={() =>
|
||||
Alert.alert('Lock the dashboard?', 'You will need the password to get back in.', [
|
||||
{ text: 'Cancel', style: 'cancel' },
|
||||
{ text: 'Lock', style: 'destructive', onPress: logout },
|
||||
])
|
||||
}>
|
||||
<Text style={{ fontSize: 16 }}>🔒</Text>
|
||||
</Pressable>
|
||||
<Link href="/settings">
|
||||
<Text style={{ fontSize: 18, padding: 6 }}>⚙️</Text>
|
||||
</Link>
|
||||
),
|
||||
}}
|
||||
/>
|
||||
@@ -139,7 +132,11 @@ export default function Today() {
|
||||
weekday: 'long', month: 'long', day: 'numeric',
|
||||
})}
|
||||
/>
|
||||
{loading && !r ? (
|
||||
{!hasToken ? (
|
||||
<Link href="/settings" style={{ padding: 24, textAlign: 'center', color: C.accent, fontSize: 15 }}>
|
||||
Add your API token in Settings to load your data →
|
||||
</Link>
|
||||
) : loading && !r ? (
|
||||
<Text style={{ color: C.muted, fontSize: 13, textAlign: 'center', padding: 24 }}>
|
||||
Loading…
|
||||
</Text>
|
||||
|
||||
74
src/app/settings.tsx
Normal file
74
src/app/settings.tsx
Normal file
@@ -0,0 +1,74 @@
|
||||
import React, { useState } from 'react';
|
||||
import { Pressable, StyleSheet, Text, TextInput, View } from 'react-native';
|
||||
import { Screen } from '../components/ui';
|
||||
import { BASE, useAuth } from '../lib/api';
|
||||
import { C } from '../lib/theme';
|
||||
|
||||
export default function Settings() {
|
||||
const { hasToken, saveToken, clearToken } = useAuth();
|
||||
const [value, setValue] = useState('');
|
||||
const [msg, setMsg] = useState('');
|
||||
const [busy, setBusy] = useState(false);
|
||||
|
||||
const save = async () => {
|
||||
setBusy(true);
|
||||
setMsg('');
|
||||
try {
|
||||
if (await saveToken(value)) {
|
||||
setValue('');
|
||||
setMsg('Saved.');
|
||||
} else setMsg('The server rejected that token.');
|
||||
} catch {
|
||||
setMsg('Network error — are you online?');
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<Screen>
|
||||
<Text style={s.lbl}>SERVER</Text>
|
||||
<Text style={s.val}>{BASE}</Text>
|
||||
<Text style={s.lbl}>API TOKEN {hasToken ? '· saved' : '· not set'}</Text>
|
||||
<TextInput
|
||||
style={s.input}
|
||||
value={value}
|
||||
onChangeText={setValue}
|
||||
placeholder={hasToken ? '•••••••• (enter a new one to replace)' : 'Paste your API token'}
|
||||
placeholderTextColor={C.dim}
|
||||
autoCapitalize="none"
|
||||
autoCorrect={false}
|
||||
secureTextEntry
|
||||
onSubmitEditing={save}
|
||||
returnKeyType="done"
|
||||
/>
|
||||
<Pressable
|
||||
style={[s.go, (busy || !value.trim()) && { opacity: 0.5 }]}
|
||||
disabled={busy || !value.trim()}
|
||||
onPress={save}>
|
||||
<Text style={s.goTxt}>Save token</Text>
|
||||
</Pressable>
|
||||
{hasToken ? (
|
||||
<Pressable style={s.clear} onPress={clearToken}>
|
||||
<Text style={{ color: C.red, fontSize: 14 }}>Remove token from this device</Text>
|
||||
</Pressable>
|
||||
) : null}
|
||||
<View style={{ minHeight: 24 }}>
|
||||
<Text style={s.msg}>{msg}</Text>
|
||||
</View>
|
||||
</Screen>
|
||||
);
|
||||
}
|
||||
|
||||
const s = StyleSheet.create({
|
||||
lbl: { fontSize: 11, color: C.muted, letterSpacing: 0.5, marginTop: 16, marginBottom: 6 },
|
||||
val: { fontSize: 15, color: C.text },
|
||||
input: {
|
||||
paddingVertical: 11, paddingHorizontal: 12, borderRadius: 10, borderWidth: 1,
|
||||
borderColor: C.border, backgroundColor: C.surface2, color: C.text, fontSize: 15,
|
||||
},
|
||||
go: { marginTop: 16, padding: 12, borderRadius: 10, backgroundColor: C.accent, alignItems: 'center' },
|
||||
goTxt: { color: '#fff', fontWeight: '600', fontSize: 15 },
|
||||
clear: { marginTop: 20, alignItems: 'center', padding: 8 },
|
||||
msg: { marginTop: 12, fontSize: 12.5, color: C.muted },
|
||||
});
|
||||
@@ -1,84 +0,0 @@
|
||||
import React, { useState } from 'react';
|
||||
import {
|
||||
KeyboardAvoidingView, Platform, Pressable, StyleSheet, Text, TextInput, View,
|
||||
} from 'react-native';
|
||||
import { useAuth } from '../lib/api';
|
||||
import { C } from '../lib/theme';
|
||||
|
||||
export function LoginScreen() {
|
||||
const { login } = useAuth();
|
||||
const [user, setUser] = useState('admin');
|
||||
const [pass, setPass] = useState('');
|
||||
const [err, setErr] = useState('');
|
||||
const [busy, setBusy] = useState(false);
|
||||
|
||||
const go = async () => {
|
||||
setBusy(true);
|
||||
setErr('');
|
||||
try {
|
||||
const ok = await login(user.trim(), pass);
|
||||
if (!ok) setErr('Wrong password.');
|
||||
else setPass('');
|
||||
} catch {
|
||||
setErr('Network error — are you online?');
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<KeyboardAvoidingView
|
||||
style={s.wrap}
|
||||
behavior={Platform.OS === 'ios' ? 'padding' : undefined}>
|
||||
<View style={s.card}>
|
||||
<Text style={{ fontSize: 34, marginBottom: 10 }}>⚕️</Text>
|
||||
<Text style={s.h1}>Health Dashboard</Text>
|
||||
<Text style={s.sub}>health.rehbock.xyz — private</Text>
|
||||
<Text style={s.lbl}>USER</Text>
|
||||
<TextInput
|
||||
style={s.input}
|
||||
value={user}
|
||||
onChangeText={setUser}
|
||||
autoCapitalize="none"
|
||||
autoCorrect={false}
|
||||
textContentType="username"
|
||||
/>
|
||||
<Text style={s.lbl}>PASSWORD</Text>
|
||||
<TextInput
|
||||
style={s.input}
|
||||
value={pass}
|
||||
onChangeText={setPass}
|
||||
secureTextEntry
|
||||
textContentType="password"
|
||||
onSubmitEditing={go}
|
||||
returnKeyType="go"
|
||||
/>
|
||||
<Pressable style={[s.go, busy && { opacity: 0.5 }]} disabled={busy} onPress={go}>
|
||||
<Text style={{ color: '#fff', fontWeight: '600', fontSize: 15 }}>Unlock</Text>
|
||||
</Pressable>
|
||||
<Text style={s.err}>{err}</Text>
|
||||
</View>
|
||||
</KeyboardAvoidingView>
|
||||
);
|
||||
}
|
||||
|
||||
const s = StyleSheet.create({
|
||||
wrap: {
|
||||
flex: 1, backgroundColor: C.bg, alignItems: 'center', justifyContent: 'center', padding: 24,
|
||||
},
|
||||
card: {
|
||||
width: '100%', maxWidth: 340, backgroundColor: C.surface, borderWidth: 1,
|
||||
borderColor: C.border, borderRadius: 16, paddingVertical: 28, paddingHorizontal: 24,
|
||||
},
|
||||
h1: { fontSize: 18, fontWeight: '600', color: C.text, marginBottom: 4 },
|
||||
sub: { fontSize: 12, color: C.muted, marginBottom: 20 },
|
||||
lbl: { fontSize: 11, color: C.muted, letterSpacing: 0.5, marginTop: 12, marginBottom: 5 },
|
||||
input: {
|
||||
paddingVertical: 11, paddingHorizontal: 12, borderRadius: 10, borderWidth: 1,
|
||||
borderColor: C.border, backgroundColor: C.surface2, color: C.text, fontSize: 15,
|
||||
},
|
||||
go: {
|
||||
marginTop: 20, padding: 12, borderRadius: 10, backgroundColor: C.accent, alignItems: 'center',
|
||||
},
|
||||
err: { marginTop: 12, fontSize: 12.5, color: C.red, minHeight: 18 },
|
||||
});
|
||||
@@ -22,62 +22,33 @@ export const FITBIT_SYNC_URL = `${BASE}/api/health/v1/fitbit/sync`;
|
||||
|
||||
/* authenticated POST (fitbit sync) */
|
||||
export async function postJson<T>(url: string, body: unknown): Promise<T> {
|
||||
if (!token) throw new Error(NO_TOKEN);
|
||||
const r = await fetch(url, {
|
||||
method: 'POST',
|
||||
headers: { Authorization: 'Basic ' + token, 'Content-Type': 'application/json' },
|
||||
headers: { Authorization: 'Bearer ' + token, 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(body),
|
||||
});
|
||||
if (r.status === 401 || r.status === 403) {
|
||||
onUnauthorized?.();
|
||||
throw new Error('unauthorized');
|
||||
}
|
||||
if (r.status === 401 || r.status === 403) throw new Error(BAD_TOKEN);
|
||||
if (!r.ok) throw new Error(`${url} → ${r.status}`);
|
||||
return r.json();
|
||||
}
|
||||
|
||||
export type EpKey = keyof typeof EP;
|
||||
|
||||
const AUTH_KEY = 'hd.auth';
|
||||
const AUTH_KEY = 'hd.token';
|
||||
|
||||
export const NO_TOKEN = 'No API token — add one in Settings.';
|
||||
export const BAD_TOKEN = 'API token rejected — check it in Settings.';
|
||||
|
||||
let token: string | null = null;
|
||||
let onUnauthorized: (() => void) | null = null;
|
||||
|
||||
/* base64 without Buffer/btoa dependency quirks across Hermes versions */
|
||||
const B64 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
|
||||
export function b64(str: string): string {
|
||||
const bytes: number[] = [];
|
||||
for (let i = 0; i < str.length; i++) {
|
||||
const code = str.codePointAt(i)!;
|
||||
if (code > 0xffff) i++;
|
||||
if (code < 0x80) bytes.push(code);
|
||||
else if (code < 0x800) bytes.push(0xc0 | (code >> 6), 0x80 | (code & 63));
|
||||
else if (code < 0x10000)
|
||||
bytes.push(0xe0 | (code >> 12), 0x80 | ((code >> 6) & 63), 0x80 | (code & 63));
|
||||
else
|
||||
bytes.push(
|
||||
0xf0 | (code >> 18), 0x80 | ((code >> 12) & 63),
|
||||
0x80 | ((code >> 6) & 63), 0x80 | (code & 63),
|
||||
);
|
||||
}
|
||||
let out = '';
|
||||
for (let i = 0; i < bytes.length; i += 3) {
|
||||
const [a, b, c] = [bytes[i], bytes[i + 1], bytes[i + 2]];
|
||||
out += B64[a >> 2] + B64[((a & 3) << 4) | (b ?? 0) >> 4];
|
||||
out += b === undefined ? '=' : B64[((b & 15) << 2) | (c ?? 0) >> 6];
|
||||
out += c === undefined ? '=' : B64[c & 63];
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
async function authFetch<T>(url: string): Promise<T> {
|
||||
if (!token) throw new Error(NO_TOKEN);
|
||||
const r = await fetch(url, {
|
||||
headers: { Authorization: 'Basic ' + token },
|
||||
headers: { Authorization: 'Bearer ' + token },
|
||||
cache: 'no-store',
|
||||
});
|
||||
if (r.status === 401 || r.status === 403) {
|
||||
onUnauthorized?.();
|
||||
throw new Error('unauthorized');
|
||||
}
|
||||
if (r.status === 401 || r.status === 403) throw new Error(BAD_TOKEN);
|
||||
if (!r.ok) throw new Error(`${url} → ${r.status}`);
|
||||
return r.json();
|
||||
}
|
||||
@@ -107,62 +78,58 @@ export function invalidate(...keys: EpKey[]) {
|
||||
|
||||
interface AuthCtx {
|
||||
ready: boolean;
|
||||
authed: boolean;
|
||||
login: (user: string, pass: string) => Promise<boolean>;
|
||||
logout: () => void;
|
||||
/** an API token is stored (it may still be rejected by the server) */
|
||||
hasToken: boolean;
|
||||
/** verify against the server, then store; false = server rejected it */
|
||||
saveToken: (t: string) => Promise<boolean>;
|
||||
clearToken: () => void;
|
||||
}
|
||||
|
||||
const Ctx = createContext<AuthCtx>({
|
||||
ready: false,
|
||||
authed: false,
|
||||
login: async () => false,
|
||||
logout: () => {},
|
||||
hasToken: false,
|
||||
saveToken: async () => false,
|
||||
clearToken: () => {},
|
||||
});
|
||||
|
||||
export const useAuth = () => useContext(Ctx);
|
||||
|
||||
export function AuthProvider({ children }: { children: React.ReactNode }) {
|
||||
const [ready, setReady] = useState(false);
|
||||
const [authed, setAuthed] = useState(false);
|
||||
const [hasToken, setHasToken] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
SecureStore.getItemAsync(AUTH_KEY)
|
||||
.then((t) => {
|
||||
if (t) {
|
||||
token = t;
|
||||
setAuthed(true);
|
||||
setHasToken(true);
|
||||
}
|
||||
})
|
||||
.catch(() => {})
|
||||
.finally(() => setReady(true));
|
||||
}, []);
|
||||
|
||||
const logout = useCallback(() => {
|
||||
const clearToken = useCallback(() => {
|
||||
token = null;
|
||||
clearCache();
|
||||
SecureStore.deleteItemAsync(AUTH_KEY).catch(() => {});
|
||||
setAuthed(false);
|
||||
setHasToken(false);
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
onUnauthorized = logout;
|
||||
return () => {
|
||||
onUnauthorized = null;
|
||||
};
|
||||
}, [logout]);
|
||||
|
||||
const login = useCallback(async (user: string, pass: string) => {
|
||||
const tok = b64(`${user}:${pass}`);
|
||||
const saveToken = useCallback(async (raw: string) => {
|
||||
const t = raw.trim();
|
||||
const r = await fetch(EP.meta, {
|
||||
headers: { Authorization: 'Basic ' + tok },
|
||||
headers: { Authorization: 'Bearer ' + t },
|
||||
cache: 'no-store',
|
||||
});
|
||||
if (!r.ok) return false;
|
||||
token = tok;
|
||||
token = t;
|
||||
clearCache();
|
||||
await SecureStore.setItemAsync(AUTH_KEY, tok);
|
||||
setAuthed(true);
|
||||
await SecureStore.setItemAsync(AUTH_KEY, t);
|
||||
setHasToken(true);
|
||||
return true;
|
||||
}, []);
|
||||
|
||||
return <Ctx.Provider value={{ ready, authed, login, logout }}>{children}</Ctx.Provider>;
|
||||
return <Ctx.Provider value={{ ready, hasToken, saveToken, clearToken }}>{children}</Ctx.Provider>;
|
||||
}
|
||||
|
||||
@@ -19,8 +19,7 @@ export function useLoad<T>(fn: () => Promise<T>): LoadState<T> & { refresh: () =
|
||||
.then((data) => live && setState({ data, loading: false }))
|
||||
.catch((e) => {
|
||||
if (!live) return;
|
||||
const msg = e instanceof Error ? e.message : String(e);
|
||||
if (msg !== 'unauthorized') setState({ err: msg, loading: false });
|
||||
setState({ err: e instanceof Error ? e.message : String(e), loading: false });
|
||||
});
|
||||
return () => {
|
||||
live = false;
|
||||
|
||||
Reference in New Issue
Block a user