Phone App: more than one server, and a session for each
The web app can be pointed at two DriverVault stacks and switch between them in a click. The phone had one address and one session: reaching a second garage meant retyping the API base in Server settings and signing in again, losing the first server's token on the way — the same act, undone, every time you switched back. So lib/servers.dart is the web's servers.js ported rather than reinvented, down to the storage keys: cc_servers holds the list, cc_active_server the one being read, cc_session_<id> the token minted by that server and no other. The two apps describe the same thing the same way, and the upgrade path falls out of it — cc_token, cc_user and cc_server_url are read once at boot and folded onto the home entry, so the build carrying this signs nobody out. Home is the address the build ships with (kDefaultApiBase, still overridable per device from the login screen) and cannot be removed: it is what a dropped session falls back to. Any other server is added by address, with /api appended if the path is left off, because a server a phone can reach is internet-facing already. The part worth reading twice is which session a rejection ends. ApiClient no longer holds a base or a token — it pins the active server's id, base and token at the moment a request goes out, so a 401 arriving after a switch clears the session of the server that actually refused it rather than whichever one is active by then. The fallback is the web's: a remote server timing out drops its own token, the app returns to home while home is still signed in, and only when nothing is left to fall back to does the login screen come back. Log out still clears every server at once, since leaving the app means leaving all of them. Switching rebuilds the shell, keyed on the active id, because record ids belong to the server that issued them — a garage, a charging page and a settings panel still holding the other server's rows would each have to be told to forget them separately. The appearance prefs come across with the profile of whoever owns the account on the server now active. Where the picker lives is the one place the phone cannot copy the web. There is no app rail here, so it became the first button in the Garage header, beside the theme toggle and log out, which is that same cluster. It names the active server once there is a choice and goes straight to adding the second when there isn't; the eyebrow reads GARAGE · Work for the reason the rail names it — two garages otherwise look identical. The login screen gets its own way in, because a remote session can expire and land you there with that server still active, and a picker reachable only from inside the app would leave nowhere to go. One judgment call inside the sheet: saving a connected server at a new address saves and stops, rather than falling through to the sign-in it now needs. The token was minted by the PocketBase behind the old address and is dropped with it, but the credentials to replace it were never asked for, so treating the save as a login would report an empty password as the error. The strings are copied out of Web App/web/src/i18n/ like the rest of the shared wording. Two are not the web's: home reads "the address this app ships with" rather than "served with this app", since the phone has no origin to be served from, and sameOrigin has no meaning here at all and was dropped. Biometric sign-in stays global. It was never per-server and replays its stored credentials against whichever server is active; making it per-server is a change of its own, and the login screen now names the server it is about to sign into. Nothing changes on the API Server. On Android there is no origin to allow, so the CORS list the web app has to satisfy to reach a second server doesn't enter into it. Verified: flutter analyze is clean and flutter test passes, 35 tests to 46. The new ones cover the registry — a bare origin gaining its /api, a fresh install knowing one unnamed server on the built-in address, the legacy keys landing on home and being cleared, two servers holding their tokens apart, a rename keeping a session where a move drops it, removing the active server falling back to a home that is still signed in, home refusing to be removed, and a restart reading the list, the active id and every session back. Not verified: none of it has been run. There is no device or emulator on this machine and no API Server to answer, so the picker, the add sheet, a real connect, the 401 fallback and the shell rebuild on a switch exist only as code the analyzer is happy with — the tests reach the registry, not a screen. No APK was built. The legacy migration was exercised against mocked SharedPreferences, which is not a phone that had the old build on it: that is the first thing to check on a device, since the failure mode is a silent sign-out. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
1 parent
35e6c511b7
commit
12ec10a797
14 files changed
+1119
-122
No files matched your search
+72
-61
@@ -1,9 +1,8 @@
|
||||
import "dart:convert";
|
||||
import "package:http/http.dart" as http;
|
||||
import "package:shared_preferences/shared_preferences.dart";
|
||||
|
||||
import "config.dart";
|
||||
import "models.dart";
|
||||
import "servers.dart";
|
||||
|
||||
/// Thrown when the API Server returns a non-2xx response.
|
||||
class ApiException implements Exception {
|
||||
@@ -14,61 +13,56 @@ class ApiException implements Exception {
|
||||
String toString() => message;
|
||||
}
|
||||
|
||||
/// The single client for the Car Control API Server. Holds the bearer token and
|
||||
/// attaches it to every request. On 401 it calls [onUnauthorized] so the app can
|
||||
/// route back to login.
|
||||
/// One request's destination: the server that was active when it went out, its
|
||||
/// base URL and its token. Pinning all three up front is what keeps a rejection
|
||||
/// attributable — re-reading the active server on the way back would let one
|
||||
/// server's 401 clear a different server's session when a switch lands between
|
||||
/// a call going out and its answer arriving.
|
||||
class _Target {
|
||||
final String id;
|
||||
final String base;
|
||||
final String? token;
|
||||
const _Target(this.id, this.base, this.token);
|
||||
|
||||
Uri uri(String path) => Uri.parse("$base$path");
|
||||
|
||||
Map<String, String> get authHeaders =>
|
||||
{if (token != null) "Authorization": "Bearer $token"};
|
||||
|
||||
Map<String, String> get jsonHeaders =>
|
||||
{"Content-Type": "application/json", ...authHeaders};
|
||||
}
|
||||
|
||||
/// The single client for the Car Control API Server. Which server the calls go
|
||||
/// to is [serverRegistry]'s business: the base URL and the bearer token are both
|
||||
/// read from whichever server is active, resolved fresh on every request so
|
||||
/// switching takes effect without rebuilding the client. On 401 it calls
|
||||
/// [onUnauthorized] with the server that rejected the session.
|
||||
class ApiClient {
|
||||
String? token;
|
||||
void Function()? onUnauthorized;
|
||||
void Function(String serverId)? onUnauthorized;
|
||||
|
||||
static const _serverKey = "cc_server_url";
|
||||
/// The active server's token — read by the multipart and download helpers,
|
||||
/// which build their own requests.
|
||||
String? get token => serverRegistry.activeToken;
|
||||
|
||||
/// The effective API base URL. Defaults to [kDefaultApiBase]; a saved override
|
||||
/// (login screen "Server settings") replaces it via [loadServerUrl].
|
||||
String baseUrl = kDefaultApiBase;
|
||||
/// The base URL the next request will go to.
|
||||
String get baseUrl => serverRegistry.activeBase;
|
||||
|
||||
/// Loads a saved server-URL override, if any. Call before the first request.
|
||||
Future<void> loadServerUrl() async {
|
||||
final prefs = await SharedPreferences.getInstance();
|
||||
final saved = prefs.getString(_serverKey);
|
||||
if (saved != null && saved.isNotEmpty) baseUrl = saved;
|
||||
}
|
||||
|
||||
/// The current override URL, or "" when using the default.
|
||||
Future<String> serverOverride() async {
|
||||
final prefs = await SharedPreferences.getInstance();
|
||||
return prefs.getString(_serverKey) ?? "";
|
||||
}
|
||||
|
||||
/// Persists a server-URL override. Blank clears it (reverts to the default).
|
||||
/// Trailing slashes are trimmed.
|
||||
Future<void> setServerUrl(String url) async {
|
||||
final prefs = await SharedPreferences.getInstance();
|
||||
final trimmed = url.trim().replaceAll(RegExp(r"/+$"), "");
|
||||
if (trimmed.isEmpty) {
|
||||
await prefs.remove(_serverKey);
|
||||
baseUrl = kDefaultApiBase;
|
||||
} else {
|
||||
await prefs.setString(_serverKey, trimmed);
|
||||
baseUrl = trimmed;
|
||||
}
|
||||
}
|
||||
|
||||
Map<String, String> get _headers => {
|
||||
"Content-Type": "application/json",
|
||||
if (token != null) "Authorization": "Bearer $token",
|
||||
};
|
||||
|
||||
Uri _uri(String path) => Uri.parse("$baseUrl$path");
|
||||
_Target _target() => _Target(
|
||||
serverRegistry.activeId,
|
||||
serverRegistry.activeBase,
|
||||
serverRegistry.activeToken,
|
||||
);
|
||||
|
||||
Future<dynamic> _send(String method, String path, {Object? body}) async {
|
||||
final req = http.Request(method, _uri(path))..headers.addAll(_headers);
|
||||
final target = _target();
|
||||
final req = http.Request(method, target.uri(path))..headers.addAll(target.jsonHeaders);
|
||||
if (body != null) req.body = jsonEncode(body);
|
||||
final streamed = await http.Client().send(req);
|
||||
final res = await http.Response.fromStream(streamed);
|
||||
|
||||
if (res.statusCode == 401 && path != "/auth/login") {
|
||||
onUnauthorized?.call();
|
||||
onUnauthorized?.call(target.id);
|
||||
throw ApiException(401, "Session expired — please log in again.");
|
||||
}
|
||||
if (res.statusCode == 204 || res.body.isEmpty) return null;
|
||||
@@ -102,14 +96,29 @@ class ApiClient {
|
||||
}
|
||||
|
||||
// --- auth ---
|
||||
/// Signs in against a named base rather than the active server: the add-server
|
||||
/// sheet checks credentials against the server being added before anything
|
||||
/// switches to it, so a wrong password leaves you where you were.
|
||||
///
|
||||
/// The API Server proxies login to PocketBase and relays its response
|
||||
/// verbatim, so the user arrives under `record` (PocketBase's name) and the
|
||||
/// token is PocketBase's own — the server no longer mints its own JWT.
|
||||
Future<(String, AuthUser)> login(String email, String password) async {
|
||||
final data = await _send("POST", "/auth/login", body: {"email": email, "password": password});
|
||||
Future<(String, AuthUser)> loginAt(String base, String email, String password) async {
|
||||
final res = await http.post(
|
||||
Uri.parse("$base/auth/login"),
|
||||
headers: const {"Content-Type": "application/json"},
|
||||
body: jsonEncode({"email": email, "password": password}),
|
||||
);
|
||||
final data = res.body.isEmpty ? null : _tryDecode(res.body);
|
||||
if (res.statusCode < 200 || res.statusCode >= 300) {
|
||||
throw ApiException(res.statusCode, _errorMessage(data, res.reasonPhrase));
|
||||
}
|
||||
return (data["token"] as String, AuthUser.fromJson(Map<String, dynamic>.from(data["record"])));
|
||||
}
|
||||
|
||||
Future<(String, AuthUser)> login(String email, String password) =>
|
||||
loginAt(serverRegistry.activeBase, email, password);
|
||||
|
||||
// --- cars ---
|
||||
Future<List<Car>> listCars() async {
|
||||
final data = await _send("GET", "/cars") as List;
|
||||
@@ -418,12 +427,13 @@ class ApiClient {
|
||||
/// the caller decodes it into whichever model it owns.
|
||||
Future<Map<String, dynamic>> uploadAttachment(
|
||||
String path, String id, List<int> bytes, String filename) async {
|
||||
final req = http.MultipartRequest("POST", _uri("$path/$id/file"));
|
||||
if (token != null) req.headers["Authorization"] = "Bearer $token";
|
||||
final target = _target();
|
||||
final req = http.MultipartRequest("POST", target.uri("$path/$id/file"))
|
||||
..headers.addAll(target.authHeaders);
|
||||
req.files.add(http.MultipartFile.fromBytes("file", bytes, filename: filename));
|
||||
final res = await http.Response.fromStream(await req.send());
|
||||
if (res.statusCode == 401) {
|
||||
onUnauthorized?.call();
|
||||
onUnauthorized?.call(target.id);
|
||||
throw ApiException(401, "Session expired — please log in again.");
|
||||
}
|
||||
final data = jsonDecode(res.body);
|
||||
@@ -436,8 +446,8 @@ class ApiClient {
|
||||
/// The attachment's bytes, or null when there is no file. Never a public URL —
|
||||
/// the server re-checks car access on every fetch.
|
||||
Future<List<int>?> getAttachmentBytes(String path, String id) async {
|
||||
final res = await http.get(_uri("$path/$id/file"),
|
||||
headers: {if (token != null) "Authorization": "Bearer $token"});
|
||||
final target = _target();
|
||||
final res = await http.get(target.uri("$path/$id/file"), headers: target.authHeaders);
|
||||
if (res.statusCode == 200) return res.bodyBytes;
|
||||
return null;
|
||||
}
|
||||
@@ -465,12 +475,13 @@ class ApiClient {
|
||||
|
||||
// --- settings: avatar ---
|
||||
Future<UserProfile> uploadAvatar(List<int> bytes, String filename) async {
|
||||
final req = http.MultipartRequest("POST", _uri("/me/avatar"));
|
||||
if (token != null) req.headers["Authorization"] = "Bearer $token";
|
||||
final target = _target();
|
||||
final req = http.MultipartRequest("POST", target.uri("/me/avatar"))
|
||||
..headers.addAll(target.authHeaders);
|
||||
req.files.add(http.MultipartFile.fromBytes("avatar", bytes, filename: filename));
|
||||
final res = await http.Response.fromStream(await req.send());
|
||||
if (res.statusCode == 401) {
|
||||
onUnauthorized?.call();
|
||||
onUnauthorized?.call(target.id);
|
||||
throw ApiException(401, "Session expired — please log in again.");
|
||||
}
|
||||
final data = jsonDecode(res.body);
|
||||
@@ -482,8 +493,8 @@ class ApiClient {
|
||||
}
|
||||
|
||||
Future<List<int>?> getAvatarBytes() async {
|
||||
final res = await http.get(_uri("/me/avatar"),
|
||||
headers: {if (token != null) "Authorization": "Bearer $token"});
|
||||
final target = _target();
|
||||
final res = await http.get(target.uri("/me/avatar"), headers: target.authHeaders);
|
||||
if (res.statusCode == 200) return res.bodyBytes;
|
||||
return null;
|
||||
}
|
||||
@@ -507,10 +518,10 @@ class ApiClient {
|
||||
/// included. Returns the bytes and the filename the server named it, which is
|
||||
/// dated — the phone has to write the file itself, so it needs both.
|
||||
Future<(List<int>, String)> exportData() async {
|
||||
final res = await http.get(_uri("/me/export"),
|
||||
headers: {if (token != null) "Authorization": "Bearer $token"});
|
||||
final target = _target();
|
||||
final res = await http.get(target.uri("/me/export"), headers: target.authHeaders);
|
||||
if (res.statusCode == 401) {
|
||||
onUnauthorized?.call();
|
||||
onUnauthorized?.call(target.id);
|
||||
throw ApiException(401, "Session expired — please log in again.");
|
||||
}
|
||||
if (res.statusCode < 200 || res.statusCode >= 300) {
|
||||
|
||||
Reference in new issue
Block a user