supabase_task.dart 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. import 'package:appflowy/env/env.dart';
  2. import 'package:appflowy/workspace/application/settings/application_data_storage.dart';
  3. import 'package:flutter/foundation.dart';
  4. import 'package:supabase_flutter/supabase_flutter.dart';
  5. import 'package:hive_flutter/hive_flutter.dart';
  6. import 'package:path/path.dart' as p;
  7. import '../startup.dart';
  8. bool isSupabaseInitialized = false;
  9. const hiveBoxName = 'appflowy_supabase_authentication';
  10. class InitSupabaseTask extends LaunchTask {
  11. @override
  12. Future<void> initialize(LaunchContext context) async {
  13. if (!isSupabaseEnabled) {
  14. return;
  15. }
  16. if (isSupabaseInitialized) {
  17. return;
  18. }
  19. await Supabase.initialize(
  20. url: Env.supabaseUrl,
  21. anonKey: Env.supabaseAnonKey,
  22. debug: kDebugMode,
  23. localStorage: const SupabaseLocalStorage(),
  24. );
  25. }
  26. }
  27. /// customize the supabase auth storage
  28. ///
  29. /// We don't use the default one because it always save the session in the document directory.
  30. /// When we switch to the different folder, the session still exists.
  31. class SupabaseLocalStorage extends LocalStorage {
  32. const SupabaseLocalStorage()
  33. : super(
  34. initialize: _initialize,
  35. hasAccessToken: _hasAccessToken,
  36. accessToken: _accessToken,
  37. removePersistedSession: _removePersistedSession,
  38. persistSession: _persistSession,
  39. );
  40. static Future<void> _initialize() async {
  41. HiveCipher? encryptionCipher;
  42. // customize the path for Hive
  43. final path = await getIt<ApplicationDataStorage>().getPath();
  44. Hive.init(p.join(path, 'supabase_auth'));
  45. await Hive.openBox(
  46. hiveBoxName,
  47. encryptionCipher: encryptionCipher,
  48. );
  49. }
  50. static Future<bool> _hasAccessToken() {
  51. return Future.value(
  52. Hive.box(hiveBoxName).containsKey(
  53. supabasePersistSessionKey,
  54. ),
  55. );
  56. }
  57. static Future<String?> _accessToken() {
  58. return Future.value(
  59. Hive.box(hiveBoxName).get(supabasePersistSessionKey) as String?,
  60. );
  61. }
  62. static Future<void> _removePersistedSession() {
  63. return Hive.box(hiveBoxName).delete(supabasePersistSessionKey);
  64. }
  65. static Future<void> _persistSession(String persistSessionString) {
  66. return Hive.box(hiveBoxName).put(
  67. supabasePersistSessionKey,
  68. persistSessionString,
  69. );
  70. }
  71. }