diff --git a/functions/handlers/post.js b/functions/handlers/post.js index 1db0144..ae839c3 100644 --- a/functions/handlers/post.js +++ b/functions/handlers/post.js @@ -1,43 +1,355 @@ +/* eslint-disable prefer-arrow-callback */ /* eslint-disable promise/always-return */ -const admin = require('firebase-admin'); +const admin = require("firebase-admin"); +const { db } = require("../util/admin"); + exports.putPost = (req, res) => { + const newPost = { + body: req.body.body, + userHandle: req.user.handle, + userImage: req.body.userImage, + userID: req.user.uid, + microBlogTitle: req.body.microBlogTitle, + createdAt: new Date().toISOString(), + likeCount: 0, + commentCount: 0, + microBlogTopics: req.body.microBlogTopics, + quoteBody: null + }; - const newPost = { - body: req.body.body, - userHandle: req.userData.handle, - userImage: req.body.userImage, - userID: req.userData.userId, - microBlogTitle: req.body.microBlogTitle, - createdAt: new Date().toISOString(), - likeCount: 0, - commentCount: 0, - microBlogTopics: req.body.microBlogTopics - - }; - - admin.firestore().collection('posts').add(newPost) - .then((doc) => { - const resPost = newPost; - resPost.postId = doc.id; - return res.status(200).json(resPost); + admin + .firestore() + .collection("posts") + .add(newPost) + .then(doc => { + doc.update({ postId: doc.id }); + 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'}); + .catch(err => { + console.error(err); + return res.status(500).json({ error: "something went wrong" }); }); }; exports.getallPostsforUser = (req, res) => { - admin.firestore().collection('posts').where('userHandle', '==', req.userData.handle ).get() - .then((data) => { - let posts = []; - data.forEach(function(doc) { - posts.push(doc.data()); - }); - return res.status(200).json(posts); + var post_query = admin + .firestore() + .collection("posts") + .where("userHandle", "==", req.user.handle); + + post_query + .get() + .then(function(myPosts) { + let posts = []; + myPosts.forEach(function(doc) { + posts.push(doc.data()); + }); + return res.status(200).json(posts); }) - .catch((err) => { - console.error(err); - return res.status(500).json({error: 'Failed to fetch all posts written by specific user.'}) + .then(function() { + return res + .status(200) + .json("Successfully retrieved all user's posts from database."); }) + .catch(function(err) { + return res + .status(500) + .json("Failed to retrieve user's posts from database.", err); + }); +}; + +exports.getallPosts = (req, res) => { + + var post_query = admin.firestore().collection("posts"); + post_query + .get() + .then(function(allPosts) { + let posts = []; + allPosts.forEach(function(doc) { + posts.push(doc.data()); + }); + return res.status(200).json(posts); + }) + .then(function() { + return res + .status(200) + .json("Successfully retrieved every post from database."); + }) + .catch(function(err) { + return res + .status(500) + .json("Failed to retrieve posts from database.", err); + }); +}; + +exports.getOtherUsersPosts = (req, res) => { + var post_query = admin + .firestore() + .collection("posts") + .where("userHandle", "==", req.body.handle); + + post_query + .get() + .then(function(myPosts) { + let posts = []; + myPosts.forEach(function(doc) { + posts.push(doc.data()); + }); + return res.status(200).json(posts); + }) + .then(function() { + return res + .status(200) + .json("Successfully retrieved all user's posts from database."); + }) + .catch(function(err) { + return res + .status(500) + .json("Failed to retrieve user's posts from database.", err); + }); +}; + +exports.quoteWithPost = (req, res) => { + let quoteData; + const quoteDoc = admin + .firestore() + .collection("quote") + .where("userHandle", "==", req.user.handle) + .where("postId", "==", req.params.postId) + .limit(1); + + const postDoc = db.doc(`/posts/${req.params.postId}`); + + postDoc + .get() + .then(doc => { + if (doc.exists) { + quoteData = doc.data(); + return quoteDoc.get(); + } else { + return res.status(404).json({ error: "Post not found" }); + } + }) + .then(data => { + if (data.empty) { + return admin + .firestore() + .collection("quote") + .add({ + quoteId: req.params.postId, + userHandle: req.user.handle, + quoteBody: req.body.quoteBody + }) + .then(() => { + const post = { + body: quoteData.body, + userHandle: req.user.handle, + quoteBody: req.body.quoteBody, + createdAt: new Date().toISOString(), + userImage: req.body.userImage, + likeCount: 0, + commentCount: 0, + userID: req.user.uid, + microBlogTitle: quoteData.microBlogTitle, + microBlogTopics: quoteData.microBlogTopics, + quoteId: req.params.postId + }; + return admin + .firestore() + .collection("posts") + .add(post) + .then(doc => { + doc.update({ postId: doc.id }); + const resPost = post; + resPost.postId = doc.id; + return res.status(200).json(resPost); + }); + }); + } else { + return res.status(400).json({ error: "Post has already been quoted." }); + } + }) + + .catch(err => { + return res.status(500).json({ error: err }); + }); +}; + +exports.quoteWithoutPost = (req, res) => { + let quoteData; + const quoteDoc = admin + .firestore() + .collection("quote") + .where("userHandle", "==", req.user.handle) + .where("postId", "==", req.params.postId) + .limit(1); + + const postDoc = db.doc(`/posts/${req.params.postId}`); + + postDoc + .get() + .then(doc => { + if (doc.exists) { + quoteData = doc.data(); + return quoteDoc.get(); + } else { + return res.status(404).json({ error: "Post not found" }); + } + }) + .then(data => { + if (data.empty) { + return admin + .firestore() + .collection("quote") + .add({ + quoteId: req.params.postId, + userHandle: req.user.handle, + quoteBody: null + }) + .then(() => { + const post = { + userHandle: req.user.handle, + body: quoteData.body, + quoteBody: null, + createdAt: new Date().toISOString(), + likeCount: 0, + commentCount: 0, + userID: req.user.uid, + userImage: req.body.userImage, + microBlogTitle: quoteData.microBlogTitle, + microBlogTopics: quoteData.microBlogTopics, + quoteId: req.params.postId + }; + return admin + .firestore() + .collection("posts") + .add(post) + .then(doc => { + doc.update({ postId: doc.id }); + const resPost = post; + resPost.postId = doc.id; + return res.status(200).json(resPost); + }); + }); + } else { + return res.status(400).json({ error: "Post has already been quoted." }); + } + }) + .catch(err => { + return res.status(500).json({ error: "Something is wrong" }); + }); +}; + +exports.checkforLikePost = (req, res) => { + const likedPostDoc = admin + .firestore() + .collection("likes") + .where("userHandle", "==", req.user.handle) + .where("postId", "==", req.params.postId) + .limit(1); + let result; + + likedPostDoc.get().then(data => { + if (data.empty) { + result = false; + return res.status(200).json(result); + } else { + result = true; + return res.status(200).json(result); + } + }); +}; + +exports.likePost = (req, res) => { + let postData; + const likeDoc = admin + .firestore() + .collection("likes") + .where("userHandle", "==", req.user.handle) + .where("postId", "==", req.params.postId) + .limit(1); + + const postDoc = db.doc(`/posts/${req.params.postId}`); + + postDoc + .get() + .then(doc => { + if (doc.exists) { + postData = doc.data(); + return likeDoc.get(); + } else { + return res.status(404).json({ error: "Post not found" }); + } + }) + + .then(data => { + if (data.empty) { + return admin + .firestore() + .collection("likes") + .add({ + postId: req.params.postId, + userHandle: req.user.handle + }) + .then(() => { + postData.likeCount++; + return postDoc.update({ likeCount: postData.likeCount }); + }) + .then(() => { + return res.status(200).json(postData); + }); + } + }) + .catch(err => { + return res.status(500).json({ error: "Something is wrong" }); + }); +}; + +exports.unlikePost = (req, res) => { + let postData; + const likeDoc = admin + .firestore() + .collection("likes") + .where("userHandle", "==", req.user.handle) + .where("postId", "==", req.params.postId) + .limit(1); + + const postDoc = db.doc(`/posts/${req.params.postId}`); + + postDoc + .get() + .then(doc => { + if (doc.exists) { + postData = doc.data(); + return likeDoc.get(); + } else { + return res.status(404).json({ error: "Post not found" }); + } + }) + .then(data => { + return db + .doc(`/likes/${data.docs[0].id}`) + .delete() + .then(() => { + postData.likeCount--; + return postDoc.update({ likeCount: postData.likeCount }); + }) + .then(() => { + res.status(200).json(postData); + }); + }) + .catch(err => { + console.error(err); + return res.status(500).json({ error: "Something is wrong" }); + }); +}; + +exports.getFilteredPosts = (req, res) => { + admin + .firestore() + .collection("posts") + .where("userHandle", "==", "new user") + .where("microBlogTopics", "=="); }; diff --git a/functions/handlers/topic.js b/functions/handlers/topic.js index 4d3dc3d..88e014e 100644 --- a/functions/handlers/topic.js +++ b/functions/handlers/topic.js @@ -1,52 +1,93 @@ -/* eslint-disable promise/always-return */ const { admin, db } = require("../util/admin"); exports.putTopic = (req, res) => { + let new_following = []; + let userRef = db.doc(`/users/${req.userData.handle}`); + userRef + .get() + .then(doc => { + new_following = doc.data().followedTopics; + new_following.push(req.body.following); - const newTopic = { - topic: req.body.topic - }; - - admin.firestore().collection('topics').add(newTopic) - .then((doc) => { - const resTopic = newTopic; - newTopic.topicId = doc.id; - return res.status(200).json(resTopic); + // add stuff + userRef + .set({ followedTopics: new_following }, { merge: true }) + .then(doc => { + return res + .status(201) + .json({ message: `Following ${req.body.following}` }); + }) + .catch(err => { + return res.status(500).json({ err }); + }); + return res.status(200).json({ message: "OK" }); }) - .catch((err) => { - console.error(err); - return res.status(500).json({ error: 'something is wrong'}); + .catch(err => { + return res.status(500).json({ err }); }); }; exports.getAllTopics = (req, res) => { - admin.firestore().collection('topics').get() - .then((data) => { - let topics = []; - data.forEach(function(doc) { - topics.push(doc.data()); + admin + .firestore() + .collection("topics") + .get() + .then(data => { + let topics = []; + data.forEach(function(doc) { + topics.push({ + topic: doc.data().topic, + id: doc.id }); - return res.status(200).json(topics); - }) - .catch((err) => { - console.error(err); - return res.status(500).json({error: 'Failed to fetch all topics.'}) + }); + return res.status(200).json(topics); }) + .catch(err => { + console.error(err); + return res.status(500).json({ error: "Failed to fetch all topics." }); + }); }; exports.deleteTopic = (req, res) => { - const topic = db.doc(`/topics/${req.params.topicId}`); - topic.get().then((doc) => { - if (!doc.exists) { - return res.status(404).json({error: 'Topic not found'}); - } else { - return topic.delete(); + let new_following = []; + let userRef = db.doc(`/users/${req.userData.handle}`); + userRef + .get() + .then(doc => { + new_following = doc.data().followedTopics; + // remove username from array + new_following.forEach(function(follower, index) { + if (follower === `${req.body.unfollow}`) { + new_following.splice(index, 1); } + }); + + // update database + userRef + .set({ followedTopics: new_following }, { merge: true }) + .then(doc => { + return res + .status(202) + .json({ message: `Successfully unfollow ${req.body.unfollow}` }); + }) + .catch(err => { + return res.status(500).json({ err }); + }); + return res.status(200).json({ message: "ok" }); }) - .then(() => { - res.json({ message: 'Topic successfully deleted!'}); + .catch(err => { + return res.status(500).json({ err }); + }); +}; + +exports.getUserTopics = (req, res) => { + let data = []; + db.doc(`/users/${req.body.handle}`) + .get() + .then(doc => { + data = doc.data().followedTopics; + return res.status(200).json({ data }); }) - .catch((err) => { - console.error(err); - return res.status(500).json({error: 'Failed to delete topic.'}) - }) -} \ No newline at end of file + .catch(err => { + return res.status(500).json({ err }); + }); +}; diff --git a/functions/handlers/users.js b/functions/handlers/users.js index 73efa8a..a2de242 100644 --- a/functions/handlers/users.js +++ b/functions/handlers/users.js @@ -8,8 +8,6 @@ const { validateUpdateProfileInfo } = require("../util/validator"); const firebase = require("firebase"); firebase.initializeApp(config); -var handle2Email = new Map(); - exports.signup = (req, res) => { const newUser = { email: req.body.email, @@ -60,7 +58,7 @@ exports.signup = (req, res) => { db.doc(`/users/${newUser.handle}`) .get() - .then((doc) => { + .then(doc => { if (doc.exists) { return res .status(400) @@ -70,27 +68,29 @@ exports.signup = (req, res) => { .auth() .createUserWithEmailAndPassword(newUser.email, newUser.password); }) - .then((data) => { + .then(data => { userId = data.user.uid; return data.user.getIdToken(); }) - .then((idToken) => { + .then(idToken => { token = idToken; + const defaultImageUrl = `https://firebasestorage.googleapis.com/v0/b/${config.storageBucket}/o/no-img.png?alt=media`; const userCred = { email: newUser.email, handle: newUser.handle, createdAt: newUser.createdAt, imageUrl: `https://firebasestorage.googleapis.com/v0/b/${config.storageBucket}/o/${noImg}?alt=media`, userId, - followedTopics: [] + followedTopics: [], + imageUrl: defaultImageUrl, + verified: false }; - handle2Email.set(userCred.handle, userCred.email); return db.doc(`/users/${newUser.handle}`).set(userCred); }) .then(() => { return res.status(201).json({ token }); }) - .catch((err) => { + .catch(err => { console.error(err); if (err.code === "auth/email-already-in-use") { return res.status(500).json({ email: "This email is already taken." }); @@ -102,7 +102,6 @@ exports.signup = (req, res) => { exports.login = (req, res) => { const user = { email: req.body.email, - handle: req.body.handle, password: req.body.password }; @@ -111,80 +110,291 @@ exports.login = (req, res) => { 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,}))$/; - // Email check + // Checks if email/username field is empty if (user.email.trim() === "") { errors.email = "Email must not be blank."; } - else if (!user.email.match(emailRegEx)) { - user.email = handle2Email.get(user.email); - } - // Password check + // Checks if password field is empty if (user.password.trim() === "") { errors.password = "Password must not be blank."; } - // Checking if any errors have been raised + // Checks if any of the above two errors were found if (Object.keys(errors).length > 0) { return res.status(400).json(errors); } - firebase - .auth() - .signInWithEmailAndPassword(user.email, user.password) - .then((data) => { - return data.user.getIdToken(); - }) - .then((token) => { - return res.status(200).json({ token }); - }) - .catch((err) => { - console.error(err); - if (err.code === "auth/wrong-password" || err.code === "auth/invalid-email" || err.code === "auth/user-not-found") { - return res - .status(403) - .json({ general: "Invalid credentials. Please try again." }); - } - return res.status(500).json({ error: err.code }); - }); + // Email/username field is username since it's not in email format + if (!user.email.match(emailRegEx)) { + var userDoc = db.collection("users").doc(`${user.email}`); + userDoc + .get() + .then(function(doc) { + if (doc.exists) { + user.email = doc.data().email; + } else { + return res + .status(403) + .json({ general: "Invalid credentials. Please try again." }); + } + return; + }) + .then(function() { + firebase + .auth() + .signInWithEmailAndPassword(user.email, user.password) + .then(data => { + return data.user.getIdToken(); + }) + .then(token => { + return res.status(200).json({ token }); + }) + .catch(err => { + console.error(err); + if ( + err.code === "auth/user-not-found" || + err.code === "auth/invalid-email" || + err.code === "auth/wrong-password" + ) { + return res + .status(403) + .json({ general: "Invalid credentials. Please try again." }); + } + return res.status(500).json({ error: err.code }); + }); + return; + }) + .catch(function(err) { + if (!doc.exists) { + return res + .status(403) + .json({ general: "Invalid credentials. Please try again." }); + } + return res.status(500).send(err); + }); + } + // Email/username field is username + else { + firebase + .auth() + .signInWithEmailAndPassword(user.email, user.password) + .then(data => { + return data.user.getIdToken(); + }) + .then(token => { + return res.status(200).json({ token }); + }) + .catch(err => { + console.error(err); + if ( + err.code === "auth/user-not-found" || + err.code === "auth/invalid-email" || + err.code === "auth/wrong-password" + ) { + return res + .status(403) + .json({ general: "Invalid credentials. Please try again." }); + } + return res.status(500).json({ error: err.code }); + }); + } }; -//Deletes user account +//Deletes user account and all associated data exports.deleteUser = (req, res) => { - var currentUser; + // Get the profile image filename + // `https://firebasestorage.googleapis.com/v0/b/${config.storageBucket}/o/${imageFileName}?alt=media` + let imageFileName; + req.userData.imageUrl + ? (imageFileName = req.userData.imageUrl.split("/o/")[1].split("?alt=")[0]) + : (imageFileName = "no-img.png"); - firebase.auth().onAuthStateChanged(function(user) { - currentUser = user; - if (currentUser) { - /*db.collection("users").doc(`${currentUser.handle}`).delete() - .then(function() { - res.status(200).send("Removed user from database."); + const userId = req.userData.userId; + let errors = {}; + + function thenFunction(data) { + console.log(`${data} for ${req.userData.handle} has been deleted.`); + } + + function catchFunction(data, err) { + console.error(err); + errors[data] = err; + } + + function deleteDirectMessages() { + return new Promise((resolve, reject) => { + const deleteUsername = req.userData.handle; + db.doc(`/users/${deleteUsername}`) + .get() + .then((deleteUserDocSnap) => { + const dms = deleteUserDocSnap.data().dms; + const dmRecipients = deleteUserDocSnap.data().dmRecipients; + + if (!dms) { + resolve(); + return; + } + + // Iterate over the list of users who this person has DM'd + let otherUsersPromises = []; + + // Resolve if they don't have a dmRecipients list + if (dmRecipients === undefined || dmRecipients === null || dmRecipients.length === 0) { + resolve(); + return; + } + dmRecipients.forEach((dmRecipient) => { + otherUsersPromises.push( + // Get each users data + db.doc(`/users/${dmRecipient}`).get() + .then((otherUserDocSnap) => { + // Get the index of deleteUsername so that we can remove the dangling + // reference to the DM document + let otherUserDMRecipients = otherUserDocSnap.data().dmRecipients; + let otherUserDMs = otherUserDocSnap.data().dms; + let index = -1; + otherUserDMRecipients.forEach((dmRecip, i) => { + if (dmRecip === deleteUsername) { + index = i; + } + }) + + if (index !== -1) { + // Remove deleteUsername from their dmRecipients list + otherUserDMRecipients.splice(index, 1); + + // Remove the DM channel with deleteUsername + otherUserDMs.splice(index, 1); + + // Update the users data + return otherUserDocSnap.ref.update({ + dmRecipients: otherUserDMRecipients, + dms: otherUserDMs + }); + } + + }) + ) + }) + + // Wait for the removal of DM data stored on other users to be deleted + Promise.all(otherUsersPromises) + .then(() => { + // Iterate through DM references and delete them from the dm collection + let dmRefsPromises = []; + dms.forEach((dmRef) => { + // Create a delete queue + let batch = db.batch(); + dmRefsPromises.push( + // Add the messages to the delete queue + db.collection(`/dm/${dmRef.id}/messages`).listDocuments() + .then((docs) => { + console.log("second") + console.log(docs); + docs.map((doc) => { + batch.delete(doc); + }) + + // Add the doc that the DM is stored in to the delete queue + batch.delete(dmRef); + + // Commit the writes + return batch.commit(); + }) + ) + }) + + return Promise.all(dmRefsPromises); + }) + .then(() => { + resolve(); + return; + }) + .catch((err) => { + console.log("error " + err); + reject(err); + return; + }) + }) + .catch((err) => { + console.log(err); + return res.status(500).json({error: err}); + }) + + }) + } + + // Deletes user from authentication + let auth = admin.auth().deleteUser(userId); + + // Deletes database data + let data = new Promise((resolve, reject) => { + deleteDirectMessages() + .then(() => { + return db + .collection("users") + .doc(`${req.user.handle}`) + .delete() + }) + .then(() => { + resolve(); return; }) - .catch(function(err) { - res.status(500).send("Failed to remove user from database.", err); - });*/ - - //let ref = db.collection('users'); - //let userDoc = ref.where('userId', '==', currentUser.uid).get(); - //userDoc.ref.delete(); - - currentUser.delete() - .then(function() { - console.log("User successfully deleted."); - res.status(200).send("Deleted user."); + .catch((err) => { + console.log(err); + reject(err); return; }) - .catch(function(err) { - console.log("Error deleting user.", err); - res.status(500).send("Failed to delete user."); + }) + + // Deletes any custom profile image + let image; + if (imageFileName !== "no-img.png") { + image = admin + .storage() + .bucket() + .file(imageFileName) + .delete(); + } else { + image = Promise.resolve(); + } + + // Deletes all users posts + let posts = db + .collection("posts") + .where("userHandle", "==", req.user.handle) + .get() + .then(query => { + query.forEach(snap => { + snap.ref.delete(); }); - } - else { - console.log("Cannot get user."); - res.status(500).send("Cannot get user."); - } - }); + return; + }); + + let promises = [ + auth.then(thenFunction("auth")).catch(err => catchFunction("auth", err)), + data.then(thenFunction("data")).catch(err => catchFunction("data", err)), + image.then(thenFunction("image")).catch(err => catchFunction("image", err)), + posts.then(thenFunction("posts")).catch(err => catchFunction("image", err)) + ]; + + // Wait for all promises to resolve + let waitPromise = Promise.all(promises); + + waitPromise + .then(() => { + if (Object.keys(errors) > 0) { + return res.status(500).json(errors); + } else { + return res.status(200).json({ + message: `All data for ${req.userData.handle} has been deleted.` + }); + } + }) + .catch(err => { + return res.status(500).json({ error: err }); + }); }; // Returns all data in the database for the user who is currently signed in @@ -192,10 +402,10 @@ exports.getProfileInfo = (req, res) => { db.collection("users") .doc(req.user.handle) .get() - .then((data) => { + .then(data => { return res.status(200).json(data.data()); }) - .catch((err) => { + .catch(err => { console.error(err); return res.status(500).json(err); }); @@ -203,8 +413,6 @@ exports.getProfileInfo = (req, res) => { // Updates the data in the database of the user who is currently logged in exports.updateProfileInfo = (req, res) => { - // TODO: Add functionality for adding/updating profile images - // Data validation const { valid, errors, profileData } = validateUpdateProfileInfo(req); if (!valid) return res.status(400).json(errors); @@ -215,13 +423,11 @@ exports.updateProfileInfo = (req, res) => { .set(profileData) .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.` - }); + return res.status(201).json({ + general: `${req.user.handle}'s profile info has been updated.` + }); }) - .catch((err) => { + .catch(err => { console.error(err); return res.status(500).json({ error: "Error updating profile data" @@ -233,37 +439,174 @@ exports.getUserDetails = (req, res) => { let userData = {}; db.doc(`/users/${req.body.handle}`) .get() - .then((doc) => { + .then(doc => { if (doc.exists) { userData = doc.data(); - return res.status(200).json({userData}); - } else { - return res.status(400).json({error: "User not found."}) - }}) - .catch((err) => { + return res.status(200).json({ userData }); + } else { + return res.status(400).json({ error: "User not found." }); + } + }) + .catch(err => { console.error(err); return res.status(500).json({ error: err.code }); }); }; +exports.getAllHandles = (req, res) => { + var user_query = admin.firestore().collection("users"); + user_query.get() + .then((allUsers) => { + let users = []; + allUsers.forEach((user) => { + users.push(user.data().handle); + }); + return res.status(200).json(users); + }) + .catch((err) => { + return res.status(500).json({ + message:"Failed to retrieve posts from database.", + error: err + }); + }); +}; + // Returns all data stored for a user exports.getAuthenticatedUser = (req, res) => { let credentials = {}; db.doc(`/users/${req.user.handle}`) .get() - .then((doc) => { + .then(doc => { if (doc.exists) { credentials = doc.data(); - return res.status(200).json({credentials}); - } else { - return res.status(400).json({error: "User not found."}) - }}) - .catch((err) => { + return res.status(200).json({ credentials }); + } else { + return res.status(400).json({ error: "User not found." }); + } + }) + .catch(err => { console.error(err); return res.status(500).json({ error: err.code }); }); }; +// Verifies the user sent to the request +// Must be run by the Admin user +exports.verifyUser = (req, res) => { + if (req.userData.handle !== "Admin") { + return res.status(403).json({ error: "This must be done as Admin" }); + } + + db.doc(`/users/${req.body.user}`) + .get() + .then(doc => { + if (doc.exists) { + let verifiedUser = doc.data(); + verifiedUser.verified = true; + return db + .doc(`/users/${req.body.user}`) + .set(verifiedUser, { merge: true }); + } else { + return res + .status(400) + .json({ error: `User ${req.body.user} was not found` }); + } + }) + .then(() => { + return res + .status(201) + .json({ message: `${req.body.user} is now verified` }); + }) + .catch(err => { + console.error(err); + return res.status(500).json({ error: err.code }); + }); +}; + +// Unverifies the user sent to the request +// Must be run by admin +exports.unverifyUser = (req, res) => { + if (req.userData.handle !== "Admin") { + return res.status(403).json({ error: "This must be done as Admin" }); + } + + db.doc(`/users/${req.body.user}`) + .get() + .then(doc => { + if (doc.exists) { + let unverifiedUser = doc.data(); + unverifiedUser.verified = false; + return db + .doc(`/users/${req.body.user}`) + .set(unverifiedUser, { merge: true }); + } else { + return res + .status(400) + .json({ error: `User ${req.body.user} was not found` }); + } + }) + .then(() => { + return res + .status(201) + .json({ message: `${req.body.user} is no longer verified` }); + }) + .catch(err => { + console.error(err); + return res.status(500).json({ error: err.code }); + }); +}; +exports.getUserHandles = (req, res) => { + db.doc(`/users/${req.body.userHandle}`) + .get() + .then(doc => { + if (doc.exists) { + let userHandle = doc.data().handle; + return res.status(200).json(userHandle); + } else { + return res.status(404).json({ error: "user not found" }); + } + }) + .catch(err => { + console.error(err); + return res.status(500).json({ error: "Failed to get all user handles." }); + }); +}; + +exports.addSubscription = (req, res) => { + let new_following = []; + let userRef = db.doc(`/users/${req.userData.handle}`); + userRef.get().then(doc => { + new_following = doc.data().following; + new_following.push(req.body.following); + + // add stuff + userRef + .set({ following: new_following }, { merge: true }) + .then(doc => { + return res + .status(201) + .json({ message: `Following ${req.body.following}` }); + }) + .catch(err => { + return res.status(500).json({ err }); + }); + return res.status(200).json({ message: "ok" }); + }); +}; + +exports.getSubs = (req, res) => { + let data = []; + db.doc(`/users/${req.userData.handle}`) + .get() + .then(doc => { + data = doc.data().following; + return res.status(200).json({ data }); + }) + .catch(err => { + return res.status(500).json({ err }); + }); +}; + // Uploads a profile image exports.uploadProfileImage = (req, res) => { const BusBoy = require("busboy"); @@ -383,3 +726,31 @@ exports.uploadProfileImage = (req, res) => { // }); // busboy.end(req.rawBody); } + +exports.removeSub = (req, res) => { + let new_following = []; + let userRef = db.doc(`/users/${req.userData.handle}`); + userRef.get().then(doc => { + new_following = doc.data().following; + // remove username from array + new_following.forEach(function(follower, index) { + if (follower === `${req.body.unfollow}`) { + new_following.splice(index, 1); + } + }); + + // update database + userRef + .set({ following: new_following }, { merge: true }) + .then(doc => { + return res + .status(202) + .json({ message: `Successfully unfollow ${req.body.unfollow}` }); + }) + .catch(err => { + return res.status(500).json({ err }); + }); + + return res.status(200).json({ message: "ok" }); + }); +}; diff --git a/functions/index.js b/functions/index.js index 155363c..4f7c3fb 100644 --- a/functions/index.js +++ b/functions/index.js @@ -11,13 +11,20 @@ app.use(cors()); *------------------------------------------------------------------*/ const { getAuthenticatedUser, + getAllHandles, getUserDetails, getProfileInfo, login, signup, deleteUser, updateProfileInfo, - uploadProfileImage + uploadProfileImage, + verifyUser, + unverifyUser, + getUserHandles, + addSubscription, + getSubs, + removeSub } = require("./handlers/users"); // Adds a user to the database and registers them in firebase with @@ -30,9 +37,13 @@ app.post("/signup", signup); app.post("/login", login); //Deletes user account -app.delete("/delete", deleteUser); +app.delete("/delete", fbAuth, deleteUser); -app.get("/getUser", fbAuth, getUserDetails); +app.post("/getUserDetails", fbAuth, getUserDetails); + +// Returns a list of all usernames +// Used for searching +app.get("/getAllHandles", fbAuth, getAllHandles); // Returns all profile data of the currently logged in user app.get("/getProfileInfo", fbAuth, getProfileInfo); @@ -47,24 +58,65 @@ app.get("/user", fbAuth, getAuthenticatedUser); // Uploads a profile image app.post("/user/image", fbAuth, uploadProfileImage); +// Verifies the user sent to the request +// Must be run by the Admin user +app.post("/verifyUser", fbAuth, verifyUser); + +// Unverifies the user sent to the request +// Must be run by admin +app.post("/unverifyUser", fbAuth, unverifyUser); + +// get user handles with search phase +app.post("/getUserHandles", fbAuth, getUserHandles); + +// get user's subscription +app.get("/getSubs", fbAuth, getSubs); + +// add user to another user's "following" data field +app.post("/addSubscription", fbAuth, addSubscription); + +// remove one subscription +app.post("/removeSub", fbAuth, removeSub); + /*------------------------------------------------------------------* * handlers/post.js * *------------------------------------------------------------------*/ -const { getallPostsforUser, putPost +const { + getallPostsforUser, + getallPosts, + putPost, + likePost, + unlikePost, + quoteWithPost, + quoteWithoutPost, + checkforLikePost, + getOtherUsersPosts } = require("./handlers/post"); -app.get("/getallPostsforUser", getallPostsforUser); +app.get("/getallPostsforUser", fbAuth, getallPostsforUser); + +app.get("/getallPosts", getallPosts); // Adds one post to the database app.post("/putPost", fbAuth, putPost); +app.get("/like/:postId", fbAuth, likePost); +app.get("/unlike/:postId", fbAuth, unlikePost); +app.get("/checkforLikePost/:postId", fbAuth, checkforLikePost); + +app.post("/quoteWithPost/:postId", fbAuth, quoteWithPost); +app.post("/quoteWithoutPost/:postId", fbAuth, quoteWithoutPost); + +app.post("/getOtherUsersPosts", fbAuth, getOtherUsersPosts); + /*------------------------------------------------------------------* * handlers/topic.js * *------------------------------------------------------------------*/ const { putTopic, getAllTopics, - deleteTopic + deleteTopic, + getUserTopics } = require("./handlers/topic"); // add topic to database @@ -74,6 +126,9 @@ app.post("/putTopic", fbAuth, putTopic); app.get("/getAllTopics", fbAuth, getAllTopics); // delete a specific topic -app.delete("/deleteTopic/:topicId", fbAuth, deleteTopic); +app.post("/deleteTopic", fbAuth, deleteTopic); + +// get topic for this user +app.post("/getUserTopics", fbAuth, getUserTopics); exports.api = functions.https.onRequest(app); diff --git a/twistter-frontend/package.json b/twistter-frontend/package.json index f7dd12f..52e50f3 100644 --- a/twistter-frontend/package.json +++ b/twistter-frontend/package.json @@ -10,11 +10,13 @@ "axios": "^0.19.0", "clsx": "^1.0.4", "create-react-app": "^3.1.2", + "fuse.js": "^3.4.6", "install": "^0.13.0", "jwt-decode": "^2.2.0", "node-pre-gyp": "^0.13.0", "react": "^16.9.0", "react-dom": "^16.9.0", + "react-modal": "^3.11.1", "react-redux": "^7.1.1", "react-router-dom": "^5.1.0", "react-scripts": "0.9.5", @@ -41,5 +43,5 @@ "last 1 safari version" ] }, - "proxy": "https://us-central1-twistter-e4649.cloudfunctions.net/api" + "proxy": "http://localhost:5001/twistter-e4649/us-central1/api" } diff --git a/twistter-frontend/src/App.js b/twistter-frontend/src/App.js index 2335b20..1ed56dc 100644 --- a/twistter-frontend/src/App.js +++ b/twistter-frontend/src/App.js @@ -10,33 +10,33 @@ import jwtDecode from "jwt-decode"; // Redux import { Provider } from "react-redux"; import store from "./redux/store"; -import MuiThemeProvider from '@material-ui/core/styles/MuiThemeProvider'; -import createMuiTheme from '@material-ui/core/styles/createMuiTheme'; -import themeObject from './util/theme'; -import { SET_AUTHENTICATED } from './redux/types'; -import { logoutUser, getUserData } from './redux/actions/userActions'; +import MuiThemeProvider from "@material-ui/core/styles/MuiThemeProvider"; +import createMuiTheme from "@material-ui/core/styles/createMuiTheme"; +import themeObject from "./util/theme"; +import { SET_AUTHENTICATED } from "./redux/types"; +import { logoutUser, getUserData } from "./redux/actions/userActions"; // Components import AuthRoute from "./util/AuthRoute"; -// axios.defaults.baseURL = 'http://localhost:5006/twistter-e4649/us-central1/api'; - // Pages -import home from './pages/Home'; -import signup from './pages/Signup'; -import login from './pages/Login'; -import user from './pages/user'; -import logout from './pages/Logout'; -import Delete from './pages/Delete'; -import writeMicroblog from './Writing_Microblogs.js'; -import editProfile from './pages/editProfile'; -import userLine from './Userline.js'; +import home from "./pages/Home"; +import signup from "./pages/Signup"; +import login from "./pages/Login"; +import user from "./pages/user"; +import logout from "./pages/Logout"; +import Delete from "./pages/Delete"; +import writeMicroblog from "./Writing_Microblogs.js"; +import editProfile from "./pages/editProfile"; +import userLine from "./Userline.js"; +import verify from "./pages/verify"; +import Search from "./pages/Search.js"; +import otherUser from "./pages/otherUser"; const theme = createMuiTheme(themeObject); const token = localStorage.FBIdToken; if (token) { - try { const decodedToken = jwtDecode(token); if (decodedToken.exp * 1000 < Date.now()) { @@ -44,7 +44,7 @@ if (token) { window.location.href = "/login"; } else { store.dispatch({ type: SET_AUTHENTICATED }); - axios.defaults.headers.common['Authorization'] = token; + axios.defaults.headers.common["Authorization"] = token; store.dispatch(getUserData()); } } catch (invalidTokenError) { @@ -53,34 +53,35 @@ if (token) { } } - class App extends Component { render() { return ( -
+
-
- {/* AuthRoute checks if the user is logged in and if they are it redirects them to /home */} - - - - + {/* AuthRoute checks if the user is logged in and if they are it redirects them to /home */} + + + - - - - {/* */} + + - + + + + + + + +
- diff --git a/twistter-frontend/src/Userline.js b/twistter-frontend/src/Userline.js index 8c95620..6c61d6d 100644 --- a/twistter-frontend/src/Userline.js +++ b/twistter-frontend/src/Userline.js @@ -1,10 +1,10 @@ import React, { Component } from "react"; -import { BrowserRouter as Router } from 'react-router-dom'; -import Route from 'react-router-dom/Route'; +// import { BrowserRouter as Router } from 'react-router-dom'; +// import Route from 'react-router-dom/Route'; import axios from 'axios'; import Box from '@material-ui/core/Box' -import {borders} from '@material-ui/system'; -import { sizing } from '@material-ui/system'; +// import {borders} from '@material-ui/system'; +// import { sizing } from '@material-ui/system'; // var moment = require('moment'); @@ -41,7 +41,7 @@ class Userline extends Component {

Userline

- +

{sortedPosts.map((microBlog) =>

Microblog Title: {microBlog.microBlogTitle} @@ -50,7 +50,7 @@ class Userline extends Component {

Number of comments: {microBlog.commentCount}

Number of likes: {microBlog.likeCount}

Body of post: {microBlog.body} -

Tagged topics: {microBlog.microBlogTopics.join("," + " ")} +

Tagged topics: {microBlog.microBlogTopics.join(", ")}

)}

diff --git a/twistter-frontend/src/Writing_Microblogs.js b/twistter-frontend/src/Writing_Microblogs.js index 6ddb974..70b67d0 100644 --- a/twistter-frontend/src/Writing_Microblogs.js +++ b/twistter-frontend/src/Writing_Microblogs.js @@ -1,107 +1,165 @@ import React, { Component } from "react"; -import { BrowserRouter as Router } from 'react-router-dom'; -import Route from 'react-router-dom/Route'; -import axios from 'axios'; - - -class Writing_Microblogs extends Component { - - constructor(props) { - super(props); - this.state = { - value: '', - title: '', - topics: '', - characterCount: 250 - - }; - - - this.handleChange = this.handleChange.bind(this); - this.handleSubmit = this.handleSubmit.bind(this); - this.handleChangeforPost = this.handleChangeforPost.bind(this); - this.handleChangeforTopics = this.handleChangeforTopics.bind(this); - - } - - handleChange(event) { - this.setState( {title: event.target.value }); - } - - handleChangeforTopics(event) { - this.setState( {topics: event.target.value}); - } - - handleSubmit(event) { - // alert('A title for the microblog was inputted: ' + this.state.title + '\nA microblog was posted: ' + this.state.value); - const postData = { - body: this.state.value, - userImage: "bing-url", - microBlogTitle: this.state.title, - microBlogTopics: this.state.topics.split(', ') - } - const headers = { - headers: { 'Content-Type': 'application/json'} - } - - axios - .post("/putPost", postData, headers) - .then((res) =>{ - alert('Post was shared successfully!') - console.log(res.data); - }) - .catch((err) => { - alert('An error occured.'); - console.error(err); - }) - event.preventDefault(); - this.setState({value: '', title: '',characterCount: 250, topics: ''}) - } - - handleChangeforPost(event) { - this.setState({value: event.target.value }) - } - - handleChangeforCharacterCount(event) { - const charCount = event.target.value.length - const charRemaining = 250 - charCount - this.setState({characterCount: charRemaining }) - - } - - render() { - return ( -
-
-
-