The following is a simple test to get the OIDC token using gapi client
// example.spec.ts
test("get oidc token", async ({ page }) => {
gapi.load("client", () => {
gapi.client
.init({
apiKey: "*****",
clientId:
"********",
discoveryDocs: [
"https://iamcredentials.googleapis.com/$discovery/rest?version=v1",
],
})
.catch((err) => {
console.error(err);
})
.then(() => {
return gapi.client.request({
path: "https://iamcredentials.googleapis.com/v1/...:generateIdToken",
...
});
})
.catch((err) => {
console.error(err);
})
.then((token) => console.log(`OIDC token ${token}`));
});
});
It won't work as it raises a ReferenceError: gapi is not defined even though the #types/gapi are installed.
I've already tried to add "gapi"/"#types/gapi" in types inside the tsconfig.json file or import 'gapi' without any success.
Now I'm wondering if it is possible to use the gapi client from Playwright or not.
Related
I've been following this tutorial with this library, but the code snippets provided are producing errors. I have registered the app with Azure and followed the instructions, but when I run the code, it says SyntaxError: await is only valid in async functions and the top level bodies of modules at /script.js:74:20
Here's a relevant snippet of code, but if you have Replit, I would really appreciate it if you could collaborate with me on my Repl instead.
Replit link: https://replit.com/join/rgqcqfcohh-5pengoo
Code:
const msal = require('#azure/msal-node');
// Create msal application object
const cca = new msal.ConfidentialClientApplication(config);
const REDIRECT_URI = "http://localhost:3000/redirect";
const config = {
auth: {
clientId: "ebcb2e8c-4675-411f-a76e-25aafe0c026d",
authority: "https://login.microsoftonline.com/98ca2106-858a-413a-b7d5-31301dcf9869/",
// I wasn't sure if this meant the key value or the secret ID
clientSecret: "ee10b5ce-f9c4-460a-a402-064030841f86"
},
system: {
loggerOptions: {
loggerCallback(loglevel, message, containsPii) {
console.log(message);
},
piiLoggingEnabled: false,
logLevel: msal.LogLevel.Verbose,
}
}
};
// 1st leg of auth code flow: acquire a code
app.get('/', (req, res) => {
const authCodeUrlParameters = {
scopes: ["user.read"],
redirectUri: REDIRECT_URI,
};
// get url to sign user in and consent to scopes needed for application
pca.getAuthCodeUrl(authCodeUrlParameters).then((response) => {
res.redirect(response);
}).catch((error) => console.log(JSON.stringify(error)));
});
// 2nd leg of auth code flow: exchange code for token
app.get('/redirect', (req, res) => {
const tokenRequest = {
code: req.query.code,
scopes: ["user.read"],
redirectUri: REDIRECT_URI,
};
pca.acquireTokenByCode(tokenRequest).then((response) => {
console.log("\nResponse: \n:", response);
res.sendStatus(200);
}).catch((error) => {
console.log(error);
res.status(500).send(error);
});
});
try {
let userDetails = await client.api("/me").get();
console.log(userDetails);
} catch (error) {
throw error;
}
MohammedMehtabSiddiqueMINDTREELIMI-9821 on the Microsoft Docs informed me that...
"You can use "await" only inside a function which is "async".
Here you can try remove 'await' from the code and try to run it"
and it worked!
I'm very new to testing and I can't figure out how to test this scenario. I use supertest and Jest for testing. In my Express app I use jwt authentication. I store a jwt token that identifies a user in a http only cookie, and it's been created when a user creates and account or logs in.
Now, I have a route that is responsible for a password change requested by a user:
router.post('/reset-password', async function (req, res, next) {
try {
//relevant to the question part here
//
const { userToken } = req.cookies
if (!userToken) {
res.status(401).json({ error: 'unauthorized' })
return
}
const { email } = jwt.verify(userToken, process.env.JWT_SECRET)
/////////////////////
} catch (err) {
res.status(401).json({ error: 'unable to verify' })
}
})
As I understand, in order to test this function, I need to set a cookie in beforeAll. I tried doing so by registering a user that normaly sets required token. Here is my test code:
const request = require('supertest')
const app = require('../app')
const MongoClient = require('mongodb').MongoClient
const client = new MongoClient(`mongodb://localhost:27017/img-test`, {
useNewUrlParser: true,
useUnifiedTopology: true,
})
beforeAll(async () => {
await client.connect()
app.locals.db = client.db('img-test')
await request(app).post('/register').send({
username: 'Bob',
email: 'bob#email.com',
password: 'Hardpass0!',
checkboxTerms: 'on',
'g-recaptcha-response': 'asdasd',
})
})
describe('Password reset', () => {
test('Should reset password', async () => {
await request(app)
.post('/api/account/reset-password')
.send({
passwordCurrent: 'Hardpass0!',
passwordNew: 'Hardpass1!',
})
.expect(200)
})
})
afterAll(async () => {
let db = app.locals.db
await db.dropDatabase()
client.close()
})
And of course, it fails. userToken is going to be undefined because as I understand supertest is not setting an http only cookie when a user is registered, and there is no token on req.cookies? How do I test this scenario? What am I doing wrong? Thanks for help.
I am trying to follow a video on youtube called "Full Stack React & Firebase Tutorial - Build a social media app" and I am having trouble with the code for adding new users to firebase..
My code looks like this:
const functions = require('firebase-functions');
const admin = require('firebase-admin');
const app = require('express')();
admin.initializeApp();
const firebaseConfig = {
apiKey: "apiKey",
authDomain: "socialtutorial.firebaseapp.com",
databaseURL: "https://socialtutorial.firebaseio.com",
projectId: "socialtutorial",
storageBucket: "socialtutorial.appspot.com",
messagingSenderId: "SenderID",
appId: "1:848457683801:web:a276f7436db03ac500b248"
}
const firebase = require('firebase');
firebase.initializeApp(firebaseConfig);
app.get('/challenges', (req, res) => {
admin
.firestore()
.collection('challenges')
.orderBy('challengeCreated', 'desc')
.get()
.then(data => {
let challenges = [];
data.forEach(doc => {
challenges.push({
challengeId: doc.id,
challengeName: doc.data().challengeName,
challengeDescription: doc.data().challengeDescription,
challengeCreated: doc.data().challengeCreated
});
});
return res.json(challenges);
})
.catch (err => console.error(err));
})
app.post('/challenge', (req, res) => {
const newChallenge = {
challengeName: req.body.challengeName,
challengeDescription: req.body.challengeDescription,
challengeCreated: new Date().toISOString()
};
admin.firestore()
.collection('challenges')
.add(newChallenge)
.then(doc => {
res.json({message: `document ${doc.id} created successfully`});
})
.catch(err => {
res.status(500).json({error: 'something went wrong'});
console.error(err);
})
})
//Sign Up Route
app.post('/signup', (req, res) => {
const newUser = {
email: req.body.email,
password: req.body.password,
confirmPassword: req.body.confirmPassword,
userName: req.body.userName
}
//TODO Validate
firebase
.auth()
.createUserWithEmailAndPassword(newUser.email, newUser.password)
.then(data => {
return res.status(201).json({message: `user ${data.user.uid} signed up successfully`});
})
.catch(err) => {
console.error(err);
return res.status(500).json({error: err.code})
}
})
exports.api = functions.region('europe-west1').https.onRequest(app);
Now, when I try "firebase deploy" or "serve" I get an unexpected token error. The error is the "." after firebase... I must have missed something in the code above, but I can't see it for the life of me. I know this is a stupid mistake and I should be able to fix it on my own, but I literally can't see, where the error comes from...
Any help from you guys? Thanks a lot in advance!
I'm not sure if maybe you copied pasted to the question incorrectly from your editor but the only thing I see is the last catch of your code. It seems you never pass a callback to it.
you defined it as follows
.catch(err) => {
but it should be
.catch(err => {
My code: Inside of an index.js file. Set up using firebase init command, functions selected. I'm able to deploy without error if I comment out the code:
const firebase = require("firebase");
firebase.initializeApp(config);
It throws the error if I leave this in. I've tried running npm install and npm rebuild in both the functions folder and the parent folder.
const functions = require("firebase-functions");
const admin = require("firebase-admin");
const app = require("express")();
admin.initializeApp();
const config = {
apiKey: "apiKey",
authDomain: "socialapp.firebaseapp.com",
databaseURL: "https://socialapp.firebaseio.com"
storageBucket: "socialapp.appspot.com"
};
const firebase = require("firebase");
firebase.initializeApp(config);
app.get("/screams", (req, res) => {
admin
.firestore()
.collection("screams")
.orderBy("createdAt", "descending")
.get()
.then(data => {
let screams = [];
data.forEach(doc => {
screams.push({
screamId: doc.id,
body: doc.data().body,
userHandle: doc.data().userHandle,
createdAt: doc.data().createdAt
});
});
return res.json(screams);
})
.catch(err => console.log(err));
});
app.post("/scream", (req, res) => {
const newScream = {
body: req.body.body,
userHandle: req.body.userHandle,
createdAt: new Date().toISOString()
};
admin
.firestore()
.collection("screams")
.add(newScream)
.then(doc => {
res.json({ message: `document ${doc.id} created successfully` });
})
.catch(err => {
res.status(500).json({ error: "Something went wrong." });
console.error(err);
});
});
//Signup Route
app.post("/signup", (req, res) => {
const newUser = {
email: req.body.email,
password: req.body.password,
confirmPassword: req.body.confirmPassword,
handle: req.body.handle
};
//Todo validate data
firebase
.auth()
.createUserWithEmailAndPassword(newUser.email, newUser.password)
.then(data => {
return res
.status(201)
.json({ message: `user ${data.user.uid} signed up successfully` });
})
.catch(err => {
console.err(error);
return res.status(500).json({ error: err.code });
});
});
exports.api = functions.https.onRequest(app);
Error from console:
i deploying functions
i functions: ensuring necessary APIs are enabled...
+ functions: all necessary APIs are enabled
i functions: preparing functions directory for uploading...
Error: Error parsing triggers: The gRPC binary module was not installed. This may be fixed by running "npm rebuild"
Original error: Cannot find module 'C:\Users\alex_\Desktop\socialapp-functions\functions\node_modules\grpc\src\node\extension_binary\node-v79-win32-x64-unknown\grpc_node.node'
Require stack:
- C:\Users\alex_\Desktop\socialapp-functions\functions\node_modules\grpc\src\grpc_extension.js
- C:\Users\alex_\Desktop\socialapp-functions\functions\node_modules\grpc\src\client_interceptors.js
- C:\Users\alex_\Desktop\socialapp-functions\functions\node_modules\grpc\src\client.js
- C:\Users\alex_\Desktop\socialapp-functions\functions\node_modules\grpc\index.js
- C:\Users\alex_\Desktop\socialapp-functions\functions\node_modules\#firebase\firestore\dist\index.node.cjs.js
- C:\Users\alex_\Desktop\socialapp-functions\functions\node_modules\firebase\dist\index.node.cjs.js
- C:\Users\alex_\Desktop\socialapp-functions\functions\index.js
- C:\Users\alex_\AppData\Roaming\npm\node_modules\firebase-tools\lib\triggerParser.js
Try running "npm install" in your functions directory before deploying.
Having trouble? Try firebase [command] --help
You don't need the "firebase" module here (it's mostly meant for web application, note nodejs apps). You can use the Admin SDK instead to create a user account as described in the documentation.
So I follow this firebase tutorial and seemingly to I do everything according to the documentation but I still get errors. Youtube FCM Tutorial
var config = {
apiKey: "AIzaSyAyWVXB9KFLm2ymoBoiY-TothNYgo3IrtA",
authDomain: "fir-end-cff84.firebaseapp.com",
databaseURL: "https://fir-end-cff84.firebaseio.com",
projectId: "fir-end-cff84",
storageBucket: "fir-end-cff84.appspot.com",
messagingSenderId: "297653223714"
};
firebase.initializeApp(config);
if ('serviceWorker' in navigator) {
navigator.serviceWorker.register('./firebase-messaging-sw.js').then(function (registration) {
// Registration was successful
console.log('ServiceWorker registration successful with scope: ', registration.scope);
}).catch(function (err) {
// registration failed :(
console.log('ServiceWorker registration failed: ', err);
});
}
const messaging = firebase.messaging();
messaging.requestPermission()
.then(function () {
console.log('Have Permit');
return messaging.getToken();
})
.then(function (token) {
console.log(token);
})
.catch(function (err) {
console.log(err);
})
These are the logs:
And this is the project overview:
Im using the latest version of webstorm on ubuntu 16.04
Edit: I even used this repo but still have the same issue
https://github.com/firebase/quickstart-js/tree/master/messaging
Apperently to get the fcm token your localhost needs to have application server capabilities, some webstorm's localhost wont do!