import 'dart:convert'; import 'package:http/http.dart' as http; /// Minimal docwell-server client. Will be replaced by a client generated /// from api/openapi.yaml. class DocwellApi { DocwellApi(String baseUrl, {http.Client? client}) : baseUrl = baseUrl.replaceAll(RegExp(r'/+$'), ''), _client = client ?? http.Client(); final String baseUrl; final http.Client _client; /// PocketBase auth token of the signed-in user, sent as a bearer token. String? token; Future version() async { final body = await _send('GET', '/api/v1/version'); return body['version'] as String; } /// Signs in with email and password and keeps the token for later calls. Future login(String email, String password) async { final body = await _send('POST', '/api/v1/auth/login', { 'email': email, 'password': password, }); token = body['token'] as String; return User.fromJson(body['user'] as Map); } Future me() async => User.fromJson(await _send('GET', '/api/v1/auth/me')); void logout() => token = null; Future> _send( String method, String path, [ Object? body, ]) async { final req = http.Request(method, Uri.parse('$baseUrl$path')); req.headers['Accept'] = 'application/json'; if (token != null) req.headers['Authorization'] = 'Bearer $token'; if (body != null) { req.headers['Content-Type'] = 'application/json'; req.body = jsonEncode(body); } final res = await http.Response.fromStream( await _client.send(req).timeout(const Duration(seconds: 15)), ); final data = res.body.isEmpty ? {} : jsonDecode(res.body) as Map; if (res.statusCode >= 300) { throw DocwellApiException( res.statusCode, data['error'] as String? ?? 'unknown', ); } return data; } } class User { User({ required this.id, required this.email, required this.name, this.role = 'user', this.organization = '', this.organizationName = '', }); factory User.fromJson(Map json) => User( id: json['id'] as String, email: json['email'] as String, name: json['name'] as String, role: json['role'] as String? ?? 'user', organization: json['organization'] as String? ?? '', organizationName: json['organizationName'] as String? ?? '', ); final String id; final String email; final String name; /// Instance role: user, admin (of their organization) or superadmin. final String role; final String organization; final String organizationName; bool get isManager => role == 'admin' || role == 'superadmin'; } class DocwellApiException implements Exception { DocwellApiException(this.status, [this.code = 'unknown']); final int status; /// Machine-readable error code from the server, e.g. "invalid_credentials". final String code; @override String toString() => 'Docwell API error $status ($code)'; }