Skip to content

Commit eba953d

Browse files
committed
Update auth snippets
1 parent 762c22a commit eba953d

9 files changed

+71
-97
lines changed

auth/create_custom_tokens.js

Lines changed: 6 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,23 +1,23 @@
11
'use strict';
2-
const admin = require('firebase-admin');
2+
import { initializeApp } from 'firebase-admin/app';
3+
import { getAuth } from 'firebase-admin/auth';
34

45
// Initialize the Admin app with the default appication credentials
56
// [START initialize_sdk_with_default_config]
6-
admin.initializeApp();
7+
initializeApp();
78
// [END initialize_sdk_with_default_config]
89

910
// Initialize the Admin app by providing a service accoune key
1011
// [START initialize_sdk_with_service_account_id]
11-
admin.initializeApp({
12+
initializeApp({
1213
serviceAccountId: '[email protected]',
1314
});
1415
// [END initialize_sdk_with_service_account_id]
1516

1617
// [START custom_token]
1718
const uid = 'some-uid';
1819

19-
admin
20-
.auth()
20+
getAuth()
2121
.createCustomToken(uid)
2222
.then((customToken) => {
2323
// Send token back to client
@@ -33,8 +33,7 @@ const additionalClaims = {
3333
premiumAccount: true,
3434
};
3535

36-
admin
37-
.auth()
36+
getAuth()
3837
.createCustomToken(userId, additionalClaims)
3938
.then((customToken) => {
4039
// Send token back to client

auth/custom_claims.js

Lines changed: 10 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,15 @@
11
'use strict';
2-
const admin = require('firebase-admin');
3-
admin.initializeApp();
2+
import { initializeApp } from 'firebase-admin/app';
3+
import { getAuth } from 'firebase-admin/auth';
4+
initializeApp();
45

56
const uid = 'firebaseUserId123';
67
const idToken = 'some-invalid-token';
78

89
// [START set_custom_user_claims]
910
// Set admin privilege on the user corresponding to uid.
1011

11-
admin
12-
.auth()
12+
getAuth()
1313
.setCustomUserClaims(uid, { admin: true })
1414
.then(() => {
1515
// The new custom claims will propagate to the user's ID token the
@@ -19,8 +19,7 @@ admin
1919

2020
// [START verify_custom_claims]
2121
// Verify the ID token first.
22-
admin
23-
.auth()
22+
getAuth()
2423
.verifyIdToken(idToken)
2524
.then((claims) => {
2625
if (claims.admin === true) {
@@ -31,8 +30,7 @@ admin
3130

3231
// [START read_custom_user_claims]
3332
// Lookup the user associated with the specified uid.
34-
admin
35-
.auth()
33+
getAuth()
3634
.getUser(uid)
3735
.then((userRecord) => {
3836
// The claims can be accessed on the user record.
@@ -41,15 +39,14 @@ admin
4139
// [END read_custom_user_claims]
4240

4341
// [START set_custom_user_claims_script]
44-
admin
45-
.auth()
42+
getAuth()
4643
.getUserByEmail('[email protected]')
4744
.then((user) => {
4845
// Confirm user is verified.
4946
if (user.emailVerified) {
5047
// Add custom claims for additional privileges.
5148
// This will be picked up by the user on token refresh or next sign in on new device.
52-
return admin.auth().setCustomUserClaims(user.uid, {
49+
return getAuth().setCustomUserClaims(user.uid, {
5350
admin: true,
5451
});
5552
}
@@ -60,8 +57,7 @@ admin
6057
// [END set_custom_user_claims_script]
6158

6259
// [START set_custom_user_claims_incremental]
63-
admin
64-
.auth()
60+
getAuth()
6561
.getUserByEmail('[email protected]')
6662
.then((user) => {
6763
// Add incremental custom claim without overwriting existing claims.
@@ -70,7 +66,7 @@ admin
7066
// Add level.
7167
currentCustomClaims['accessLevel'] = 10;
7268
// Add custom claims for additional privileges.
73-
return admin.auth().setCustomUserClaims(user.uid, currentCustomClaims);
69+
return getAuth().setCustomUserClaims(user.uid, currentCustomClaims);
7470
}
7571
})
7672
.catch((error) => {

auth/email_action_links.js

Lines changed: 7 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
'use strict';
2-
const admin = require('firebase-admin');
3-
admin.initializeApp();
2+
import { initializeApp } from 'firebase-admin/app';
3+
import { getAuth } from 'firebase-admin/auth';
4+
initializeApp();
45

56
// [START init_action_code_settings]
67
const actionCodeSettings = {
@@ -25,8 +26,7 @@ const actionCodeSettings = {
2526
// [START password_reset_link]
2627
// Admin SDK API to generate the password reset link.
2728
const userEmail = '[email protected]';
28-
admin
29-
.auth()
29+
getAuth()
3030
.generatePasswordResetLink(userEmail, actionCodeSettings)
3131
.then((link) => {
3232
// Construct password reset email template, embed the link and send
@@ -41,8 +41,7 @@ admin
4141
// [START email_verification_link]
4242
// Admin SDK API to generate the password reset link.
4343
const email = '[email protected]';
44-
admin
45-
.auth()
44+
getAuth()
4645
.generatePasswordResetLink(email, actionCodeSettings)
4746
.then((link) => {
4847
// Construct password reset email template, embed the link and send
@@ -56,8 +55,7 @@ admin
5655
// [START email_verification_link]
5756
// Admin SDK API to generate the email verification link.
5857
const useremail = '[email protected]';
59-
admin
60-
.auth()
58+
getAuth()
6159
.generateEmailVerificationLink(useremail, actionCodeSettings)
6260
.then((link) => {
6361
// Construct email verification template, embed the link and send
@@ -72,8 +70,7 @@ admin
7270
// [START sign_in_with_email_link]
7371
// Admin SDK API to generate the sign in with email link.
7472
const usremail = '[email protected]';
75-
admin
76-
.auth()
73+
getAuth()
7774
.generateSignInWithEmailLink(usremail, actionCodeSettings)
7875
.then((link) => {
7976
// Construct sign-in with email link template, embed the link and

auth/get_service_account_tokens.js

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -15,10 +15,10 @@
1515
*/
1616
'use strict';
1717
// [START get_service_account_tokens]
18-
const admin = require('firebase-admin');
18+
import { cert } from 'firebase-admin/app';
1919

2020
const serviceAccount = require('./path/to/serviceAccountKey.json');
21-
const credential = admin.credential.cert(serviceAccount);
21+
const credential = cert(serviceAccount);
2222

2323
credential.getAccessToken().then((accessTokenInfo) => {
2424
const accessToken = accessTokenInfo.access_token;

auth/import_users.js

Lines changed: 10 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
'use strict';
2-
const admin = require('firebase-admin');
3-
admin.initializeApp();
2+
import { initializeApp } from 'firebase-admin/app';
3+
import { getAuth } from 'firebase-admin/auth';
4+
initializeApp();
45

56
//[START build_user_list]
67
// Up to 1000 users can be imported at once.
@@ -22,8 +23,7 @@ const userImportRecords = [
2223
//[END build_user_list]
2324

2425
// [START import_users]
25-
admin
26-
.auth()
26+
getAuth()
2727
.importUsers(userImportRecords, {
2828
hash: {
2929
algorithm: 'HMAC_SHA256',
@@ -49,8 +49,7 @@ admin
4949
// [END import_users]
5050

5151
// [START import_with_hmac]
52-
admin
53-
.auth()
52+
getAuth()
5453
.importUsers(
5554
[
5655
{
@@ -81,8 +80,7 @@ admin
8180
// [END import_with_hmac]
8281

8382
// [START import_with_pbkdf]
84-
admin
85-
.auth()
83+
getAuth()
8684
.importUsers(
8785
[
8886
{
@@ -112,8 +110,7 @@ admin
112110
// [END import_with_pbkdf]
113111

114112
// [START import_with_standard_scrypt]
115-
admin
116-
.auth()
113+
getAuth()
117114
.importUsers(
118115
[
119116
{
@@ -146,8 +143,7 @@ admin
146143
// [END import_with_standard_scrypt]
147144

148145
// [START import_with_bcrypt]
149-
admin
150-
.auth()
146+
getAuth()
151147
.importUsers(
152148
[
153149
{
@@ -174,8 +170,7 @@ admin
174170
// [END import_with_bcrypt]
175171

176172
// [START import_with_scrypt]
177-
admin
178-
.auth()
173+
getAuth()
179174
.importUsers(
180175
[
181176
{
@@ -210,8 +205,7 @@ admin
210205
// [END import_with_scrypt]
211206

212207
// [START import_without_password]
213-
admin
214-
.auth()
208+
getAuth()
215209
.importUsers([
216210
{
217211
uid: 'some-uid',

auth/manage_cookies.js

Lines changed: 11 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,8 @@
11
'use strict';
2-
const admin = require('firebase-admin');
3-
admin.initializeApp();
2+
import { initializeApp } from 'firebase-admin/app';
3+
import { getAuth } from 'firebase-admin/auth';
4+
initializeApp();
5+
46
const express = require('express');
57
const app = express();
68

@@ -20,8 +22,7 @@ app.post('/sessionLogin', (req, res) => {
2022
// The session cookie will have the same claims as the ID token.
2123
// To only allow session cookie setting on recent sign-in, auth_time in ID token
2224
// can be checked to ensure user was recently signed in before creating a session cookie.
23-
admin
24-
.auth()
25+
getAuth()
2526
.createSessionCookie(idToken, { expiresIn })
2627
.then(
2728
(sessionCookie) => {
@@ -43,14 +44,13 @@ app.post('/verifyToken', (req, res) => {
4344
// Set session expiration to 5 days.
4445
const expiresIn = 60 * 60 * 24 * 5 * 1000;
4546
// [START check_auth_time]
46-
admin
47-
.auth()
47+
getAuth()
4848
.verifyIdToken(idToken)
4949
.then((decodedIdToken) => {
5050
// Only process if the user just signed in in the last 5 minutes.
5151
if (new Date().getTime() / 1000 - decodedIdToken.auth_time < 5 * 60) {
5252
// Create session cookie and set it.
53-
return admin.auth().createSessionCookie(idToken, { expiresIn });
53+
return getAuth().createSessionCookie(idToken, { expiresIn });
5454
}
5555
// A user that was not recently signed in is trying to set a session cookie.
5656
// To guard against ID token theft, require re-authentication.
@@ -65,8 +65,7 @@ app.post('/profile', (req, res) => {
6565
const sessionCookie = req.cookies.session || '';
6666
// Verify the session cookie. In this case an additional check is added to detect
6767
// if the user's Firebase session was revoked, user deleted/disabled, etc.
68-
admin
69-
.auth()
68+
getAuth()
7069
.verifySessionCookie(sessionCookie, true /** checkRevoked */)
7170
.then((decodedClaims) => {
7271
serveContentForUser('/profile', req, res, decodedClaims);
@@ -81,8 +80,7 @@ app.post('/profile', (req, res) => {
8180
app.post('/verifySessionCookie', (req, res) => {
8281
const sessionCookie = req.cookies.session || '';
8382
// [START session_verify_with_permission_check]
84-
admin
85-
.auth()
83+
getAuth()
8684
.verifySessionCookie(sessionCookie, true)
8785
.then((decodedClaims) => {
8886
// Check custom claims to confirm user is an admin.
@@ -109,11 +107,10 @@ app.post('/sessionLogout', (req, res) => {
109107
app.post('/sessionLogout', (req, res) => {
110108
const sessionCookie = req.cookies.session || '';
111109
res.clearCookie('session');
112-
admin
113-
.auth()
110+
getAuth()
114111
.verifySessionCookie(sessionCookie)
115112
.then((decodedClaims) => {
116-
return admin.auth().revokeRefreshTokens(decodedClaims.sub);
113+
return getAuth().revokeRefreshTokens(decodedClaims.sub);
117114
})
118115
.then(() => {
119116
res.redirect('/login');

auth/manage_sessions.js

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,8 @@
11
'use strict';
2-
const admin = require('firebase-admin');
3-
admin.initializeApp();
2+
import { initializeApp } from 'firebase-admin/app';
3+
import { getAuth } from 'firebase-admin/auth';
4+
import { getDatabase } from 'firebase-admin/database';
5+
initializeApp();
46

57
const uid = 'some_uid_1234';
68
const idToken = 'some_id_token';
@@ -9,11 +11,10 @@ const utcRevocationTimeSecs = 60 * 60;
911
// [START revoke_tokens]
1012
// Revoke all refresh tokens for a specified user for whatever reason.
1113
// Retrieve the timestamp of the revocation, in seconds since the epoch.
12-
admin
13-
.auth()
14+
getAuth()
1415
.revokeRefreshTokens(uid)
1516
.then(() => {
16-
return admin.auth().getUser(uid);
17+
return getAuth().getUser(uid);
1718
})
1819
.then((userRecord) => {
1920
return new Date(userRecord.tokensValidAfterTime).getTime() / 1000;
@@ -24,7 +25,7 @@ admin
2425
// [END revoke_tokens]
2526

2627
// [START save_revocation_in_db]
27-
const metadataRef = admin.database().ref('metadata/' + uid);
28+
const metadataRef = getDatabase().ref('metadata/' + uid);
2829
metadataRef.set({ revokeTime: utcRevocationTimeSecs }).then(() => {
2930
console.log('Database updated successfully.');
3031
});
@@ -34,8 +35,7 @@ metadataRef.set({ revokeTime: utcRevocationTimeSecs }).then(() => {
3435
// Verify the ID token while checking if the token is revoked by passing
3536
// checkRevoked true.
3637
let checkRevoked = true;
37-
admin
38-
.auth()
38+
getAuth()
3939
.verifyIdToken(idToken, checkRevoked)
4040
.then((payload) => {
4141
// Token is valid.

0 commit comments

Comments
 (0)