mirror of
https://github.com/ClaytonWWilson/CS307-Team24.git
synced 2025-12-16 10:18:48 +00:00
35 lines
1.2 KiB
JavaScript
35 lines
1.2 KiB
JavaScript
const {admin, db} = require('./admin');
|
|
|
|
// Acts as a middleman between the client and any function that you use it with
|
|
// The function will only execute if the user is logged in, or rather, they have
|
|
// a valid token
|
|
module.exports = (req, resp, next) => {
|
|
let idToken;
|
|
|
|
// Checking that the token exists in the header of the request
|
|
if (req.headers.authorization && req.headers.authorization.startsWith('Bearer ')) {
|
|
idToken = req.headers.authorization.split('Bearer ')[1];
|
|
} else {
|
|
console.error('No token found');
|
|
return resp.status(403).json({ error: 'Unauthorized' });
|
|
}
|
|
|
|
// Checking that the token is valid in firebase
|
|
admin.auth().verifyIdToken(idToken)
|
|
.then(decodedToken => {
|
|
req.user = decodedToken;
|
|
console.log(decodedToken);
|
|
return db.collection('users')
|
|
.where('userId', '==', req.user.uid)
|
|
.limit(1)
|
|
.get();
|
|
})
|
|
.then(data => {
|
|
req.user.handle = data.docs[0].data().handle; // Save username
|
|
return next();
|
|
})
|
|
.catch(err => {
|
|
console.error('Error verifying token', err);
|
|
return res.status(403).json(err);
|
|
})
|
|
}; |