How to use the auth function from firebase-admin

Find comprehensive JavaScript firebase-admin.auth code examples handpicked from public code repositorys.

firebase-admin.auth is a module in the Firebase Admin SDK for Node.js that provides a programmatic interface for managing users in Firebase projects.

70
71
72
73
74
75
76
77
78
79
batch.update(admin.firestore().doc('PERRINNMessages/'+messageId),{chatImageUrlMedium:chatImageData.imageUrlMedium||messageData.chatImageUrlMedium||null},{create:true})

//user data
let emails=messageData.emails||userPreviousMessageData.emails||{}
if(emails.auth==undefined){
  const userRecord=await admin.auth().getUser(user)
  if(userRecord)emails.auth=userRecord.toJSON().email
}
if(emails.auth&&userPreviousMessageData.emails&&(emails.auth!=userPreviousMessageData.emails.auth))await admin.auth().updateUser(user,{email:emails.auth})
messageData.createdTimestamp=messageData.createdTimestamp||userPreviousMessageData.createdTimestamp||now
fork icon1
star icon0
watch icon2

+ 19 other calls in file

52
53
54
55
56
57
58
59
60
61
62
    console.log("Successfully updated user", userRecord.toJSON());
    userRecord['uid'] = userId;
    if (email) {
      userRecord['email'] = email;
    }
    return admin.auth().createUser(userRecord);
  });
}


/**
fork icon0
star icon0
watch icon1

+ 41 other calls in file

How does firebase-admin.auth work?

firebase-admin.auth is a module provided by the Firebase Admin SDK that allows developers to manage users and authentication for their Firebase project on the server-side using Node.js. It provides a set of APIs to perform tasks such as creating and updating user accounts, managing user sessions, verifying user identities, and more. This module also supports various authentication providers such as email/password, Google, Facebook, and many more. Developers can use this module to authenticate users on the server-side and manage their user accounts and profiles programmatically.

80
81
82
83
84
85
86
87
88
.then(
    (sessionCookie) => {
        res.cookie("token", sessionCookie, { maxAge: expiresIn, httpOnly: true }, { sameSite: 'none', secure: true });
        console.log('session cookie created successfully', sessionCookie);
        req.session.token = sessionCookie;
        admin.auth().verifySessionCookie(sessionCookie, true).then((decodedClaims) => {
            console.log('session cookie verified successfully');
            console.log(decodedClaims);

fork icon0
star icon0
watch icon1

+ 9 other calls in file

48
49
50
51
52
53
54
55
56
57
if (!token) {
    res.status(401);
    return next('Unauthorized');
}
try {
    const appCheckClaims = await admin.auth().verifyIdToken(token);
    return next("");
} catch (err) {
    console.log(err)
    res.status(401);
fork icon0
star icon0
watch icon1

+ 4 other calls in file

Ai Example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
const admin = require("firebase-admin");

// Initialize Firebase Admin SDK
admin.initializeApp();

// Create a new user with email and password
admin
  .auth()
  .createUser({
    email: "user@example.com",
    password: "secretPassword123",
  })
  .then((userRecord) => {
    console.log("Successfully created new user:", userRecord.uid);
  })
  .catch((error) => {
    console.error("Error creating new user:", error);
  });

This code initializes the Firebase Admin SDK, creates a new user with the email user@example.com and password secretPassword123, and logs the user's UID to the console if the creation is successful.

4
5
6
7
8
9
10
11
12
13
14
15
  credential: admin.credential.cert(serviceAccount),
  databaseURL: "https://first-app-d7cf5-default-rtdb.firebaseio.com"
});


async function getUid(){
  const getUser=await admin.auth().listUsers()
  return getUser
}


var db=admin.database()
fork icon0
star icon0
watch icon1

+ 4 other calls in file

11
12
13
14
15
16
17
18
19
20
21


exports.addUsers = functions.https.onCall(async (data, context) => {
  // Grab the text parameter.
  const users = data;
  // Returns the text received
  admin.auth()
      .importUsers(users, {
        hash: {
          algorithm: "PBKDF2_SHA256",
          rounds: 100000,
fork icon0
star icon0
watch icon1

+ 9 other calls in file

40
41
42
43
44
45
46
  Users,
  CurrentTime,
  FutureTime,
  admin,
  bucket,
  auth: admin.auth(app)
};
fork icon0
star icon0
watch icon1

+ 9 other calls in file

37
38
39
40
41
42
43
44
45
46
const createHatim = (req, res) => __awaiter(void 0, void 0, void 0, function* () {
    hatim.createHatim();
});
const retrieveHatim = (req, res) => __awaiter(void 0, void 0, void 0, function* () {
    const token = req.headers['authorization'].split(' ')[1];
    yield admin.auth().verifyIdToken(token).then((response) => __awaiter(void 0, void 0, void 0, function* () {
        // Get a reference to the desired node in the database
        const nodeRef = admin.database().ref('Hatim');
        // Read the data at the node once
        nodeRef.once('value', (snapshot) => {
fork icon0
star icon0
watch icon1

+ 9 other calls in file

465
466
467
468
469
470
471
472
473
474
475
exports.getVideos = getData(videoModel);


// create user
exports.createNewUser = catchAsync(async (req, res, next) => {
  const { email, password, name } = req.body;
  const user = await firebase.auth().createUser({
    email: email,
    password,
    displayName: name,
  });
fork icon0
star icon0
watch icon1

+ 2 other calls in file

94
95
96
97
98
99
100
101
102
103
104


//find firebase user uid from displayname
async function findUser(displayName){
  try {
    let uid = '';
    await admin.auth()
      .listUsers(1000)
      .then((listUsersResult) => {
        listUsersResult.users.forEach((userRecord) => {
          if (userRecord.displayName === displayName){
fork icon0
star icon0
watch icon1

+ 12 other calls in file

9
10
11
12
13
14
15
16
17
18
19
const admin = require("firebase-admin");
admin.initializeApp();


exports.addAdminRole = functions.https.onCall(async (data, context) => {
  // get user by email and add custom claim (admin)
  return admin.auth().getUserByEmail(data.email)
      .then((user) => {
        return admin.auth().setCustomUserClaims(user.uid, {admin: true});
      }).then(() => {
        return {message: `Success! ${data.email} has been made an admin!`};
fork icon0
star icon0
watch icon0

+ 3 other calls in file

27
28
29
30
31
32
33
34
35
36
37


async function verifyToken(req, res, next) {
  if (req.headers?.authorization?.startsWith('Bearer ')) {
    const totken = req.headers.authorization.split(' ')[1];
    try {
      const decodedUser = await admin.auth().verifyIdToken(token);
      req.decodedEmail = decodedEmail;
    } catch {}
  }
  next();
fork icon0
star icon0
watch icon0

15
16
17
18
19
20
21
22
23
24

return admin
  .auth()
  .getUserByEmail(data.email)
  .then((user) => {
    return admin.auth().setCustomUserClaims(user.uid, {
      teacher: true,
    });
  })
  .then(() => {
fork icon0
star icon0
watch icon0

+ 2 other calls in file