Created
April 13, 2020 01:50
-
-
Save BadPirate/b8c25848ea3a7b44a534d3966e68a936 to your computer and use it in GitHub Desktop.
Custom Firebase Hasura Claims with Firestore
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const functions = require('firebase-functions') | |
const admin = require('firebase-admin') | |
const cors = require('cors')({ | |
origin: (origin, callback) => { | |
const allowed = ['http://localhost:3000', 'https://yourfinalwebsite.com'] | |
if (allowed.indexOf(origin) !== -1) { | |
return callback(null, true) | |
} | |
return callback(new Error(`CORS Policy denies ${origin}`), false) | |
}, | |
}) | |
const Firestore = require('@google-cloud/firestore') | |
admin.initializeApp(functions.config().firebase) | |
const firestore = new Firestore({ | |
projectId: 'your-firebase-project-id', | |
timestampsInSnapshots: true, | |
}) | |
const updateClaims = (uid) => firestore.collection('claims').doc(uid).get().then((doc) => { | |
if (!doc) { return {} } | |
const data = doc.data() | |
console.log(`${uid} has custom claims`, data) | |
return data | |
}) | |
.then((additionalClaims) => { | |
const defaultClaims = { | |
'x-hasura-default-role': 'user', | |
'x-hasura-allowed-roles': ['user'], | |
'x-hasura-user-id': uid, | |
} | |
const claims = { | |
'https://hasura.io/jwt/claims': { | |
...defaultClaims, | |
...additionalClaims, | |
}, | |
} | |
return admin.auth().setCustomUserClaims(uid, claims) | |
}) | |
exports.processSignUp = functions.auth.user().onCreate((user) => updateClaims(user.uid)) | |
exports.refreshToken = functions.https.onRequest((req, res) => { | |
console.log('TOKEN REFRESH', req.query.uid) | |
cors(req, res, () => { | |
updateClaims(req.query.uid).then(() => { | |
res.status(200).send('success') | |
}).catch((error) => { | |
console.error('REFRESH ERROR', error) | |
res.status(400).send(error) | |
}) | |
}) | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment