Reconciled with new pull from master

This commit is contained in:
Aaron Sun
2019-09-30 23:22:09 -04:00
36 changed files with 6582 additions and 9171 deletions

View File

@@ -0,0 +1,28 @@
const admin = require('firebase-admin');
/* eslint-disable promise/always-return */
exports.putPost = (req, res) => {
const newPost = {
body: req.body.body,
userHandle: req.body.userHandle,
userImage: req.body.userImage,
microBlogTitle: req.body.microBlogTitle,
createdAt: new Date().toISOString(),
likeCount: 0,
commentCount: 0,
};
admin.firestore().collection('posts').add(newPost)
.then((doc) => {
const resPost = newPost;
resPost.postId = doc.id;
return res.status(200).json(resPost);
})
.catch((err) => {
console.error(err);
return res.status(500).json({ error: 'something is wrong'});
});
};

View File

@@ -0,0 +1,78 @@
const {db} = require('../util/admin');
const {validateUpdateProfileInfo} = require('../util/validator');
exports.getProfileInfo = (req, res) => {
// FIXME: Delete this after login is implemented
req.user = {};
req.user.handle = 'itsjimmy';
db.collection('users').doc(req.user.handle).get()
.then((data) => {
return res.status(200).json(data.data());
})
.catch((err) => {
console.error(err);
return res.status(500).json(err);
});
};
exports.updateProfileInfo = (req, res) => {
// FIXME: Delete this after login is implemented
req.user = {};
req.user.handle = 'itsjimmy';
// TODO: Add functionality for adding/updating profile images
// Data validation
const {valid, errors, profileData} = validateUpdateProfileInfo(req.body);
if (!valid) return res.status(400).json(errors);
// Update the database entry for this user
db.collection('users').doc(req.user.handle).set(profileData, {merge: true})
.then(() => {
console.log(`${req.user.handle}'s profile info has been updated.`)
return res.status(201).json({general: `${req.user.handle}'s profile info has been updated.`});
})
.catch((err) => {
console.error(err);
return res.status(500).json({
error: 'Error updating profile data'
});
})
};
exports.getUserDetails = (req, res) => {
let userData = {};
db.doc(`/users/${req.params.handle}`).get().then((doc) => {
if (doc.exists) {
userData.user = doc.data();
return db.collection('post').where('userHandle', '==', req.params.handle)
.orderBy('createdAt', 'desc').get();
} else {
return res.status(404).json({
error: 'User not found'
});
}
})
.then((data) => {
userData.posts = [];
data.forEach((doc) => {
userData.posts.push({
body: doc.data().body,
createAt: doc.data().createAt,
userHandle: doc.data().userHandle,
userImage: doc.data().userImage,
likeCount: doc.data().likeCount,
commentCount: doc.data().commentCount,
postId: doc.id
});
});
return res.json(userData);
})
.catch((err) => {
console.error(err);
return res.status(500).json({ error: err.code});
});
};

View File

@@ -1,9 +1,8 @@
/* eslint-disable promise/always-return */
const functions = require('firebase-functions');
const admin = require('firebase-admin');
const app = require('express')();
admin.initializeApp();
const db = admin.firestore();
const cors = require('cors');
app.use(cors());
var config = {
apiKey: "AIzaSyCvsWetg4qFdsPGfJ3LCw_QaaYzoan7Q34",
@@ -231,29 +230,29 @@ app.post('/login', (req, res) => {
});
});
app.get('/getUsers', (req, res) => {
admin.firestore().collection('users').get().then(data => {
let users = [];
data.forEach(doc => {
users.push(doc.data());
}); return res.json(users);
}).catch((err) => console.error(err));
});
/*------------------------------------------------------------------*
* handlers/users.js *
*------------------------------------------------------------------*/
const {getUserDetails, getProfileInfo, updateProfileInfo} = require('./handlers/users');
app.get('/getUser/:handle', getUserDetails);
// Returns all profile data of the currently logged in user
// TODO: Add fbAuth
app.get('/getProfileInfo', getProfileInfo);
// Updates the currently logged in user's profile information
// TODO: Add fbAuth
app.post('/updateProfileInfo', updateProfileInfo);
/*------------------------------------------------------------------*
* handlers/post.js *
*------------------------------------------------------------------*/
const {putPost} = require('./handlers/post');
// Adds one post to the database
app.post('/putPost', fbAuth, putPost);
app.post('/postUser', (req, res) => {
const newUser = {
body: req.body.body
};
admin.firestore().collection('users').add(newUser).then((doc) => {
res.json({
message: 'Successfully added!'
});
}).catch((err) => {
res.status(500).json({
error: "Error in posting user!"
});
console.error(err);
});
});
exports.api = functions.https.onRequest(app);

View File

@@ -26,7 +26,7 @@
"@firebase/app": {
"version": "0.4.17",
"resolved": "https://registry.npmjs.org/@firebase/app/-/app-0.4.17.tgz",
"integrity": "sha512-4aa6ixQlV6xQxj4HbwFKrfYZnnKk8AtB/vEEuIaBCGQYBvV287OVNCozXd4CC4Q4I4Vtkzrc+kggahYFl8nDWQ==",
"integrity": "sha512-YkCe10/KHnfJ5Lx79SCQ4ZJRlpnwe8Yns6Ntf7kltXq1hCQCUrKEU3zaOTPY90SBx36hYm47IaqkKwT/kBOK3A==",
"requires": {
"@firebase/app-types": "0.4.3",
"@firebase/logger": "0.1.25",
@@ -70,15 +70,36 @@
"integrity": "sha512-foQHhvyB0RR+mb/+wmHXd/VOU+D8fruFEW1k79Q9wzyTPpovMBa1Mcns5fwEWBhUfi8bmoEtaGB8RSAHnTFzTg=="
},
"@firebase/database": {
<<<<<<< HEAD
"version": "0.5.3",
"resolved": "https://registry.npmjs.org/@firebase/database/-/database-0.5.3.tgz",
"integrity": "sha512-LnXKRE1AmjlS+iRF7j8vx+Ni8x85CmLP5u5Pw5rDKhKLn2eTR1tJKD937mUeeGEtDHwR1rrrkLYOqRR2cSG3hQ==",
=======
"version": "0.5.4",
"resolved": "https://registry.npmjs.org/@firebase/database/-/database-0.5.4.tgz",
"integrity": "sha512-Hz1Bi3fzIcNNocE4EhvvwoEQGurG2BGssWD3/6a2bzty+K1e57SLea2Ied8QYNBUU1zt/4McHfa3Y71EQIyn/w==",
>>>>>>> 7969d3b10bc35a9078834c5ee2ba8c8fd60d338f
"requires": {
"@firebase/database-types": "0.4.3",
"@firebase/logger": "0.1.24",
"@firebase/util": "0.2.27",
"@firebase/logger": "0.1.25",
"@firebase/util": "0.2.28",
"faye-websocket": "0.11.3",
"tslib": "1.10.0"
},
"dependencies": {
"@firebase/logger": {
"version": "0.1.25",
"resolved": "https://registry.npmjs.org/@firebase/logger/-/logger-0.1.25.tgz",
"integrity": "sha512-/lRhuepVcCCnQ2jcO5Hr08SYdmZDTQU9fdPdzg+qXJ9k/QnIrD2RbswXQcL6mmae3uPpX7fFXQAoScJ9pzp50w=="
},
"@firebase/util": {
"version": "0.2.28",
"resolved": "https://registry.npmjs.org/@firebase/util/-/util-0.2.28.tgz",
"integrity": "sha512-ZQMAWtXj8y5kvB6izs0aTM/jG+WO8HpqhXA/EwD6LckJ+1P5LnAhaLZt1zR4HpuCE+jeP5I32Id5RJ/aifFs6A==",
"requires": {
"tslib": "1.10.0"
}
}
}
},
"@firebase/database-types": {
@@ -92,7 +113,11 @@
"@firebase/firestore": {
"version": "1.5.3",
"resolved": "https://registry.npmjs.org/@firebase/firestore/-/firestore-1.5.3.tgz",
<<<<<<< HEAD
"integrity": "sha512-CPYLvkGZBKE47oQC9a0q13UMVRj3LvnSbB1nOerktE3CGRHKy44LxDumamN8Kj067hV/80mKK9FdbeUufwO/Rg==",
=======
"integrity": "sha512-O/yAbXpitOA6g627cUl0/FHYlkTy1EiEKMKOlnlMOJF2fH+nLVZREXjsrCC7N2tIvTn7yYwfpZ4zpSNvrhwiTA==",
>>>>>>> 7969d3b10bc35a9078834c5ee2ba8c8fd60d338f
"requires": {
"@firebase/firestore-types": "1.5.0",
"@firebase/logger": "0.1.25",
@@ -335,9 +360,9 @@
"optional": true
},
"@google-cloud/storage": {
"version": "3.2.1",
"resolved": "https://registry.npmjs.org/@google-cloud/storage/-/storage-3.2.1.tgz",
"integrity": "sha512-129EwPGej6bXzY1u5nja2aeMDew6DIHaJn7ZV6nteQ74LQQSNv2jKrqTlyhndBsAwpuwQAxeghPTCoFT/H8Frg==",
"version": "3.3.0",
"resolved": "https://registry.npmjs.org/@google-cloud/storage/-/storage-3.3.0.tgz",
"integrity": "sha512-9jmHJ0ncQTcrZRwq5MRjXEwuCFkIjHenYwVbycV6bbZ4O84Hcgg4Yp33sKcJug5rvZeVgrpCzPbYXqO3B0LzJw==",
"optional": true,
"requires": {
"@google-cloud/common": "^2.1.1",
@@ -346,27 +371,50 @@
"arrify": "^2.0.0",
"compressible": "^2.0.12",
"concat-stream": "^2.0.0",
"date-and-time": "^0.9.0",
"date-and-time": "^0.10.0",
"duplexify": "^3.5.0",
"extend": "^3.0.2",
"gaxios": "^2.0.1",
"gcs-resumable-upload": "^2.0.0",
"gcs-resumable-upload": "^2.2.4",
"hash-stream-validation": "^0.2.1",
"mime": "^2.2.0",
"mime-types": "^2.0.8",
"onetime": "^5.1.0",
"p-limit": "^2.2.0",
"pumpify": "^2.0.0",
"readable-stream": "^3.4.0",
"snakeize": "^0.1.0",
"stream-events": "^1.0.1",
"through2": "^3.0.0",
"xdg-basedir": "^4.0.0"
},
"dependencies": {
"readable-stream": {
"version": "3.4.0",
"resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-3.4.0.tgz",
"integrity": "sha512-jItXPLmrSR8jmTRmRWJXCnGJsfy85mB3Wd/uINMXA65yrnFo0cPClFIUWzo2najVNSl+mx7/4W8ttlLWJe99pQ==",
"optional": true,
"requires": {
"inherits": "^2.0.3",
"string_decoder": "^1.1.1",
"util-deprecate": "^1.0.1"
}
},
"string_decoder": {
"version": "1.3.0",
"resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.3.0.tgz",
"integrity": "sha512-hkRX8U1WjJFd8LsDJ2yQ/wWWxaopEsABU1XfkM8A+j0+85JAGppt16cr1Whg6KIbb4okU6Mql6BOj+uup/wKeA==",
"optional": true,
"requires": {
"safe-buffer": "~5.2.0"
}
}
}
},
"@grpc/grpc-js": {
"version": "0.5.3",
"resolved": "https://registry.npmjs.org/@grpc/grpc-js/-/grpc-js-0.5.3.tgz",
"integrity": "sha512-doDzxjdN0IJihQJvjDkZun9bZp/TW2EKO5E4fNvw8634kU1eNqPnFtAmiEiIYptqJ9StC+zRo1mwrazhqI0k5A==",
"version": "0.5.4",
"resolved": "https://registry.npmjs.org/@grpc/grpc-js/-/grpc-js-0.5.4.tgz",
"integrity": "sha512-aY4fTCz7jq7oKFmfAeZVqGzMCR5I9NLdY9E2fJ70QtGXwlJnTaN6cnbRmCk23/aKPx9UHqOtk2lyjpN6LbAaxw==",
"optional": true,
"requires": {
"semver": "^6.2.0"
@@ -974,9 +1022,9 @@
"optional": true
},
"date-and-time": {
"version": "0.9.0",
"resolved": "https://registry.npmjs.org/date-and-time/-/date-and-time-0.9.0.tgz",
"integrity": "sha512-4JybB6PbR+EebpFx/KyR5Ybl+TcdXMLIJkyYsCx3P4M4CWGMuDyFF19yh6TyasMAIF5lrsgIxiSHBXh2FFc7Fg==",
"version": "0.10.0",
"resolved": "https://registry.npmjs.org/date-and-time/-/date-and-time-0.10.0.tgz",
"integrity": "sha512-IbIzxtvK80JZOVsWF6+NOjunTaoFVYxkAQoyzmflJyuRCJAJebehy48mPiCAedcGp4P7/UO3QYRWa0fe6INftg==",
"optional": true
},
"debug": {
@@ -1146,9 +1194,15 @@
}
},
"end-of-stream": {
<<<<<<< HEAD
"version": "1.4.1",
"resolved": "https://registry.npmjs.org/end-of-stream/-/end-of-stream-1.4.1.tgz",
"integrity": "sha512-1MkrZNvWTKCaigbn+W15elq2BB/L22nqrSY5DKlo3X6+vclJm8Bb5djXJBmEX6fS3+zCh/F4VBK5Z2KxJt4s2Q==",
=======
"version": "1.4.3",
"resolved": "https://registry.npmjs.org/end-of-stream/-/end-of-stream-1.4.3.tgz",
"integrity": "sha512-cbNhPFS6MlYlWTGncSiDYbdqKhwWFy7kNeb1YSOG6K65i/wPTkLVCJQj0hXA4j0m5Da+hBWnqopEnu1FFelisQ==",
>>>>>>> 7969d3b10bc35a9078834c5ee2ba8c8fd60d338f
"optional": true,
"requires": {
"once": "^1.4.0"
@@ -1713,9 +1767,9 @@
}
},
"google-gax": {
"version": "1.5.2",
"resolved": "https://registry.npmjs.org/google-gax/-/google-gax-1.5.2.tgz",
"integrity": "sha512-NceyDzlw4mQz6qH3bDIuRtfDAZKehM96QpnPPJ3Hur7FA/gPzpzboUYwhfP6q5obSP4LuSSDhI/76Fu51/ljtg==",
"version": "1.6.1",
"resolved": "https://registry.npmjs.org/google-gax/-/google-gax-1.6.1.tgz",
"integrity": "sha512-5/6uaUA9qAqRKVe2sjvMgsnU/HbfQisQTM5EZ5DfNGOYVBoTsPBdOhR2ZqEWPyqHe7YkdzVHev3FH9W3YWcORw==",
"optional": true,
"requires": {
"@grpc/grpc-js": "^0.5.2",
@@ -2186,9 +2240,15 @@
}
},
"gtoken": {
<<<<<<< HEAD
"version": "4.0.0",
"resolved": "https://registry.npmjs.org/gtoken/-/gtoken-4.0.0.tgz",
"integrity": "sha512-XaRCfHJxhj06LmnWNBzVTAr85NfAErq0W1oabkdqwbq3uL/QTB1kyvGog361Uu2FMG/8e3115sIy/97Rnd4GjQ==",
=======
"version": "4.1.0",
"resolved": "https://registry.npmjs.org/gtoken/-/gtoken-4.1.0.tgz",
"integrity": "sha512-wqyn2gf5buzEZN4QNmmiiW2i2JkEdZnL7Z/9p44RtZqgt4077m4khRgAYNuu8cBwHWCc6MsP6eDUn/KkF6jFIw==",
>>>>>>> 7969d3b10bc35a9078834c5ee2ba8c8fd60d338f
"optional": true,
"requires": {
"gaxios": "^2.0.0",

View File

@@ -13,9 +13,8 @@
"node": "10"
},
"dependencies": {
"express": "^4.17.1",
"firebase": "^6.6.2",
"firebase-admin": "^8.0.0",
"firebase-admin": "^8.6.0",
"firebase-functions": "^3.1.0"
},
"devDependencies": {

7
functions/util/admin.js Normal file
View File

@@ -0,0 +1,7 @@
const admin = require('firebase-admin');
admin.initializeApp();
const db = admin.firestore();
module.exports = { admin, db };

9
functions/util/config.js Normal file
View File

@@ -0,0 +1,9 @@
module.exports = {
apiKey: "AIzaSyCvsWetg4qFdsPGfJ3LCw_QaaYzoan7Q34",
authDomain: "twistter-e4649.firebaseapp.com",
databaseURL: "https://twistter-e4649.firebaseio.com",
projectId: "twistter-e4649",
storageBucket: "twistter-e4649.appspot.com",
messagingSenderId: "20131817365",
appId: "1:20131817365:web:633c95fb08b16d4526b89c"
};

34
functions/util/fbAuth.js Normal file
View File

@@ -0,0 +1,34 @@
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, res, next) => {
let idToken;
// Checking that the token exists in the header of the request
if (req.headers.authorization) {
idToken = req.headers.authorization;
} else {
console.error('No token found');
return res.status(403).json({ error: 'Unauthorized'});
}
// Checking that the token is valid in firebase
admin.auth().verifyIdToken(idToken)
.then((decodedToken) => {
req.user = 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
req.user.imageUrl = data.docs[0].data().imageUrl;
return next();
})
.catch((err) => {
console.error('Error while verifying token ', err);
return res.status(403).json(err);
});
};

View File

@@ -0,0 +1,36 @@
const isEmpty = (str) => {
if (str.trim() === '') return true;
else return false;
};
const isEmail = (str) => {
const emailRegEx = /^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
if (str.match(emailRegEx)) return true;
else return false;
}
exports.validateUpdateProfileInfo = (data) => {
let errors = {};
let profileData = {};
// ?: Should users be able to change their handles and emails?
// Only adds the key to the DB if the values are not empty
if (!isEmpty(data.firstName)) profileData.firstName = data.firstName.trim();
if (!isEmpty(data.lastName)) profileData.lastName = data.lastName.trim();
if (!isEmpty(data.bio)) profileData.bio = data.bio.trim();
if (isEmpty(data.email)) {
errors.email = "Must not be empty.";
} else if (!isEmail(data.email)) {
errors.email = "Must be a valid email."
} else {
profileData.email = data.email;
}
return {
errors,
valid: Object.keys(errors).length === 0 ? true : false,
profileData
}
};