Verify Firebase Token on Apollo Node.js backend?
After user signs in on my Android App with Firebase I want to send the Firebase Token as a String param via GraphQL Mutation. Then receive it on my Express.js API inside the GraphQL mutation resolver and verify the token with the Firebase Admin SDK.
I have no idea if this is the correct way, all I want is to get the UID from the Token and check with Prisma if the UID is already existing on my MySQL User Table, if not then create a new user.
This should be done whenever the user inside the app uploads a new file, likes a post, comments etc.
I have absolutely no Idea if this is the way to do it.
Here is my Firebase Object (firebaseApp.js):
const admin = require('firebase-admin')
const serviceAccount = require("./.firebase/service-account.json");
const firebaseApp =
global.firebaseApp ??
admin.initializeApp({
credential: admin.credential.cert(serviceAccount),
})
// store on global object so we can reuse it if we attempt
// to initialize the app again
global.firebaseApp = firebaseApp
Here is my Mutation Resolver:
const db = require('../firebaseApp')
module.exports = {
Mutation: {
authenticateUser: async (parent, { token }) => {
db.auth().verifyIdToken(token)
.then((decodedToken) => {
const uid = decodedToken.uid;
return {
message: "User is authenticated: " + uid
}
})
.catch((error) => {
return {
message: "User is not authenticated: "
}
});
}
}
}
Here is the output when I try to send a token with the mutation:
db.auth is not a function
I have the strong feeling that I have a big misconception in my head and that this is aboslutely not the way to do it, I literally cannot find anything on the internet which explains this using my tech stack (Apollo GraphQL, Node.js, Prisma) Would appreciate some help
do you know?
how many words do you know
See also questions close to this topic
-
Updating a Single Column In Room Database
That's the function I'm using for updat
private fun updateSettingsDatabase(settingsDao: SettingsDao) { lifecycleScope.launch { settingsDao.update(SettingsEntity( 1, nightMode=nightModeResult, )) } } @Query("SELECT * FROM `settings-table`") fun fetchCurrentSettings(): Flow<List<SettingsEntity>>
I specified
nightMode=
because I thought that this way I'm only updating this colummn, but it turns out that it resets every column, how do I update a single column, while keeping the values the rest of the columns? -
Using EdittextPreference for Goto search
sorry for my poor English. I want to use EditTextPreference in my bottom nav like the pic below, ![screenshot][1]
I have recycleview xml in my project with in many sub cardview layouts(which is scrollable) and I want to create item in the bottom nav which is called "Goto". When the "Goto" item is clicked i want it to pop-up like the screenshot. And when user enters a number(according to the cardviews i.e if the number of cardview is 40 user must enter 1-40) I want to search the cardview by its ID. Thank you and I hope u got it, If u have any questions let me know [1]: https://i.stack.imgur.com/grK8P.jpg
My xml format look like this. As you see in the blow since the cardviews are huge in number it is not cool to scroll all the way down that is why i need Goto item in the bottom nav to search it by its ID when the user click number in the EditTextPreference as u see in the screenshot. i.e The screenshot is not from my app
<LinearLayout> <LinearLayout> <androidx.cardview.widget.CardView> <RealtiveLayout> <Textview/> <RealtiveLayout> </androidx.cardview.widget.CardView> </LinearLayout> <LinearLayout> <androidx.cardview.widget.CardView> <RealtiveLayout> <Textview/> <RealtiveLayout> </androidx.cardview.widget.CardView> </LinearLayout> <LinearLayout> <androidx.cardview.widget.CardView> <RealtiveLayout> <Textview/> <RealtiveLayout> </androidx.cardview.widget.CardView> </LinearLayout> <LinearLayout> <androidx.cardview.widget.CardView> <RealtiveLayout> <Textview/> <RealtiveLayout> </androidx.cardview.widget.CardView> </LinearLayout> .. .. .. .. many more..
-
IOS Launcher in android studio
I'm trying to change the whole Android OS installed app icons into IOS icons, please help me with the proper code or library for android kotlin
-
Error message : MongoServerError: bad auth :Authentication failed
What is the reason behind this error? this code I am using to connect to DB.
const uri =`mongodb+srv://${process.env.DB_USER}:${process.env.DB_PASSWORD}@cluster0.xft2s.mongodb.net/myFirstDatabase?retryWrites=true&w=majority`;
-
In Mongo, If a document I'm saving "Prateek" then I don't want on the next create operation even the "prateek" or "praTEEK", etc is saved
//** If I'm adding a new document with the name: "India", then I don't want that the DB allow another name with the name: "INDIA", "india", "indIA", etc. I'm new and learning, help would be great!!**
// Controller
var Dinosaur = require('../models/dinosaurs'); //addDino module.exports.addDino = (req, res) => { var name = req.body.name; var type = req.body.type; var height = req.body.height; var weight = req.body.weight; var Period = req.body.Period; req.checkBody('name', 'Name is required').notEmpty(); var errors = req.validationErrors(); if (errors) return res.status(400).send({ message: 'Name is Required' }); else { let newDino = { name: name, type: type, height: height, weight: weight, Period: Period } Dinosaur.addDino(newDino, (err, result) => { if (err) { if (err.name) return res.status(409).send({ message: name + ' Already Exist' }); else if (err.url) return res.json({ status: false, error: { url: "Url already exist" }, message: err.url }); else return res.json(err, "Server Error"); } else { return res.status(200).send({ message: "Done" }); } }); } }
// Model
var mongoose = require('mongoose'); //dinosaur schema var DinosaurSchema = mongoose.Schema({ name: { type: String, unique: true }, type: { type: String }, height: { type: Number }, weight: { type: Number }, Period: { type: String } }); var Dinosaur = mongoose.model('dinosaur', DinosaurSchema); //add module.exports.addDino = (query, callback) => { Dinosaur.create(query, callback); }
// GetAll, Already Created a new document with the name "Brachiosaurus"
// > Create, a new create with the first letter lower case "brachiosaurus", Don't want it to be pushed.
- i am trying to run the node of ganache but getting this error
-
How can I fixed my problem"FirebaseError: Firebase: Error (auth/invalid-api-key)."
My environment variable is ok. No comas and name mistakes but they given me error like "FirebaseError: Firebase: Error (auth/invalid-api-key)". How can I fixed it. Please Help me...
This my .env file
REACT_APP_apiKey=AIzaSyBWobnhbdeMdNpXXXXXXXXXXXXXXXXXXXX REACT_APP_authDomain=XXXXX.firebaseapp.com REACT_APP_projectId=XXXX REACT_APP_storageBucket=XXXXX.appspot.com REACT_APP_messagingSenderId=4997390XXXXX REACT_APP_appId=1:4997390XXXXX:web:cc7bc80aa1bdb78fXXXXXX REACT_APP_measurementId=G-M1XDXXXXXX
This my firebase config file
const firebaseConfig = { apiKey: process.env.REACT_APP_apiKey, authDomain: process.env.REACT_APP_authDomain, projectId: process.env.REACT_APP_projectId, storageBucket: process.env.REACT_APP_storageBucket, messagingSenderId: process.env.REACT_APP_messagingSenderId, appId: process.env.REACT_APP_appId, measurementId: process.env.REACT_APP_measurementId, }; when I debugging firebaseConfig object console.log(firebaseConfig.apiKey); ==========> undefined console.log(firebaseConfig.authDomain); ==========> undefined console.log(firebaseConfig.projectId); ==========> undefined console.log(firebaseConfig.storageBucket); ==========> undefined console.log(firebaseConfig.measurementId); ==========> undefined console.log(firebaseConfig.appId); ==========> undefined console.log(firebaseConfig.measurementId); ==========> undefined
client side given error this "FirebaseError: Firebase: Error (auth/invalid-api-key)"
-
How to Fix Firebase invalid API key
I'm using my API key stored in a .env.local file. And it setup correctly but not working
assert.ts:128 Uncaught FirebaseError: Firebase: Error (auth/invalid-api-key). at createErrorInternal (assert.ts:128:1) at _assert (assert.ts:153:1) at register.ts:67:1 at Component.instanceFactory (register.ts:90:1) at Provider.getOrInitializeService (provider.ts:318:1) at Provider.initialize (provider.ts:242:1) at initializeAuth (initialize.ts:66:1) at getAuth (index.ts:44:1) at Module../src/firebase.init.js (firebase.init.js:22:1) at Module.options.factory (react refresh:6:1)
I don't know why React is giving me an error. I intialized firebase in the following file
// Import the functions you need from the SDKs you need import { initializeApp } from "firebase/app"; import { getAuth } from "firebase/auth"; // TODO: Add SDKs for Firebase products that you want to use // https://firebase.google.com/docs/web/setup#available-libraries // Your web app's Firebase configuration // For Firebase JS SDK v7.20.0 and later, measurementId is optional const firebaseConfig = { apiKey: process.env.REACT_APP_apiKey, authDomain: process.env.REACT_APP_authDomain, projectId: process.env.REACT_APP_projectId, storageBucket: process.env.REACT_APP_storageBucket, messagingSenderId: process.env.REACT_APP_messagingSenderId, appId: process.env.REACT_APP_appId, measurementId:process.env.REACT_APP_measurementId }; // Initialize Firebase const app = initializeApp(firebaseConfig); const auth = getAuth(app); export default auth;
-
Knowing when the javascript SDK has made a definite decision as to whether the user is logged in or not upon initial load
I'm trying to accomplish something rather simple here but it's turning out to be a bit of a head-scratcher.
Obviously we have the handy onAuthStateChanged event which allows me to listen to changes to auth status. So it's easy to be informed when the user logs in or out.
The issue is that during the initial application load, there doesn't seem to be a reliable way to tell if the user is simply not logged at all or if the sign-in is being processed in the background.
For example, if the user has a stored session (logged in from last time), and returns, initially onAuthStateChanged will return null, and then afterward it's triggered again and returns the user.
If the user is not logged in, it will return null and then do nothing.
The problem is I can't really tell if the first null is telling me that the user is not logged in at all versus the user is not logged in yet because it's being processed in the background.
I would like a way where I could know for sure either way.
Thanks!
-
Firebase no method found signInWithEmailandPassword using Nodejs
I was trying to use firebase in node js project but i cant found the method
signInWithEmailandPassword
package.json
"dependencies": { "body-parser": "^1.20.0", "cookie-parser": "^1.4.6", "express": "^4.18.1", "express-handlebars": "^6.0.5", "firebase": "^9.7.0", "firebase-admin": "^10.2.0", "nodemon": "^2.0.16" }
app.js
const admin =require('firebase-admin') const serviceAccount = require('./serviceAccountKey.json') admin.initializeApp({ credential: admin.credential.cert(serviceAccount), databaseURL: "https://icredit-f0f7f.firebaseio.com" }); admin.auth().//No method found only generate link,resetPass,emailLink
-
Firebase Functions "subscribeToTopic" works only for the first time
For some reason, I can't subscribe users for more than one topic
Here is my code:
exports.subscribe = functions.https.onCall((request, response) => { console.log(request); admin .messaging() .subscribeToTopic(request.token, request.topic) .then((response) => { console.log("Successfully subscribed to topic:", response); }) .catch((error) => { console.log("Error subscribing to topic:", error); }); });
For the first time, everything works fine, but on the second time, I get some error in response:
errors: [ { index: 0, error: [FirebaseMessagingError] } ]
So here are two questions:
- How to get this error text?
- How to subscribe user for multiple topics?
-
Access Firebase access token through Firebase Admin PHP SDK
I have generated myself a service account with .json file for Firebase Admin PHP SDK authorization.
Aside from that, I would want to use the same service account for authenticating Clodfunctions API calls, without the need for authorizing another service account and getting token for it (that'll be used in API calls).
Is there a way to extract the access token from Factory object I initialized with my service account .json file?
More on Factory initialization is explained here. I went through source code but none of the methods exist that would give me this option. Some of them could potentially store this data, but they are all private; used only inside core classes used for communication with Firebase database.
-
Prisma: make boolean so only one can be true at the same time
Is it possible to make a boolean "unique" in Prisma? I want only one row to be 'true' at the same time. @Unique doesn't work because there can be multiple 'false'.
I know there are better options to keep track of whether someone is logged in, but according to the assignment I MUST do it this way....
Thanks in advance.
-
next auth coinbase provider using prisma adapter doesn't add Account error created_at in data.created_at for type AccountUncheckedCreateInput
Seems like one data object in AccountUncheckedCreateInput is missing: data.created_at
Invalid p.account.create() invocation in
16 }, 17 updateUser: ({ id, ...data }) => p.user.update({ where: { id }, data }), 18 deleteUser: (id) => p.user.delete({ where: { id } }), → 19 linkAccount: (data) => p.account.create({ data: { xxx } }) Unknown arg created_at in data.created_at for type AccountUncheckedCreateInput. Available args: type AccountUncheckedCreateInput { id?: String userId: String type: String provider: String providerAccountId: String refresh_token?: String | Null access_token?: String | Null expires_at?: Int | Null token_type?: String | Null scope?: String | Null id_token?: String | Null session_state?: String | Null }
-
How to configure NextJS Server API GraphQL Subscription
currently i'm learning how to develop an application using graphql. I'm facing the error of implementing the subscription inside my application
resolver.js
const pubsub = new PubSub() export const resolvers = { Mutation: { createCategory:async(parent,arg,{pubsub}) => { console.log(pubsub) const prisma = new PrismaClient(); const {name} = arg await prisma.category.create({ data:{ name:name, author:{ connect:{ id: "vjuwU0KvWhVDehB1gPgJ7TFRwcy1" } } } }); pubsub.publish('NEW_CATEGORY',{ newCategory:{ id:"1" } }) return true; } }, Subscription:{ category:{ subscribe: (_,__,)=>pubsub.asyncIterator(['NEW_CATEGORY']), } } };
api/graphql.js
const pubsub = new PubSub() const apolloServer = new ApolloServer({ typeDefs, resolvers,context:({req,res})=>({req,res,pubsub})}); const startServer = apolloServer.start(); export default cors(async function handler(req, res) { if (req.method === "OPTIONS") { res.end(); return false; } await startServer; await apolloServer.createHandler({ path: "/api/graphql", })(req, res); }); export const config = { api: { bodyParser: false, }, };
Error were occurred, i was unable to solve it due to this error message