RK

Search products

Search plugins, packages and apps, or jump to a section.

Laravel Rust Firebase

Use Firebase in a Laravel-Rust app: sign-in, push notifications, Firestore, Realtime Database, file storage and more.

Rust Crate
v0.1.18 downloads

Firebase for Laravel for Rust

Use Firebase in a Laravel for Rust application. It's modelled on laravel-firebase, the package for Laravel PHP, and covers the same services:

Service Inject What it does
Authentication Inject<Auth> Users, ID tokens, custom tokens, session cookies, email links
Cloud Messaging Inject<Messaging> Push notifications, topics, and a notification channel
Firestore Inject<Firestore> Documents, queries, batches, transactions
Realtime Database Inject<Database> Values, queries, transactions, rules
Cloud Storage Inject<Storage> Files and signed URLs
Remote Config Inject<RemoteConfig> Templates and their versions
App Check Inject<AppCheck> Tokens that prove requests come from your apps

Installation

cargo add laravel-rust-firebase

Register the service provider in src/app.rs:

Application::configure()
    .with_providers(|providers| {
        providers.add(firebase::FirebaseServiceProvider);
    })

Download a service account's JSON file from the Firebase console, under Project settings → Service accounts. Keep it out of Git, and name it in .env:

FIREBASE_CREDENTIALS=storage/app/firebase-auth.json

Or put the keys from that file in .env themselves:

FIREBASE_PROJECT_ID=my-app
FIREBASE_CLIENT_EMAIL=firebase-adminsdk-abc@my-app.iam.gserviceaccount.com
FIREBASE_PRIVATE_KEY="-----BEGIN PRIVATE KEY-----\nMIIE...\n-----END PRIVATE KEY-----\n"

Then check that it works:

cargo run -- firebase:check

Configuration

Firebase is optional: without credentials, the application starts as usual, and using Firebase returns an error. Check first with Inject<Firebase>:

if firebase.is_configured() {
    // Send the notification...
}

It's true when the environment or your configuration holds credentials.

Variable Purpose
FIREBASE_CREDENTIALS The service account: a path to its JSON file, or the JSON itself, in single quotes. Falls back to FIREBASE_CLIENT_EMAIL and FIREBASE_PRIVATE_KEY, then GOOGLE_APPLICATION_CREDENTIALS, then your gcloud login, then the Google Cloud machine's own account.
FIREBASE_PROJECT_ID The project ID. Defaults to the one in the credentials.
FIREBASE_DATABASE_URL The Realtime Database's URL. Required to use it.
FIREBASE_STORAGE_DEFAULT_BUCKET The default Storage bucket, such as my-app.firebasestorage.app.
FIREBASE_FIRESTORE_DATABASE The Firestore database. Defaults to (default).
FIREBASE_AUTH_TENANT_ID The Identity Platform tenant.
FIREBASE_HTTP_CLIENT_PROXY A proxy for every request.
FIREBASE_HTTP_CLIENT_TIMEOUT Seconds to wait for a response. Defaults to 30.
FIREBASE_PROJECT The default project's name. Defaults to app.

To use the local emulators, set FIREBASE_AUTH_EMULATOR_HOST, FIRESTORE_EMULATOR_HOST, FIREBASE_DATABASE_EMULATOR_HOST or FIREBASE_STORAGE_EMULATOR_HOST to their host:port. The Auth emulator's tokens aren't signed, so an application in production refuses to start with it.

Authentication

Your mobile or web app signs users in with Firebase, and sends their ID token as a bearer token. To log them in to your API, write a request guard that finds your own user for the token. This one expects a firebase_uid column:

use firebase::{Auth, FirebaseError};
use laravel::auth::RequestGuard;
use laravel::container::singleton;
use laravel::prelude::*;

use crate::models::User;

#[singleton]
pub struct FirebaseGuard;

impl RequestGuard for FirebaseGuard {
    type User = User;

    async fn user(&self, request: &Request) -> laravel::Result<Option<User>> {
        let Some(token) = request.bearer_token() else {
            return Ok(None);
        };

        let auth = laravel::resolve::<Auth>().await?;

        match auth.verify_id_token(&token).await {
            Ok(token) => User::first_where(User::firebase_uid.eq(token.uid)).await,
            Err(FirebaseError::InvalidToken(_)) => Ok(None),
            Err(error) => Err(error.into()),
        }
    }
}
route.middleware(Authenticate::via::<FirebaseGuard>()).group(|route| {
    route.get("/me", users::me);
});

verify_id_token checks the signature with Google's cached public keys. verify_id_token_strict also asks Firebase whether the token was revoked or its user disabled, which takes a request each time.

Manage users:

let user = auth
    .create_user(CreateUser::new().email("asha@example.com").password("secret-1"))
    .await?;

auth.update_user(&user.uid, UpdateUser::new().display_name("Asha")).await?;
auth.set_custom_claims(&user.uid, claims).await?;

let user = auth.get_user_by_email("asha@example.com").await?.or_abort(404)?;
let link = auth.email_link(EmailLink::PasswordReset, "asha@example.com", None).await?;

Push notifications

let message = Message::to_token(token)
    .notification("Order shipped", "It arrives on Friday.")
    .data("order_id", "42");

messaging.send(&message).await?;

send_to_tokens sends one message to several devices, and reports on each:

let report = messaging.send_to_tokens(&message, &tokens).await;

for token in report.unregistered_tokens() {
    // The app was uninstalled, so delete the token...
}

Or add the Fcm channel to a notification:

use firebase::{Fcm, Message};
use laravel::notification::Receives;

#[laravel::notification]
impl OrderShipped {
    #[via(Fcm)]
    fn push(&self, _user: &User) -> Message {
        Message::new().notification("Order shipped", "It arrives on Friday.")
    }
}

impl Receives<Fcm> for User {
    fn route(&self) -> Option<Vec<String>> {
        self.fcm_token.clone().map(|token| vec![token])
    }
}

The channel dispatches firebase::messaging::TokensUnregistered with the tokens of uninstalled apps, for you to delete.

A queued notification is tried again when Firebase is unreachable or busy. When Firebase refuses the message itself, the job fails at once.

Firestore

Read and write any Serde type:

#[derive(Serialize, Deserialize)]
struct City {
    name: String,
    population: u64,
    #[serde(with = "firebase::firestore::as_timestamp")]
    founded_at: Timestamp,
}

let cities = firestore.collection("cities");

cities.document("pune").set(&city).await?;
let city: City = cities.document("pune").get().await?.or_abort(404)?.data()?;

let large = cities
    .filter("population", Operator::GreaterThan, 1_000_000)
    .order_by("population", Direction::Descending)
    .limit(10)
    .get()
    .await?;

set replaces a document, merge changes only the fields you pass, and update takes paths and needs the document to exist:

cities.document("pune").update(json!({
    "address.state": "Maharashtra",
    "visits": firestore::increment(1),
    "seen_at": firestore::server_timestamp(),
})).await?;

Use firestore.batch() for writes that happen together, and firestore.transaction(..) for writes based on what you read. The package uses Firestore's REST API, which has no realtime listeners.

Realtime Database

let posts = database.reference("posts");

let post = posts.push(json!({ "title": "Hello" })).await?;
post.update(json!({ "title": "Hello, world" })).await?;

let recent: Option<BTreeMap<String, Post>> =
    posts.order_by_key().limit_to_last(10).get().await?;

database
    .reference("likes")
    .transaction(|likes: Option<u64>| likes.unwrap_or(0) + 1)
    .await?;

Storage

let bucket = storage.default_bucket()?;

bucket.upload_file("reports/q3.pdf", "storage/app/q3.pdf", "application/pdf").await?;
let url = bucket.signed_url("reports/q3.pdf", 15.minutes()).await?;

Remote Config

let mut template = remote_config.get().await?;
template.set("welcome_message", "Namaste!");
remote_config.publish(&template).await?;

App Check

let token = request.header("x-firebase-appcheck").or_abort(401)?;
app_check.verify_token(token).await?;

consume_token also makes sure the token wasn't used before.

Multiple projects

Inject<Firebase> has every project, and works as the default one:

firebase.auth();
firebase.project("admin")?.auth();

Add projects in src/app.rs:

use firebase::{FirebaseConfig, ProjectConfig};

Application::configure()
    .with_config(|config, env| {
        config.section_mut::<FirebaseConfig>().add_project("admin", ProjectConfig {
            credentials: env.get("FIREBASE_ADMIN_CREDENTIALS"),
            ..ProjectConfig::default()
        });
    })

Keys from your configuration or database

Pass the keys yourself, such as ones an admin entered:

use firebase::{Project, ProjectConfig};

let config = ProjectConfig::service_account(&project_id, &client_email, &private_key);
let project = Project::connect(config);

project.messaging().send(&message).await?;

To set them for the default project instead, do it in src/app.rs:

Application::configure()
    .with_config(|config, _| {
        config
            .section_mut::<FirebaseConfig>()
            .add_project("app", ProjectConfig::service_account(project_id, client_email, private_key));
    })

Errors

Every method returns a FirebaseError. error.code() is Firebase's own code:

match auth.create_user(user).await {
    Err(error) if error.code() == Some("EMAIL_EXISTS") => { /* ... */ }
    result => { /* ... */ }
}

Returned from a handler with ?, an invalid token responds 401, and a failure on Firebase's side 502 or 503.

Testing

Requests go through Laravel's HTTP client, so client::fake() intercepts them:

let http = client::fake()
    .with("oauth2.googleapis.com/*", json!({ "access_token": "fake", "expires_in": 3600 }))
    .with("fcm.googleapis.com/*", json!({ "name": "projects/acme/messages/1" }));

To run the package's own tests:

cargo test

firebase emulators:exec --project demo-laravel --config tests/emulators/firebase.json \
    "cargo test --test emulators -- --ignored"

Coming from Laravel PHP

The FIREBASE_* variables keep their names, with these differences:

  • FIREBASE_DATABASE_URL and FIREBASE_STORAGE_DEFAULT_BUCKET have no default, because Firebase no longer names them all after the project ID.
  • There's no FIREBASE_CACHE_STORE. Tokens and keys stay in the server's memory.
  • There are no log channels. Set LOG_LEVEL=info,laravel::http::client=debug to log requests.
  • A user or document that doesn't exist is None, not an error.

License

MIT. Your use of Firebase is governed by the Terms of Service for Firebase Services.

We only use essential cookies to keep you signed in, remember your cart and protect forms. No tracking or ads. Learn more