Before a user first signed in to the main page of my app, I've done updating user's displayName
and photoURL
by calling the following method below.
updateUserProfile(name: string, photoURL: string) {
let data = {
displayName: name,
photoURL: photoURL
};
this.afAuth.auth.currentUser.updateProfile(data)
.then(() => console.log('Updated user profile.'))
.catch((err) => console.log(err));
}
However, the problem is when a logged in user makes an HTTP request, the server throws an error.
Error: Cannot encode type ([object Undefined])
I'm pretty sure this is because name
and picture
are missing! How can I resolve this problem? Perhaps the token has a problem?
Note: If a user makes HTTP requests after attempting the second login, it works fine.
Client-side code
sendFriendRequest(user: User) {
this.afAuth.auth.currentUser.getIdToken().then(idToken => {
const url = 'https://us-central1-my-db-name.cloudfunctions.net/functionname/api/v1/friend-requests/';
this.http.post(url, JSON.stringify(user), {
headers: {'Authorization': idToken, 'Content-Type': 'application/json; charset=utf-8'}
}).subscribe((res) => {
console.log('res', res);
});
});
}
Server-side code
'use strict';
module.exports = ({ admin, cors, express, functions }) => {
const app = express();
const fireStore = admin.firestore();
const db = fireStore.collection('friendReqeusts');
app.use(cors({ origin: true }));
app.use((req, res, next) => {
console.log('HEADERS:', req.headers);
if (!req.headers.authorization) return res.status(403).json({ message: 'Missing Authorization Header' });
let jwt = req.headers.authorization.trim();
return admin.auth().verifyIdToken(jwt).then((claims) => {
req.user = claims; // gives us a user object to use below
next();
}).catch((err) => {
return res.status(400).json({
message: 'Invalid JWT'
});
});
});
app.post('/api/v1/friend-requests/', (req, res) => {
const recipientId = req.body.uid;
const frRef = db.doc(recipientId).collection('receiveFrom');
console.log('request body:', req.body);
console.log('requester:', req.user);
frRef.add({
uid: req.user.user_id,
displayName: req.user.name, // undefined only if a user first signed in
photoURL: req.user.picture, // undefined only if a user first signed in
timestamp: admin.firestore.FieldValue.serverTimestamp(),
message: "Let's be friends!"
}).then(() => {
res.status(200).send({message: 'Friend Requested!'});
}).catch((error) => console.log("Error writing document: ", error));
});
return functions.https.onRequest(app);
};
SOLVED
this.afAuth.auth.currentUser.getIdToken(true);
Fixed the problem.
bojeil answered my question in the following post.