Initial commit

This commit is contained in:
St. Nebula
2026-04-23 23:58:59 -05:00
commit 47b9e3c159
257 changed files with 18913 additions and 0 deletions
@@ -0,0 +1,86 @@
---
name: firebase-auth-basics
description: Guide for setting up and using Firebase Authentication. Use this skill when the user's app requires user sign-in, user management, or secure data access using auth rules.
compatibility: This skill is best used with the Firebase CLI, but does not require it. Firebase CLI can be accessed through `npx -y firebase-tools@latest`.
---
## Prerequisites
- **Firebase Project**: Created via `npx -y firebase-tools@latest projects:create` (see `firebase-basics`).
- **Firebase CLI**: Installed and logged in (see `firebase-basics`).
## Core Concepts
Firebase Authentication provides backend services, easy-to-use SDKs, and ready-made UI libraries to authenticate users to your app.
### Users
A user is an entity that can sign in to your app. Each user is identified by a unique ID (`uid`) which is guaranteed to be unique across all providers.
User properties include:
- `uid`: Unique identifier.
- `email`: User's email address (if available).
- `displayName`: User's display name (if available).
- `photoURL`: URL to user's photo (if available).
- `emailVerified`: Boolean indicating if the email is verified.
### Identity Providers
Firebase Auth supports multiple ways to sign in:
- **Email/Password**: Basic email and password authentication.
- **Federated Identity Providers**: Google, Facebook, Twitter, GitHub, Microsoft, Apple, etc.
- **Phone Number**: SMS-based authentication.
- **Anonymous**: Temporary guest accounts that can be linked to permanent accounts later.
- **Custom Auth**: Integrate with your existing auth system.
Google Sign In is recommended as a good and secure default provider.
### Tokens
When a user signs in, they receive an ID Token (JWT). This token is used to identify the user when making requests to Firebase services (Realtime Database, Cloud Storage, Firestore) or your own backend.
- **ID Token**: Short-lived (1 hour), verifies identity.
- **Refresh Token**: Long-lived, used to get new ID tokens.
## Workflow
### 1. Provisioning
#### Option 1. Enabling Authentication via CLI
Only Google Sign In, anonymous auth, and email/password auth can be enabled via CLI. For other providers, use the Firebase Console.
Configure Firebase Authentication in `firebase.json` by adding an 'auth' block:
```
{
"auth": {
"providers": {
"anonymous": true,
"emailPassword": true,
"googleSignIn": {
"oAuthBrandDisplayName": "Your Brand Name",
"supportEmail": "support@example.com",
"authorizedRedirectUris": ["https://example.com"]
}
}
}
}
```
#### Option 2. Enabling Authentication in Console
Enable other providers in the Firebase Console.
1. Go to the https://console.firebase.google.com/project/_/authentication/providers
2. Select your project.
3. Enable the desired Sign-in providers (e.g., Email/Password, Google).
### 2. Client Setup & Usage
**Web**
See [references/client_sdk_web.md](references/client_sdk_web.md).
### 3. Security Rules
Secure your data using `request.auth` in Firestore/Storage rules.
See [references/security_rules.md](references/security_rules.md).
@@ -0,0 +1,287 @@
# Firebase Authentication Web SDK
## Initialization
First, ensure you have initialized the Firebase App (see `firebase-basics` skill). Then, initialize the Auth service:
```javascript
import { getAuth } from "firebase/auth";
import { app } from "./firebase"; // Your initialized Firebase App
const auth = getAuth(app);
export { auth };
```
## Connect to Emulator
If you are running the Authentication emulator (usually on port 9099), connect to it immediately after initialization.
```javascript
import { getAuth, connectAuthEmulator } from "firebase/auth";
const auth = getAuth();
// Connect to emulator if running locally
if (location.hostname === "localhost") {
connectAuthEmulator(auth, "http://localhost:9099");
}
```
## Sign Up with Email/Password
```javascript
import { getAuth, createUserWithEmailAndPassword } from "firebase/auth";
const auth = getAuth();
createUserWithEmailAndPassword(auth, email, password)
.then((userCredential) => {
const user = userCredential.user;
// ...
})
.catch((error) => {
const errorCode = error.code;
const errorMessage = error.message;
// ..
});
```
## Sign In with Google (Popup)
```javascript
import { getAuth, signInWithPopup, GoogleAuthProvider } from "firebase/auth";
const auth = getAuth();
const provider = new GoogleAuthProvider();
signInWithPopup(auth, provider)
.then((result) => {
// This gives you a Google Access Token. You can use it to access the Google API.
const credential = GoogleAuthProvider.credentialFromResult(result);
const token = credential.accessToken;
// The signed-in user info.
const user = result.user;
// ...
})
.catch((error) => {
// Handle Errors here.
const errorCode = error.code;
const errorMessage = error.message;
// ...
});
```
## Sign In with Facebook (Popup)
```javascript
import { getAuth, signInWithPopup, FacebookAuthProvider } from "firebase/auth";
const auth = getAuth();
const provider = new FacebookAuthProvider();
signInWithPopup(auth, provider)
.then((result) => {
// The signed-in user info.
const user = result.user;
// This gives you a Facebook Access Token. You can use it to access the Facebook API.
const credential = FacebookAuthProvider.credentialFromResult(result);
const accessToken = credential.accessToken;
})
.catch((error) => {
// Handle Errors here.
});
```
## Sign In with Apple (Popup)
```javascript
import { getAuth, signInWithPopup, OAuthProvider } from "firebase/auth";
const auth = getAuth();
const provider = new OAuthProvider('apple.com');
signInWithPopup(auth, provider)
.then((result) => {
const user = result.user;
// Apple credential
const credential = OAuthProvider.credentialFromResult(result);
const accessToken = credential.accessToken;
})
.catch((error) => {
// Handle Errors here.
});
```
## Sign In with Twitter (Popup)
```javascript
import { getAuth, signInWithPopup, TwitterAuthProvider } from "firebase/auth";
const auth = getAuth();
const provider = new TwitterAuthProvider();
signInWithPopup(auth, provider)
.then((result) => {
const user = result.user;
// Twitter credential
const credential = TwitterAuthProvider.credentialFromResult(result);
const token = credential.accessToken;
const secret = credential.secret;
})
.catch((error) => {
// Handle Errors here.
});
```
## Sign In with GitHub (Popup)
```javascript
import { getAuth, signInWithPopup, GithubAuthProvider } from "firebase/auth";
const auth = getAuth();
const provider = new GithubAuthProvider();
signInWithPopup(auth, provider)
.then((result) => {
const user = result.user;
const credential = GithubAuthProvider.credentialFromResult(result);
const token = credential.accessToken;
})
.catch((error) => {
// Handle Errors here.
});
```
## Sign In with Microsoft (Popup)
```javascript
import { getAuth, signInWithPopup, OAuthProvider } from "firebase/auth";
const auth = getAuth();
const provider = new OAuthProvider('microsoft.com');
signInWithPopup(auth, provider)
.then((result) => {
const user = result.user;
const credential = OAuthProvider.credentialFromResult(result);
const accessToken = credential.accessToken;
})
.catch((error) => {
// Handle Errors here.
});
```
## Sign In with Yahoo (Popup)
```javascript
import { getAuth, signInWithPopup, OAuthProvider } from "firebase/auth";
const auth = getAuth();
const provider = new OAuthProvider('yahoo.com');
signInWithPopup(auth, provider)
.then((result) => {
const user = result.user;
const credential = OAuthProvider.credentialFromResult(result);
const accessToken = credential.accessToken;
})
.catch((error) => {
// Handle Errors here.
});
```
## Sign In Anonymously
```javascript
import { getAuth, signInAnonymously } from "firebase/auth";
const auth = getAuth();
signInAnonymously(auth)
.then(() => {
// Signed in..
})
.catch((error) => {
const errorCode = error.code;
const errorMessage = error.message;
});
```
## Email Link Authentication
**1. Send Auth Link**
```javascript
import { getAuth, sendSignInLinkToEmail } from "firebase/auth";
const auth = getAuth();
const actionCodeSettings = {
// URL you want to redirect back to. The domain must be in the authorized domains list in Firebase Console.
url: 'https://www.example.com/finishSignUp?cartId=1234',
handleCodeInApp: true,
};
sendSignInLinkToEmail(auth, email, actionCodeSettings)
.then(() => {
// Save the email locally so you don't need to ask the user for it again
window.localStorage.setItem('emailForSignIn', email);
})
.catch((error) => {
// Error
});
```
**2. Complete Sign In (on landing page)**
```javascript
import { getAuth, isSignInWithEmailLink, signInWithEmailLink } from "firebase/auth";
const auth = getAuth();
if (isSignInWithEmailLink(auth, window.location.href)) {
let email = window.localStorage.getItem('emailForSignIn');
if (!email) {
email = window.prompt('Please provide your email for confirmation');
}
signInWithEmailLink(auth, email, window.location.href)
.then((result) => {
window.localStorage.removeItem('emailForSignIn');
// You can check result.user
})
.catch((error) => {
// Error
});
}
```
## Observe Auth State
Recommended way to get the current user. This listener triggers whenever the user signs in or out.
```javascript
import { getAuth, onAuthStateChanged } from "firebase/auth";
const auth = getAuth();
onAuthStateChanged(auth, (user) => {
if (user) {
// User is signed in, see docs for a list of available properties
// https://firebase.google.com/docs/reference/js/firebase.User
const uid = user.uid;
// ...
} else {
// User is signed out
// ...
}
});
```
## Sign Out
```javascript
import { getAuth, signOut } from "firebase/auth";
const auth = getAuth();
signOut(auth).then(() => {
// Sign-out successful.
}).catch((error) => {
// An error happened.
});
```
@@ -0,0 +1,38 @@
# Authentication in Security Rules
Firebase Security Rules work with Firebase Authentication to provide rule-based access control. For better advice on writing safe security rules,
enable the `firebase-firestore-basics` or `firebase-storage-basics` skills.
The `request.auth` variable contains authentication information for the user requesting data.
## Basic Checks
### Check if user is signed in
```
allow read, write: if request.auth != null;
```
### Check if user owns the data
Access data only if the document ID matches the user's UID.
```
allow read, write: if request.auth != null && request.auth.uid == userId;
```
(Where `userId` is a path variable, e.g., `match /users/{userId}`)
### Check if user owns the document (field-based)
Access data only if the document has a `owner_uid` field matching the user's UID.
```
allow read, write: if request.auth != null && request.auth.uid == resource.data.owner_uid;
```
## Token Properties
`request.auth.token` contains standard JWT claims and custom claims.
- `request.auth.token.email`: The user's email address.
- `request.auth.token.email_verified`: If the email is verified.
- `request.auth.token.name`: The user's display name.
### Example: Email Verification Check
```
allow create: if request.auth.token.email_verified == true;
```