diff --git a/functions/handlers/post.js b/functions/handlers/post.js index a72be0e..2be5bda 100644 --- a/functions/handlers/post.js +++ b/functions/handlers/post.js @@ -23,23 +23,46 @@ exports.putPost = (req, res) => { }) .catch((err) => { console.error(err); - return res.status(500).json({ error: 'something is wrong'}); + 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) => { + var post_query = admin.firestore().collection("posts").where("userHandle", "==", req.user.handle); + post_query.get() + .then(function(myPosts) { let posts = []; - data.forEach(function(doc) { + 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() { + res.status(200).send("Successfully retrieved all user's posts from database."); + return; }) + .catch(function(err) { + res.status(500).send("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() { + res.status(200).send("Successfully retrieved every post from database."); + return; + }) + .catch(function(err) { + res.status(500).send("Failed to retrieve posts from database.", err); + }); }; exports.getFilteredPosts = (req, res) => { diff --git a/functions/handlers/topic.js b/functions/handlers/topic.js index 4d3dc3d..a55f748 100644 --- a/functions/handlers/topic.js +++ b/functions/handlers/topic.js @@ -1,52 +1,60 @@ -/* eslint-disable promise/always-return */ const { admin, db } = require("../util/admin"); exports.putTopic = (req, res) => { + const newTopic = { + topic: req.body.topic + }; - 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); + admin + .firestore() + .collection("topics") + .add(newTopic) + .then(doc => { + const resTopic = newTopic; + return res.status(200).json(resTopic); }) - .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 is wrong" }); }); }; 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(); - } + 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(); + } }) .then(() => { - res.json({ message: 'Topic successfully deleted!'}); + return res.json({ message: "Topic successfully deleted!" }); }) - .catch((err) => { - console.error(err); - return res.status(500).json({error: 'Failed to delete topic.'}) - }) -} \ No newline at end of file + .catch(err => { + console.error(err); + return res.status(500).json({ error: "Failed to delete topic." }); + }); +}; diff --git a/functions/handlers/users.js b/functions/handlers/users.js index e1f58fe..1e9ecf0 100644 --- a/functions/handlers/users.js +++ b/functions/handlers/users.js @@ -1,5 +1,4 @@ /* eslint-disable promise/catch-or-return */ - const { admin, db } = require("../util/admin"); const config = require("../util/config"); const { validateUpdateProfileInfo } = require("../util/validator"); @@ -55,7 +54,7 @@ exports.signup = (req, res) => { db.doc(`/users/${newUser.handle}`) .get() - .then((doc) => { + .then(doc => { if (doc.exists) { return res .status(400) @@ -65,18 +64,20 @@ 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, userId, followedTopics: [], + imageUrl: defaultImageUrl, verified: false }; return db.doc(`/users/${newUser.handle}`).set(userCred); @@ -84,7 +85,7 @@ exports.signup = (req, res) => { .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." }); @@ -122,116 +123,153 @@ exports.login = (req, res) => { // 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) { + 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." }); + } 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 }); + .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((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." }); + .catch(function(err) { + if (!doc.exists) { + return res + .status(403) + .json({ general: "Invalid credentials. Please try again." }); } - return res.status(500).json({ error: err.code }); + return res.status(500).send(err); }); - 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 }); - }); + .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; - firebase.auth().onAuthStateChanged(function(user) { - currentUser = user; - if (currentUser) { - var post_query = db.collection("posts").where("userHandle", "==", req.user.handle); - post_query.get() - .then(function(myPosts) { - myPosts.forEach(function(doc) { - doc.ref.delete(); - }); - return; + // 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' + + const userId = req.userData.userId; + let errors = {}; + + function thenFunction(data) { + console.log(`${data} data for ${req.userData.handle} has been deleted.`); + } + + function catchFunction(data, err) { + console.error(err); + errors[data] = err; + } + + // Deletes user from authentication + let auth = admin.auth().deleteUser(userId); + + // Deletes database data + let data = db.collection("users").doc(`${req.user.handle}`).delete(); + + // 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(); }) - .then(function() { - res.status(200).send("Successfully removed all user's posts from database."); - return; - }) - .catch(function(err) { - res.status(500).send("Failed to remove all user's posts from database.", err); - }); + }) + + 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); - db.collection("users").doc(`${req.user.handle}`).delete() - .then(function() { - res.status(200).send("Sucessfully removed user from database."); - return; - }) - .catch(function(err) { - res.status(500).send("Failed to remove user from database.", err); - }); - - - - currentUser.delete() - .then(function() { - console.log("Successfully deleted user."); - res.status(200).send("Sucessfully deleted user."); - return; - }) - .catch(function(err) { - console.log("Failed to delete user.", err); - res.status(500).send("Failed to delete user."); - }); - } - else { - console.log("Failed to deleter user or cannot get user."); - res.status(500).send("Failed to deleter user or cannot get user."); + 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 @@ -239,10 +277,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); }); @@ -260,13 +298,11 @@ exports.updateProfileInfo = (req, res) => { .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.` - }); + 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" @@ -278,14 +314,15 @@ 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 }); }); @@ -295,14 +332,15 @@ 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 }); }); @@ -360,4 +398,21 @@ exports.unverifyUser = (req, res) => { console.error(err); return res.status(500).json({error: err.code}); }); -} \ No newline at end of file +} +exports.getUserHandles = (req, res) => { + admin + .firestore() + .collection("users") + .get() + .then(data => { + let users = []; + data.forEach(function(doc) { + users.push(doc.data().handle); + }); + return res.status(200).json(users); + }) + .catch(err => { + console.error(err); + return res.status(500).json({ error: "Failed to get all user handles." }); + }); +}; diff --git a/functions/index.js b/functions/index.js index 59bc8db..f05c7b8 100644 --- a/functions/index.js +++ b/functions/index.js @@ -18,7 +18,8 @@ const { deleteUser, updateProfileInfo, verifyUser, - unverifyUser + unverifyUser, + getUserHandles } = require("./handlers/users"); // Adds a user to the database and registers them in firebase with @@ -51,13 +52,17 @@ app.post("/verifyUser", fbAuth, verifyUser); // Must be run by admin app.post("/unverifyUser", fbAuth, unverifyUser); +// get user handles with search phase +app.get("/getUserHandles", fbAuth, getUserHandles); + /*------------------------------------------------------------------* * handlers/post.js * *------------------------------------------------------------------*/ -const { getallPostsforUser, putPost -} = require("./handlers/post"); +const { getallPostsforUser, getallPosts, putPost } = 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); @@ -65,11 +70,7 @@ app.post("/putPost", fbAuth, putPost); /*------------------------------------------------------------------* * handlers/topic.js * *------------------------------------------------------------------*/ -const { - putTopic, - getAllTopics, - deleteTopic -} = require("./handlers/topic"); +const { putTopic, getAllTopics, deleteTopic } = require("./handlers/topic"); // add topic to database app.post("/putTopic", fbAuth, putTopic); diff --git a/twistter-frontend/src/App.js b/twistter-frontend/src/App.js index 0420d45..71c16a2 100644 --- a/twistter-frontend/src/App.js +++ b/twistter-frontend/src/App.js @@ -10,11 +10,11 @@ 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"; @@ -22,21 +22,21 @@ 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 Search from "./pages/Search.js"; 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,33 +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/Writing_Microblogs.js b/twistter-frontend/src/Writing_Microblogs.js index 0734d1c..9cac7b7 100644 --- a/twistter-frontend/src/Writing_Microblogs.js +++ b/twistter-frontend/src/Writing_Microblogs.js @@ -1,107 +1,128 @@ import React, { Component } from "react"; -import { BrowserRouter as Router } from 'react-router-dom'; -import Route from 'react-router-dom/Route'; -import axios from 'axios'; - +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 + }; - 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); + } - - 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 }); + } - handleChange(event) { - this.setState( {title: event.target.value }); - } + handleChangeforTopics(event) { + this.setState({ topics: 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" } + }; - handleSubmit(event) { + 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: "" }); + } - 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 }); + } - handleChangeforPost(event) { - this.setState({value: event.target.value }) - } + handleChangeforCharacterCount(event) { + const charCount = event.target.value.length; + const charRemaining = 250 - charCount; + this.setState({ characterCount: charRemaining }); + } - handleChangeforCharacterCount(event) { - const charCount = event.target.value.length - const charRemaining = 250 - charCount - this.setState({characterCount: charRemaining }) - - } + render() { + return ( +
+
+
+