Merge branch 'master' into auth-backend-3

This commit is contained in:
Clayton Wilson 2019-10-31 16:09:17 -04:00 committed by GitHub
commit ce984df437
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
6 changed files with 230 additions and 183 deletions

View File

@ -1,3 +1,4 @@
/* eslint-disable prefer-arrow-callback */
/* eslint-disable promise/always-return */ /* eslint-disable promise/always-return */
const admin = require('firebase-admin'); const admin = require('firebase-admin');
@ -63,3 +64,7 @@ exports.getallPosts = (req, res) => {
res.status(500).send("Failed to retrieve posts from database.", err); res.status(500).send("Failed to retrieve posts from database.", err);
}); });
}; };
exports.getFilteredPosts = (req, res) => {
admin.firestore().collection('posts').where('userHandle', '==', 'new user').where('microBlogTopics', '==')
};

View File

@ -1,52 +1,61 @@
/* eslint-disable promise/always-return */ /* eslint-disable promise/always-return */
const { admin, db } = require("../util/admin"); const { admin, db } = require("../util/admin");
exports.putTopic = (req, res) => { exports.putTopic = (req, res) => {
const newTopic = { const newTopic = {
topic: req.body.topic topic: req.body.topic
}; };
admin.firestore().collection('topics').add(newTopic) admin
.then((doc) => { .firestore()
.collection("topics")
.add(newTopic)
.then(doc => {
const resTopic = newTopic; const resTopic = newTopic;
newTopic.topicId = doc.id;
return res.status(200).json(resTopic); return res.status(200).json(resTopic);
}) })
.catch((err) => { .catch(err => {
console.error(err); console.error(err);
return res.status(500).json({ error: 'something is wrong'}); return res.status(500).json({ error: "something is wrong" });
}); });
}; };
exports.getAllTopics = (req, res) => { exports.getAllTopics = (req, res) => {
admin.firestore().collection('topics').get() admin
.then((data) => { .firestore()
.collection("topics")
.get()
.then(data => {
let topics = []; let topics = [];
data.forEach(function(doc) { data.forEach(function(doc) {
topics.push(doc.data()); topics.push({
topic: doc.data().topic,
id: doc.id
});
}); });
return res.status(200).json(topics); return res.status(200).json(topics);
}) })
.catch((err) => { .catch(err => {
console.error(err); console.error(err);
return res.status(500).json({error: 'Failed to fetch all topics.'}) return res.status(500).json({ error: "Failed to fetch all topics." });
}) });
}; };
exports.deleteTopic = (req, res) => { exports.deleteTopic = (req, res) => {
const topic = db.doc(`/topics/${req.params.topicId}`); const topic = db.doc(`/topics/${req.params.topicId}`);
topic.get().then((doc) => { topic
.get()
.then(doc => {
if (!doc.exists) { if (!doc.exists) {
return res.status(404).json({error: 'Topic not found'}); return res.status(404).json({ error: "Topic not found" });
} else { } else {
return topic.delete(); return topic.delete();
} }
}) })
.then(() => { .then(() => {
res.json({ message: 'Topic successfully deleted!'}); res.json({ message: "Topic successfully deleted!" });
}) })
.catch((err) => { .catch(err => {
console.error(err); console.error(err);
return res.status(500).json({error: 'Failed to delete topic.'}) return res.status(500).json({ error: "Failed to delete topic." });
}) });
} };

View File

@ -56,11 +56,7 @@ app.post("/putPost", fbAuth, putPost);
/*------------------------------------------------------------------* /*------------------------------------------------------------------*
* handlers/topic.js * * handlers/topic.js *
*------------------------------------------------------------------*/ *------------------------------------------------------------------*/
const { const { putTopic, getAllTopics, deleteTopic } = require("./handlers/topic");
putTopic,
getAllTopics,
deleteTopic
} = require("./handlers/topic");
// add topic to database // add topic to database
app.post("/putTopic", fbAuth, putTopic); app.post("/putTopic", fbAuth, putTopic);

View File

@ -10,11 +10,11 @@ import jwtDecode from "jwt-decode";
// Redux // Redux
import { Provider } from "react-redux"; import { Provider } from "react-redux";
import store from "./redux/store"; import store from "./redux/store";
import MuiThemeProvider from '@material-ui/core/styles/MuiThemeProvider'; import MuiThemeProvider from "@material-ui/core/styles/MuiThemeProvider";
import createMuiTheme from '@material-ui/core/styles/createMuiTheme'; import createMuiTheme from "@material-ui/core/styles/createMuiTheme";
import themeObject from './util/theme'; import themeObject from "./util/theme";
import { SET_AUTHENTICATED } from './redux/types'; import { SET_AUTHENTICATED } from "./redux/types";
import { logoutUser, getUserData } from './redux/actions/userActions'; import { logoutUser, getUserData } from "./redux/actions/userActions";
// Components // Components
import AuthRoute from "./util/AuthRoute"; import AuthRoute from "./util/AuthRoute";
@ -22,21 +22,20 @@ import AuthRoute from "./util/AuthRoute";
// axios.defaults.baseURL = 'http://localhost:5006/twistter-e4649/us-central1/api'; // axios.defaults.baseURL = 'http://localhost:5006/twistter-e4649/us-central1/api';
// Pages // Pages
import home from './pages/Home'; import home from "./pages/Home";
import signup from './pages/Signup'; import signup from "./pages/Signup";
import login from './pages/Login'; import login from "./pages/Login";
import user from './pages/user'; import user from "./pages/user";
import logout from './pages/Logout'; import logout from "./pages/Logout";
import Delete from './pages/Delete'; import Delete from "./pages/Delete";
import writeMicroblog from './Writing_Microblogs.js'; import writeMicroblog from "./Writing_Microblogs.js";
import editProfile from './pages/editProfile'; import editProfile from "./pages/editProfile";
import userLine from './Userline.js'; import userLine from "./Userline.js";
const theme = createMuiTheme(themeObject); const theme = createMuiTheme(themeObject);
const token = localStorage.FBIdToken; const token = localStorage.FBIdToken;
if (token) { if (token) {
try { try {
const decodedToken = jwtDecode(token); const decodedToken = jwtDecode(token);
if (decodedToken.exp * 1000 < Date.now()) { if (decodedToken.exp * 1000 < Date.now()) {
@ -44,7 +43,7 @@ if (token) {
window.location.href = "/login"; window.location.href = "/login";
} else { } else {
store.dispatch({ type: SET_AUTHENTICATED }); store.dispatch({ type: SET_AUTHENTICATED });
axios.defaults.headers.common['Authorization'] = token; axios.defaults.headers.common["Authorization"] = token;
store.dispatch(getUserData()); store.dispatch(getUserData());
} }
} catch (invalidTokenError) { } catch (invalidTokenError) {
@ -53,18 +52,19 @@ if (token) {
} }
} }
class App extends Component { class App extends Component {
render() { render() {
return ( return (
<MuiThemeProvider theme={theme}> <MuiThemeProvider theme={theme}>
<Provider store={store}> <Provider store={store}>
<Router> <Router>
<div className='container' > <div className="container">
<Navbar /> <Navbar />
</div> </div>
<div className="app"> <div className="app">
<Switch> <Switch>
{/* AuthRoute checks if the user is logged in and if they are it redirects them to /home */}
<AuthRoute exact path="/signup" component={signup} /> <AuthRoute exact path="/signup" component={signup} />
<AuthRoute exact path="/login" component={login} /> <AuthRoute exact path="/login" component={login} />
<AuthRoute exact path="/" component={home}/> <AuthRoute exact path="/" component={home}/>

View File

@ -1,94 +1,118 @@
import React, { Component } from "react"; import React, { Component } from "react";
import { BrowserRouter as Router } from 'react-router-dom'; import { BrowserRouter as Router } from "react-router-dom";
import Route from 'react-router-dom/Route'; import Route from "react-router-dom/Route";
import axios from 'axios'; import axios from "axios";
class Writing_Microblogs extends Component { class Writing_Microblogs extends Component {
constructor(props) { constructor(props) {
super(props); super(props);
this.state = { this.state = {
value: '', value: "",
title: '', title: "",
topics: '', topics: "",
characterCount: 250 characterCount: 250
}; };
this.handleChange = this.handleChange.bind(this); this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this); this.handleSubmit = this.handleSubmit.bind(this);
this.handleChangeforPost = this.handleChangeforPost.bind(this); this.handleChangeforPost = this.handleChangeforPost.bind(this);
this.handleChangeforTopics = this.handleChangeforTopics.bind(this); this.handleChangeforTopics = this.handleChangeforTopics.bind(this);
} }
handleChange(event) { handleChange(event) {
this.setState( {title: event.target.value }); this.setState({ title: event.target.value });
} }
handleChangeforTopics(event) { handleChangeforTopics(event) {
this.setState( {topics: event.target.value}); this.setState({ topics: event.target.value });
} }
handleSubmit(event) { handleSubmit(event) {
// alert('A title for the microblog was inputted: ' + this.state.title + '\nA microblog was posted: ' + this.state.value);
const postData = { const postData = {
body: this.state.value, body: this.state.value,
userImage: "bing-url", userImage: "bing-url",
microBlogTitle: this.state.title, microBlogTitle: this.state.title,
microBlogTopics: this.state.topics.split(', ') microBlogTopics: this.state.topics.split(", ")
} };
const headers = { const headers = {
headers: { 'Content-Type': 'application/json'} headers: { "Content-Type": "application/json" }
} };
axios axios
.post("/putPost", postData, headers) .post("/putPost", postData, headers)
.then((res) =>{ .then(res => {
alert('Post was shared successfully!') alert("Post was shared successfully!");
console.log(res.data); console.log(res.data);
}) })
.catch((err) => { .catch(err => {
alert('An error occured.'); alert("An error occured.");
console.error(err); console.error(err);
}) });
event.preventDefault(); event.preventDefault();
this.setState({value: '', title: '',characterCount: 250, topics: ''}) this.setState({ value: "", title: "", characterCount: 250, topics: "" });
} }
handleChangeforPost(event) { handleChangeforPost(event) {
this.setState({value: event.target.value }) this.setState({ value: event.target.value });
} }
handleChangeforCharacterCount(event) { handleChangeforCharacterCount(event) {
const charCount = event.target.value.length const charCount = event.target.value.length;
const charRemaining = 250 - charCount const charRemaining = 250 - charCount;
this.setState({characterCount: charRemaining }) this.setState({ characterCount: charRemaining });
} }
render() { render() {
return ( return (
<div> <div>
<div style={{ width: "200px", height: "50px", marginTop: "180px", marginLeft: "50px" }}> <div
style={{
width: "200px",
height: "50px",
marginTop: "180px",
marginLeft: "50px"
}}
>
<form> <form>
<textarea placeholder="Enter Microblog Title" value={this.state.title} required onChange={this.handleChange} cols={30} rows={1} /> <textarea
placeholder="Enter Microblog Title"
value={this.state.title}
required
onChange={this.handleChange}
cols={30}
rows={1}
/>
</form> </form>
</div> </div>
<div style={{ width: "200px", height: "50px", marginLeft: "50px"}} > <div style={{ width: "200px", height: "50px", marginLeft: "50px" }}>
<form> <form>
<textarea placeholder="Enter topics seperated by a comma" value={this.state.topics} required onChange={this.handleChangeforTopics} cols={40} rows={1} /> <textarea
placeholder="Enter topics seperated by a comma"
value={this.state.topics}
required
onChange={this.handleChangeforTopics}
cols={40}
rows={1}
/>
</form> </form>
</div> </div>
<div style={{ width: "200px", marginLeft: "50px"}}> <div style={{ width: "200px", marginLeft: "50px" }}>
<form onSubmit={this.handleSubmit}> <form onSubmit={this.handleSubmit}>
<textarea value={this.state.value} required maxLength="250" placeholder= "Write Microblog here..." <textarea
onChange = { (e) => { this.handleChangeforPost(e); this.handleChangeforCharacterCount(e) } } cols={40} rows={20} /> value={this.state.value}
<div style={{ fontSize: "14px", marginRight: "-100px"}} > required
maxLength="250"
placeholder="Write Microblog here..."
onChange={e => {
this.handleChangeforPost(e);
this.handleChangeforCharacterCount(e);
}}
cols={40}
rows={20}
/>
<div style={{ fontSize: "14px", marginRight: "-100px" }}>
<p2>Characters Left: {this.state.characterCount}</p2> <p2>Characters Left: {this.state.characterCount}</p2>
</div> </div>
<div style={{ marginRight: "-100px" }}> <div style={{ marginRight: "-100px" }}>
@ -97,11 +121,8 @@ class Writing_Microblogs extends Component {
</form> </form>
</div> </div>
</div> </div>
); );
} }
} }
export default Writing_Microblogs; export default Writing_Microblogs;

View File

@ -3,28 +3,29 @@ import React, { Component } from 'react';
import PropTypes from 'prop-types'; import PropTypes from 'prop-types';
import { connect } from 'react-redux'; import { connect } from 'react-redux';
import axios from 'axios'; import axios from 'axios';
//import '../App.css';
// Material UI and React Router // Material UI and React Router
import { makeStyles, styled } from "@material-ui/core/styles";
import { Link } from 'react-router-dom'; import { Link } from 'react-router-dom';
import { makeStyles, styled } from '@material-ui/core/styles'; import Card from "@material-ui/core/Card";
import Grid from '@material-ui/core/Grid';
import Card from '@material-ui/core/Card';
import CardMedia from '@material-ui/core/CardMedia'; import CardMedia from '@material-ui/core/CardMedia';
import CardContent from '@material-ui/core/CardContent'; import CardContent from '@material-ui/core/CardContent';
import Chip from '@material-ui/core/Chip';
import Button from '@material-ui/core/Button'; import Button from '@material-ui/core/Button';
import Grid from "@material-ui/core/Grid";
import Chip from "@material-ui/core/Chip";
import Typography from "@material-ui/core/Typography"; import Typography from "@material-ui/core/Typography";
import AddCircle from '@material-ui/icons/AddCircle'; import AddCircle from "@material-ui/icons/AddCircle";
import TextField from '@material-ui/core/TextField'; import TextField from "@material-ui/core/TextField";
// component // component
import '../App.css'; import '../App.css';
import noImage from '../images/no-img.png'; import noImage from '../images/no-img.png';
import Writing_Microblogs from '../Writing_Microblogs'; import Writing_Microblogs from '../Writing_Microblogs';
const MyChip = styled(Chip)({ const MyChip = styled(Chip)({
margin: 2, margin: 2,
color: 'primary' color: "primary"
}); });
class user extends Component { class user extends Component {
@ -35,26 +36,34 @@ class user extends Component {
newTopic: null newTopic: null
}; };
handleDelete = (topic) => { handleDelete = topic => {
alert(`Delete topic: ${topic}!`); axios
} .delete(`/deleteTopic/${topic.id}`)
.then(function() {
handleAddCircle = () => {
axios.post('/putTopic', {
topic: this.state.newTopic
})
.then(function () {
location.reload(); location.reload();
}) })
.catch(function (err) { .catch(function(err) {
console.log(err); console.log(err);
}); });
} };
handleAddCircle = () => {
axios
.post("/putTopic", {
topic: this.state.newTopic
})
.then(function() {
location.reload();
})
.catch(function(err) {
console.log(err);
});
};
handleChange(event) { handleChange(event) {
this.setState({ this.setState({
newTopic: event.target.value newTopic: event.target.value
}) });
} }
componentDidMount() { componentDidMount() {
@ -73,7 +82,7 @@ class user extends Component {
.then(res => { .then(res => {
this.setState({ this.setState({
topics: res.data topics: res.data
}) });
}) })
.catch(err => console.log(err)); .catch(err => console.log(err));
@ -95,13 +104,19 @@ class user extends Component {
<p> <p>
<Typography variant='h5'>{this.state.profile}</Typography> <Typography variant='h5'>{this.state.profile}</Typography>
</p>) : (<p>loading username...</p>); </p>) : (<p>loading username...</p>);
let topicsMarkup = this.state.topics ? ( let topicsMarkup = this.state.topics ? (
this.state.topics.map(topic => <MyChip this.state.topics.map(
label={{topic}.topic.topic} topic => (
key={{topic}.topic.topicId} <MyChip
onDelete={ (topic) => this.handleDelete(topic)}/>) label={{ topic }.topic.topic}
) : (<p> loading topics...</p>); key={{ topic }.topic.id}
onDelete={key => this.handleDelete(topic)}
/>
) // console.log({ topic }.topic.id)
)
) : (
<p> loading topics...</p>
);
let imageMarkup = this.state.imageUrl ? (<img src={this.state.imageUrl} height="150" width="150" />) : let imageMarkup = this.state.imageUrl ? (<img src={this.state.imageUrl} height="150" width="150" />) :
(<img src={noImage} height="150" width="150"/>); (<img src={noImage} height="150" width="150"/>);
@ -159,6 +174,7 @@ class user extends Component {
<Grid item sm={4} xs={8}> <Grid item sm={4} xs={8}>
<Writing_Microblogs /> <Writing_Microblogs />
</Grid> </Grid>
      
</Grid> </Grid>
); );
} }