Skip to content

Commit c31978a

Browse files
committed
auth
1 parent 231c442 commit c31978a

File tree

3 files changed

+530
-4
lines changed

3 files changed

+530
-4
lines changed

auth/custom_claims.js

Lines changed: 75 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,6 @@
11
'use strict';
2+
const express = require('express');
3+
24
const admin = require('firebase-admin');
35
admin.initializeApp();
46

@@ -77,3 +79,76 @@ admin
7779
console.log(error);
7880
});
7981
// [END set_custom_user_claims_incremental]
82+
83+
function customClaimsCloudFunction() {
84+
// [START auth_custom_claims_cloud_function]
85+
const functions = require('firebase-functions');
86+
87+
const admin = require('firebase-admin');
88+
admin.initializeApp();
89+
90+
// On sign up.
91+
exports.processSignUp = functions.auth.user().onCreate(async (user) => {
92+
// Check if user meets role criteria.
93+
if (
94+
user.email &&
95+
user.email.endsWith('@admin.example.com') &&
96+
user.emailVerified
97+
) {
98+
const customClaims = {
99+
admin: true,
100+
accessLevel: 9
101+
};
102+
103+
try {
104+
// Set custom user claims on this newly created user.
105+
await admin.auth().setCustomUserClaims(user.uid, customClaims);
106+
107+
// Update real-time database to notify client to force refresh.
108+
const metadataRef = admin.database().ref("metadata/" + user.uid);
109+
110+
// Set the refresh time to the current UTC timestamp.
111+
// This will be captured on the client to force a token refresh.
112+
await metadataRef.set({refreshTime: new Date().getTime()});
113+
} catch (error) {
114+
console.log(error);
115+
}
116+
}
117+
});
118+
// [END auth_custom_claims_cloud_function]
119+
}
120+
121+
function customClaimsServer() {
122+
const app = express();
123+
124+
// [START auth_custom_claims_server]
125+
app.post('/setCustomClaims', async (req, res) => {
126+
// Get the ID token passed.
127+
const idToken = req.body.idToken;
128+
129+
// Verify the ID token and decode its payload.
130+
const claims = await admin.auth().verifyIdToken(idToken);
131+
132+
// Verify user is eligible for additional privileges.
133+
if (
134+
typeof claims.email !== 'undefined' &&
135+
typeof claims.email_verified !== 'undefined' &&
136+
claims.email_verified &&
137+
claims.email.endsWith('@admin.example.com')
138+
) {
139+
// Add custom claims for additional privileges.
140+
await admin.auth().setCustomUserClaims(claims.sub, {
141+
admin: true
142+
});
143+
144+
// Tell client to refresh token on user.
145+
res.end(JSON.stringify({
146+
status: 'success'
147+
}));
148+
} else {
149+
// Return nothing.
150+
res.end(JSON.stringify({ status: 'ineligible' }));
151+
}
152+
});
153+
// [END auth_custom_claims_server]
154+
}

0 commit comments

Comments
 (0)