GithubHelp home page GithubHelp logo

saadardati / dartbase-admin-sdk Goto Github PK

View Code? Open in Web Editor NEW

This project forked from cachapa/firedart

6.0 1.0 3.0 287 KB

A dart-native implementation of the Firebase Admin SDK to enable administrive tasks to your firebase project.

Home Page: https://pub.dev/packages/dartbase_admin

License: Apache License 2.0

Dart 99.79% Shell 0.21%

dartbase-admin-sdk's Introduction

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.

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>, 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.

dartbase-admin-sdk's People

Contributors

cachapa avatar ekasetiawans avatar netantho avatar saadardati avatar seualiado avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.