Files
pipelines/app/lib/core/session/server_session.dart
T

96 lines
3.1 KiB
Dart

import 'package:shared_preferences/shared_preferences.dart';
import 'server_session_stub.dart'
if (dart.library.io) 'server_session_io.dart'
as impl;
/// The web sign-in the app carries on a phone.
///
/// A browser keeps the server's login cookie itself. The native app signs in
/// with the same password, keeps the returned session cookie, and sends it on
/// the websocket and on file downloads, so it can reach a server that sits
/// behind the web login (for example over Tailscale). A server with no login
/// needs none of this.
class ServerSession {
ServerSession._();
static const _key = 'pipelines.session.cookie';
/// The `name=value` session cookie, or null when signed out.
static String? cookie;
/// Headers that carry the session, empty when signed out.
static Map<String, String> get headers {
final value = cookie;
return value == null || value.isEmpty ? const {} : {'Cookie': value};
}
static Future<void> load() async {
try {
final prefs = await SharedPreferences.getInstance();
cookie = prefs.getString(_key);
} catch (_) {
cookie = null;
}
}
static Future<void> _save(String? value) async {
cookie = value;
try {
final prefs = await SharedPreferences.getInstance();
if (value == null) {
await prefs.remove(_key);
} else {
await prefs.setString(_key, value);
}
} catch (_) {}
}
/// Signs in at the web login beside [endpoint] (its `/login` page) with
/// [password] and keeps the session. Returns null on success, otherwise
/// what went wrong in words.
static Future<String?> signIn(Uri endpoint, String password) async {
final login = loginUriFor(endpoint);
if (login == null) return 'The server address has no web login.';
final result = await impl.postLogin(login, password);
if (result.cookie != null) {
await _save(result.cookie);
return null;
}
return result.error ?? 'Sign-in failed.';
}
static Future<void> signOut() => _save(null);
/// Whether [endpoint]'s server accepts the kept session.
static Future<SessionState> check(Uri endpoint) async {
final login = loginUriFor(endpoint);
if (login == null) return SessionState.unreachable;
final status = await impl.probeLogin(login, headers);
if (status == null) return SessionState.unreachable;
// The web login sends a signed-in visitor on; it shows its form otherwise.
if (status >= 300 && status < 400) return SessionState.signedIn;
if (status == 200) return SessionState.signedOut;
return SessionState.unreachable;
}
}
/// What a server says about this device's session.
enum SessionState { signedIn, signedOut, unreachable }
/// The web login page for a websocket endpoint: same host and port, http(s).
Uri? loginUriFor(Uri endpoint) {
final scheme = switch (endpoint.scheme) {
'wss' || 'https' => 'https',
'ws' || 'http' => 'http',
_ => null,
};
if (scheme == null || endpoint.host.isEmpty) return null;
return Uri(
scheme: scheme,
host: endpoint.host,
port: endpoint.hasPort ? endpoint.port : null,
path: '/login',
);
}