pocketbase / dart-sdk

PocketBase Dart SDK
https://pub.dev/packages/pocketbase
MIT License
512 stars 51 forks source link

FormatException when making authenticated requests #1

Closed irmhonde closed 2 years ago

irmhonde commented 2 years ago

Description

"FormatException: Invalid length, must be multiple of four" is thrown when making authenticated requests. There is an open issue with the dart-sdk on this #39510

Steps to reproduce

  1. Running the following code.
import 'package:pocketbase/pocketbase.dart';

void main(List<String> args) async {
  final client = PocketBase('http://localhost:8090');
  const email = 'email';
  const password = 'password';
  final authData = await client.users.authViaEmail(email, password);
  final records = await client.records.getFullList('tasks');
}

Expected result

A list of records

Actual result

Format exception

Unhandled exception:
FormatException: Invalid length, must be multiple of four (at character 75)
eyJleHAiOjE2NjA1OjA3NRIsImlkIjoiUFg2c2oyVlJTcjlRbHpHIiwidHlwZSI6InVzZXIifQ
                                                                          ^

#0      _Base64Decoder.close (dart:convert/base64.dart:639:7)
#1      Base64Decoder.convert (dart:convert/base64.dart:510:13)
#2      Base64Codec.decode (dart:convert/base64.dart:83:47)
#3      base64Decode (dart:convert/base64.dart:52:49)
#4      AuthStore.isValid (package:pocketbase/src/auth_store.dart:41:32)
#5      PocketBase.send (package:pocketbase/src/client.dart:117:60)
#6      _BaseCrudService._getList (package:pocketbase/src/services/base_crud_service.dart:289:19)
#7      _BaseCrudService._getFullList.request (package:pocketbase/src/services/base_crud_service.dart:252:14)    
#8      _BaseCrudService._getFullList.request (package:pocketbase/src/services/base_crud_service.dart:251:28)    
#9      _BaseCrudService._getFullList (package:pocketbase/src/services/base_crud_service.dart:271:12)
#10     SubCrudService.getFullList (package:pocketbase/src/services/base_crud_service.dart:135:12)

Possible solution

Normalize the token sub-string first before decoding it

// pocketbase-0.1.0+4\lib\src\auth_store.dart

...
// Normalize the token sub-string first before decoding
final part = base64.normalize(parts[1]);
final data = jsonDecode(utf8.decode(base64Decode(part))) as Map<String, dynamic>;
...

Additional information

Will submit a PR with the above possible solution.

Environment

OS: Windows Dart SDK version: 2.17.6 (stable) (Tue Jul 12 12:54:37 2022 +0200) on "windows_x64"