dartbase_admin 0.1.3

  • Readme
  • Changelog
  • Example
  • Installing
  • new72

Dartbase Admin SDK™️ #

Dart CI

A dart-native implementation of the Firebase Admin SDK.

This library is a fork of cachapa's client firebase sdk; cachapa/firedart; modified and converted to support admin only firebase features. This library also uses these files from appsup-dart/firebase_admin to enable admin authentication to firebase because it is not documented on firebase's official documentation (May 2020):

  • user_record.dart.
  • token_handler.dart

Currently supported: #

  • Firebase Auth
  • Firestore
  • Firebase Storage
  • Firebase Cloud Messaging

Installing #

Add dartbase to your pubspec.yaml file:

dependencies:
  dartbase_admin: [latest version]

Setup & Usage #

import 'package:dartbase_admin/dartbase.dart';

To begin, you need to initialize Firebase:

  • You can initialize the global singleton instance provided by the package that you can access anywhere.

  • You can initialize a new local instance of Firebase as a variable and as many times as you want. You can pass that instance to all the other Firebase features, but if you don't, they default back to the global instance.

Global Instance #

await Firebase.initialize(projectId, ServiceAccount);

var firebase = Firebase.instance;

Local Instance #

var firebase = Firebase(projectId, ServiceAccount);

await firebase.init();

ServiceAccount #

You can reference a service account through several means:

First way:

ServiceAccount.fromEnvironmentVariable('Environment Variable Key');

If you do NOT specify an environment variable key, it will fallback to GOOGLE_APPLICATION_CREDENTIALS

Second way:

ServiceAccount.fromJson(r'''
{
      Project Settings -> Service Accounts -> generate new private key
      Paste the json here
}
''');

Third way:

await ServiceAccount.fromFile(serviceAccountFilePath);

Firebase Auth #

The FirebaseAuth class will let you control administrative tasks related to user management.

Currently, the feature-set for it is very limited, but the available methods are:

Get a user #

UserRecord user = await FirebaseAuth.instance.getUserById(uid);

The UserRecord object holds data like id, email, profilePicture, etc...

Verify an ID Token #

try {
    String id = await FirebaseAuth.instance.verifyIdToken(<client token>, enforceEmailVerification: true, checkRevoked: true);
} catch (e) {
    print(e);
}

The client token can be acquired from any client using a Firebase Client SDK of any kind. There should be a method called firebase.currentUser.idToken() (or something along those lines) that gives you an id token you can send to your backend, waiting to be processed by this method here.

The returned id is the user's id. This method will throw an exception if verification does not succeed, with a descriptive exception message.

Further usage examples can be found in the integration tests.

Firestore #

This will give you ADMIN access to firestore, be careful. The Firestore class implements the necessary functionality for a usable firestore implementation.

Usage #

  // Instantiate a reference to a document - this happens offline
  var ref = Firestore.instance.collection('test').document('doc');

  // Subscribe to changes to that document
  ref.stream.listen((document) => print('updated: $document'));

  // Update the document
  await ref.update({'value': 'test'});

  // Get a snapshot of the document
  var document = await ref.get();
  print('snapshot: ${document['value']}');

  print(
      'Sleeping for 30 seconds. You can make changes to test/doc in the UI console');
  await Future.delayed((const Duration(seconds: 30)));

  print('closing the connection');
  await Firestore.instance.close();

Further usage examples can be found in the integration tests.

Limitations #

  • The data is not cached locally.
  • Failed writes (e.g. due to network errors) are not retried.
  • Closed streams are not automatically recovered.

Firebase Storage #

The FirebaseStorage class implements the necessary functionality for bucket interactions with firebase. Note that it is a wrapper from gcloud and made io-safe. It does not reference dart:io

Usage #

There is no global/local instances to initialize here. You can reference a Bucket at any time as a local variable anywhere.

The storageURL looks like so: <project-id>.appspot.com

var bucket = await FirebaseStorage.getBucket(storageUrl);

/// UPLOAD
await bucket.upload('remoteDirectory/remoteFile.jpg', localFile.absolute.path);

/// INFO
var info = await bucket.info('remoteDirectory/remoteFile.jpg');

/// DOWNLOAD
await bucket.download('remoteDirectory/remoteFile.jpg', localFile.absolute.path);

/// LIST
var list = await (await bucket.list(prefix: 'remoteDirectory/')).toList();

/// DELETE
await bucket.delete('remoteDirectory/remoteFile.jpg');

Several helper methods exist for uploading and downloading if you explore the FirebaseStorage class.

More advanced usages and further usage examples can be found in the integration tests.

Firebase Cloud Messaging #

The FCM class implements the necessary functionality for sending cloud messages.

Make sure you've enabled Cloud Messaging in the Firebase Console, also enroll a test device there. You'll also need to go to open Project Settings and under the Cloud Messaging tab copy the Server key.

Usage #

Then in your main script:

import 'package:dartbase_admin/dartbase.dart';
import 'package:dartbase_admin/fcm/message.dart';

const cloudMessagingServerKey = 'Project settings -> Cloud Messaging -> Server key';

main() async {

  var firebase = await Firebase.initialize(projectId,
      await ServiceAccount.fromFile(serviceAccountPath));
  var fcm = FCM(firebase, FCMConfig(firebase.projectId));
  const token = '<Your device token here>';
  const topic = '<Choose a topic name>';

  // Send to a token
  var message = Message(
    token: token,
    notification: MessageNotification(
      title: "plantyplants test",
      body: "Some body text here",
    ),
  );
  var nameTopicMessage = await fcm.send(message);

  // Send to a topic
  var message = Message(
    topic: topic,
    notification: MessageNotification(
      title: "plantyplants test",
      body: "Some body text here",
    ),
  );
  var nameTopicMessage = await fcm.send(message);

  return;
}

Further usage examples can be found in the integration tests.

Limitations #

  • Doesn't support batch send.
  • Doesn't support receiving a cloud message.

[0.1.3] - 19 June 2020 #

  • Fix pana not recognizing main class

[0.1.2] - 14 June 2020 #

  • Update example and tests

[0.1.1] - 14 June 2020 #

  • Align package for publishing

example/example.dart

import 'package:dartbase_admin/dartbase_admin.dart';
import 'package:dartbase_admin/fcm/message.dart';

const projectId = 'Project Settings -> General -> Project ID';
const storageUrl =
    'Bucket name without gs://, should look like <project-id>.appspot.com';

/// Note: Beware of pushing your credentials to source control.
void main() async {
  /// You can use environment variable look-up to find your service-account.json like so:
  /// (GOOGLE_APPLICATION_CREDENTIALS is the default environment variable we look for.)
  /// ServiceAccount.fromEnvironmentVariable();
  /// or from a file
  /// ServiceAccount.fromFile(filePath);
  /// or directly from a json string
  /// ServiceAccount.fromJson(String);
  await Firebase.initialize(projectId, ServiceAccount.fromJson(r'''
{
      Project Settings -> Service Accounts -> generate new private key
      Paste the json here
}
'''));

  await firestoreExample();
  await firebaseStorageExample();
  await authExample();
  await fcmExample();
}

void firestoreExample() async {
  /// Initialize the global firestore instance.
  /// Firestore fall back to the global firebase instance we initialized in main().
  Firestore.initialize();

  /// Instantiate a reference to a document - this happens offline.
  var ref = Firestore.instance.collection('test').document('doc');

  /// Subscribe to changes to that document.
  ref.stream.listen((document) => print('updated: $document'));

  /// Update the document
  await ref.update({'value': 'test'});

  /// Get a snapshot of the document
  var document = await ref.get();
  print('snapshot: ${document['value']}');
}

void firebaseStorageExample() async {
  /// FirebaseStorage doesn't have a global instance. You just get a bucket reference whenever you need it.
  var bucket = await FirebaseStorage.getBucket(storageUrl);
  var localFilePath = 'path/to/your/file.jpg';

  /// UPLOAD
  await bucket.upload('remoteDirectory/remoteFile.jpg', localFilePath);

  /// INFO
  var info = await bucket.info('remoteDirectory/remoteFile.jpg');
  print(info.downloadLink);

  /// DOWNLOAD
  await bucket.download('remoteDirectory/remoteFile.jpg', localFilePath);

  /// LIST
  var list = await (await bucket.list(prefix: 'remoteDirectory/')).toList();
  print(list.map((info) => info.name).join(','));

  /// DELETE
  await bucket.delete('remoteDirectory/remoteFile.jpg');
}

void authExample() async {
  /// Initialize the global firebase auth instance.
  /// Firebase Auth will fall back to the global firebase instance we initialized in main().
  await FirebaseAuth.initialize();

  try {
    /// Get the user id from a client generate id token through verification.
    /// A bad token will throw an exception.
    var userId = await FirebaseAuth.instance.verifyIdToken(
        'A client generated id token.',
        checkRevoked: true,
        enforceEmailVerification: true);

    /// We can use that id to get the user object or pass any user id we want that
    /// signed up to our project's firebase auth flow.
    var user = await FirebaseAuth.instance.getUserById(userId);
    print(user.displayName);
  } catch (e) {
    /// If the token is revoked, you will know here.
    print('User has a revoked token!');
    print(e);
  }
}

void fcmExample() async {
  /// Initialize the global FCM instance.
  /// FCM fall back to the global firebase instance we initialized in main().
  await FCM.initialize();

  /// Create a message to send. Many options exist here.
  var message = Message(
    topic: 'Some topic',
    notification: MessageNotification(
      title: 'Some title',
      body: 'Some body text here',
    ),
  );

  /// Send the message and return the firebase-assigned name of the message.
  var name = await FCM.instance.send(message);

  print('Firebase-assigned message name: $name');
}

Use this package as a library

1. Depend on it

Add this to your package's pubspec.yaml file:


dependencies:
  dartbase_admin: ^0.1.3

2. Install it

You can install packages from the command line:

with pub:


$ pub get

with Flutter:


$ flutter pub get

Alternatively, your editor might support pub get or flutter pub get. Check the docs for your editor to learn more.

3. Import it

Now in your Dart code, you can use:


import 'package:dartbase_admin/dartbase_admin.dart';
  
Popularity:
Describes how popular the package is relative to other packages. [more]
48
Health:
Code health derived from static analysis. [more]
100
Maintenance:
Reflects how tidy and up-to-date the package is. [more]
90
Overall:
Weighted score of the above. [more]
72
Learn more about scoring.

We analyzed this package on Jul 14, 2020, and provided a score, details, and suggestions below. Analysis was completed with status completed using:

  • Dart: 2.8.4
  • pana: 0.13.15

Analysis suggestions

Package not compatible with runtime flutter-web on Web

Because:

  • package:dartbase_admin/dartbase_admin.dart that imports:
  • package:dartbase_admin/storage/firebase_storage.dart that imports:
  • package:googleapis_auth/auth_io.dart that imports:
  • package:googleapis_auth/src/oauth2_flows/metadata_server.dart that imports:
  • dart:io

Package not compatible with runtime js

Because:

  • package:dartbase_admin/dartbase_admin.dart that imports:
  • package:dartbase_admin/storage/firebase_storage.dart that imports:
  • package:googleapis_auth/auth_io.dart that imports:
  • package:googleapis_auth/src/oauth2_flows/metadata_server.dart that imports:
  • dart:io

Maintenance issues and suggestions

Support latest dependencies. (-10 points)

The version constraint in pubspec.yaml does not support the latest published versions for 1 dependency (jose).

Dependencies

Package Constraint Resolved Available
Direct dependencies
Dart SDK >=2.3.0 <3.0.0
asn1lib ^0.6.4 0.6.5
clock ^1.0.1 1.0.1
crypto_keys ^0.1.2 0.1.3
fixnum ^0.10.11 0.10.11
gcloud ^0.7.0+1 0.7.3
googleapis_auth ^0.2.11 0.2.12
grpc ^2.1.3 2.2.0
http ^0.12.1 0.12.1
jose ^0.1.2+1 0.1.2+1 0.2.1+1
json_annotation ^3.0.1 3.0.1
meta ^1.1.8 1.2.2 1.3.0-nullsafety
openid_client ^0.2.5 0.2.5
pointycastle ^1.0.2 1.0.2
protobuf ^1.0.1 1.0.1
x509 ^0.1.0+1 0.1.2+1
Transitive dependencies
_discoveryapis_commons 0.2.0
args 1.6.0
async 2.4.2
built_collection 4.3.2
built_value 7.1.0
charcode 1.1.3
collection 1.14.13 1.15.0-nullsafety
convert 2.1.1
crypto 2.1.5
googleapis 0.55.0
http2 1.0.0
http_parser 3.1.4
logging 0.11.4
matcher 0.12.9
path 1.7.0
quiver 2.1.3
source_span 1.7.0
stack_trace 1.9.5
string_scanner 1.0.5
term_glyph 1.1.0
typed_data 1.2.0 1.3.0-nullsafety
Dev dependencies
build_runner ^1.10.0
firedart ^0.8.0+1
json_serializable ^3.3.0
pedantic ^1.9.0 1.9.2
test ^1.14.3