Compare commits

...

17 Commits

Author SHA1 Message Date
shobhitm23
d3bfd8b5f3 Fixing UI 2019-11-01 15:36:22 -04:00
DreamCoder23
16567e2373 Merge pull request #63 from ClaytonWWilson/auth-backend-3
Auth backend 3
2019-10-29 14:40:02 -04:00
Aaron Sun
d3a77afe43 Pulled and merged the latest code from master 2019-10-29 14:02:56 -04:00
Aaron Sun
42b73632c0 Delete user's posts fully works now 2019-10-29 10:34:09 -04:00
Aaron Sun
c482f56762 Invalid credential message displays after non-exisitng email is passed in 2019-10-28 20:14:38 -04:00
Aaron Sun
9525ff7d0a Delete post works in Postman but not in actual database 2019-10-28 17:57:03 -04:00
Shobhit Makhija
f602b8251f Merge pull request #61 from ClaytonWWilson/filteredPosts
Arrow-callback warning
2019-10-28 01:34:43 -04:00
shobhitm23
70a12dcca4 Arrow-callback warning 2019-10-28 00:21:29 -04:00
Aaron Sun
657277bcad Username and user id now show in post data 2019-10-27 23:11:24 -04:00
Aaron Sun
d69828ef7f Merge branch 'master' of https://github.com/ClaytonWWilson/CS307-Team24 into auth-backend-3 2019-10-27 20:48:15 -04:00
Aaron Sun
5fa4caf0a3 Log in with username fully works now 2019-10-27 17:47:04 -04:00
Aaron Sun
fd226b454e Delete users fully works now 2019-10-27 14:46:31 -04:00
Leon Liang
0bbc453d54 Merge pull request #55 from ClaytonWWilson/delete_topic
Delete topic
2019-10-27 00:10:56 -04:00
Leon Liang
e236ceeb4b Merge branch 'master' into delete_topic 2019-10-27 00:10:38 -04:00
Leon Liang
1c81ae1663 show user's profile image 2019-10-27 00:09:17 -04:00
Leon Liang
c356dd18fa added UI allowing topic creation 2019-10-27 00:08:38 -04:00
Leon Liang
ec041732d9 reformat 2019-10-25 23:14:25 -04:00
11 changed files with 185 additions and 104 deletions

View File

@@ -1,18 +1,18 @@
/* 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');
exports.putPost = (req, res) => {
exports.putPost = (req, res) => {
const newPost = { const newPost = {
body: req.body.body, body: req.body.body,
userHandle: req.userData.handle, userHandle: req.user.handle,
userImage: req.body.userImage, userImage: req.body.userImage,
userID: req.userData.userId, userID: req.user.uid,
microBlogTitle: req.body.microBlogTitle, microBlogTitle: req.body.microBlogTitle,
createdAt: new Date().toISOString(), createdAt: new Date().toISOString(),
likeCount: 0, likeCount: 0,
commentCount: 0, commentCount: 0,
microBlogTopics: req.body.microBlogTopics microBlogTopics: req.body.microBlogTopics
}; };
admin.firestore().collection('posts').add(newPost) admin.firestore().collection('posts').add(newPost)
@@ -41,3 +41,7 @@ exports.getallPostsforUser = (req, res) => {
return res.status(500).json({error: 'Failed to fetch all posts written by specific user.'}) return res.status(500).json({error: 'Failed to fetch all posts written by specific user.'})
}) })
}; };
exports.getFilteredPosts = (req, res) => {
admin.firestore().collection('posts').where('userHandle', '==', 'new user').where('microBlogTopics', '==')
};

View File

@@ -34,7 +34,6 @@ exports.getAllTopics = (req, res) => {
}; };
exports.deleteTopic = (req, res) => { exports.deleteTopic = (req, res) => {
// TODO: handle add and delete by topic id
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) {

View File

@@ -7,8 +7,6 @@ const { validateUpdateProfileInfo } = require("../util/validator");
const firebase = require("firebase"); const firebase = require("firebase");
firebase.initializeApp(config); firebase.initializeApp(config);
var handle2Email = new Map();
exports.signup = (req, res) => { exports.signup = (req, res) => {
const newUser = { const newUser = {
email: req.body.email, email: req.body.email,
@@ -80,7 +78,6 @@ exports.signup = (req, res) => {
userId, userId,
followedTopics: [] followedTopics: []
}; };
handle2Email.set(userCred.handle, userCred.email);
return db.doc(`/users/${newUser.handle}`).set(userCred); return db.doc(`/users/${newUser.handle}`).set(userCred);
}) })
.then(() => { .then(() => {
@@ -98,7 +95,6 @@ exports.signup = (req, res) => {
exports.login = (req, res) => { exports.login = (req, res) => {
const user = { const user = {
email: req.body.email, email: req.body.email,
handle: req.body.handle,
password: req.body.password password: req.body.password
}; };
@@ -107,25 +103,63 @@ 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,}))$/; 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() === "") { if (user.email.trim() === "") {
errors.email = "Email must not be blank."; 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() === "") { if (user.password.trim() === "") {
errors.password = "Password must not be blank."; 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) { if (Object.keys(errors).length > 0) {
return res.status(400).json(errors); return res.status(400).json(errors);
} }
firebase // 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() .auth()
.signInWithEmailAndPassword(user.email, user.password) .signInWithEmailAndPassword(user.email, user.password)
.then((data) => { .then((data) => {
@@ -136,49 +170,65 @@ exports.login = (req, res) => {
}) })
.catch((err) => { .catch((err) => {
console.error(err); console.error(err);
if (err.code === "auth/wrong-password" || err.code === "auth/invalid-email" || err.code === "auth/user-not-found") { if (err.code === "auth/user-not-found" || err.code === "auth/invalid-email" || err.code === "auth/wrong-password") {
return res return res
.status(403) .status(403)
.json({ general: "Invalid credentials. Please try again." }); .json({ general: "Invalid credentials. Please try again." });
} }
return res.status(500).json({ error: err.code }); return res.status(500).json({ error: err.code });
}); });
}
}; };
//Deletes user account //Deletes user account
exports.deleteUser = (req, res) => { exports.deleteUser = (req, res) => {
var currentUser; var currentUser;
firebase.auth().onAuthStateChanged(function(user) { firebase.auth().onAuthStateChanged(function(user) {
currentUser = user; currentUser = user;
if (currentUser) { if (currentUser) {
/*db.collection("users").doc(`${currentUser.handle}`).delete() 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;
})
.then(function() { .then(function() {
res.status(200).send("Removed user from database."); 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);
});
db.collection("users").doc(`${req.user.handle}`).delete()
.then(function() {
res.status(200).send("Sucessfully removed user from database.");
return; return;
}) })
.catch(function(err) { .catch(function(err) {
res.status(500).send("Failed to remove user from database.", 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() currentUser.delete()
.then(function() { .then(function() {
console.log("User successfully deleted."); console.log("Successfully deleted user.");
res.status(200).send("Deleted user."); res.status(200).send("Sucessfully deleted user.");
return; return;
}) })
.catch(function(err) { .catch(function(err) {
console.log("Error deleting user.", err); console.log("Failed to delete user.", err);
res.status(500).send("Failed to delete user."); res.status(500).send("Failed to delete user.");
}); });
} }
else { else {
console.log("Cannot get user."); console.log("Failed to deleter user or cannot get user.");
res.status(500).send("Cannot get user."); res.status(500).send("Failed to deleter user or cannot get user.");
} }
}); });
}; };
@@ -199,8 +249,6 @@ exports.getProfileInfo = (req, res) => {
// Updates the data in the database of the user who is currently logged in // Updates the data in the database of the user who is currently logged in
exports.updateProfileInfo = (req, res) => { exports.updateProfileInfo = (req, res) => {
// TODO: Add functionality for adding/updating profile images
// Data validation // Data validation
const { valid, errors, profileData } = validateUpdateProfileInfo(req); const { valid, errors, profileData } = validateUpdateProfileInfo(req);
if (!valid) return res.status(400).json(errors); if (!valid) return res.status(400).json(errors);

View File

@@ -29,7 +29,7 @@ app.post("/signup", signup);
app.post("/login", login); app.post("/login", login);
//Deletes user account //Deletes user account
app.delete("/delete", deleteUser); app.delete("/delete", fbAuth, deleteUser);
app.get("/getUser", fbAuth, getUserDetails); app.get("/getUser", fbAuth, getUserDetails);

View File

@@ -36,6 +36,7 @@ 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()) {
@@ -74,7 +75,6 @@ class App extends Component {
<Route exact path="/user" component={user} /> <Route exact path="/user" component={user} />
<Route exact path="/home" component={writeMicroblog} /> <Route exact path="/home" component={writeMicroblog} />
<Route exact path="/edit" component={editProfile} /> <Route exact path="/edit" component={editProfile} />
{/* <Route exact path="/user" component={userLine} /> */}
<AuthRoute exact path="/" component={home}/> <AuthRoute exact path="/" component={home}/>
</Switch> </Switch>

View File

@@ -5,7 +5,7 @@ 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 = {
@@ -15,13 +15,13 @@ class Writing_Microblogs extends Component {
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) {
@@ -33,7 +33,7 @@ class Writing_Microblogs extends Component {
} }
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",
@@ -101,7 +101,7 @@ class Writing_Microblogs extends Component {
); );
} }
} }
export default Writing_Microblogs; export default Writing_Microblogs;

View File

@@ -31,13 +31,9 @@ const styles = {
position: "absolute" position: "absolute"
} }
}; };
export class Navbar extends Component { export class Navbar extends Component {
render() { render() {
const authenticated = this.props.user.authenticated; const authenticated = this.props.user.authenticated;
return ( return (
<AppBar> <AppBar>
@@ -54,11 +50,9 @@ const styles = {
{authenticated && <Button component={ Link } to='/logout'> {authenticated && <Button component={ Link } to='/logout'>
Logout Logout
</Button>} </Button>}
{/* Commented out the delete button, because it should probably go on {authenticated && <Button component={ Link } to='/delete'>
the profile or editProfile page instead of the NavBar */}
{/* <Button component={ Link } to='/delete'>
Delete Account Delete Account
</Button> */} </Button>}
</ToolBar> </ToolBar>
</AppBar> </AppBar>
) )

View File

@@ -7,7 +7,8 @@ import Button from "@material-ui/core/Button";
import withStyles from "@material-ui/core/styles/withStyles"; import withStyles from "@material-ui/core/styles/withStyles";
// Redux stuff // Redux stuff
import { logoutUser } from "../redux/actions/userActions"; //import { logoutUser } from "../redux/actions/userActions";
import { deleteUser } from "../redux/actions/userActions";
import { connect } from "react-redux"; import { connect } from "react-redux";
const styles = { const styles = {
@@ -32,7 +33,8 @@ const styles = {
export class Delete extends Component { export class Delete extends Component {
componentDidMount() { componentDidMount() {
this.props.logoutUser(); //this.props.logoutUser();
this.props.deleteUser();
this.props.history.push('/'); this.props.history.push('/');
} }
@@ -45,10 +47,12 @@ const mapStateToProps = (state) => ({
user: state.user user: state.user
}); });
const mapActionsToProps = { logoutUser }; //const mapActionsToProps = { logoutUser };
const mapActionsToProps = { deleteUser };
Delete.propTypes = { Delete.propTypes = {
logoutUser: PropTypes.func.isRequired, //logoutUser: PropTypes.func.isRequired,
deleteUser: PropTypes.func.isRequired,
user: PropTypes.object.isRequired, user: PropTypes.object.isRequired,
classes: PropTypes.object.isRequired classes: PropTypes.object.isRequired
}; };

View File

@@ -16,13 +16,15 @@ import withStyles from "@material-ui/core/styles/withStyles";
// Redux stuff // Redux stuff
import { connect } from 'react-redux'; import { connect } from 'react-redux';
import { loginUser } from '../redux/actions/userActions'; import { loginUser } from '../redux/actions/userActions';
import { fontFamily } from '@material-ui/system';
//Theme
const styles = { const styles = {
form: { form: {
textAlign: "center" textAlign: "center"
}, },
textField: { textField: {
marginBottom: 30 marginBottom: 20
}, },
pageTitle: { pageTitle: {
// marginTop: 20, // marginTop: 20,
@@ -34,6 +36,9 @@ const styles = {
}, },
progress: { progress: {
position: "absolute" position: "absolute"
},
p: {
fontFamily: "cursive",
} }
}; };
@@ -104,9 +109,12 @@ export class Login extends Component {
<Grid item sm /> <Grid item sm />
<Grid item sm> <Grid item sm>
<img src={logo} className="app-logo" alt="logo" /> <img src={logo} className="app-logo" alt="logo" />
<Typography variant="h2" className={classes.pageTitle}> <br></br>
Log in to Twistter <Typography variant="p" className={classes.pageTitle} fontFamily = "Georgia, serif">
<b>Log in to Twistter</b>
<br></br>
</Typography> </Typography>
<br></br>
<form noValidate onSubmit={this.handleSubmit}> <form noValidate onSubmit={this.handleSubmit}>
<TextField <TextField
id="email" id="email"

View File

@@ -16,13 +16,17 @@ import withStyles from "@material-ui/core/styles/withStyles";
// Redux stuff // Redux stuff
import { connect } from 'react-redux'; import { connect } from 'react-redux';
import { signupUser } from '../redux/actions/userActions'; import { signupUser } from '../redux/actions/userActions';
import { border } from '@material-ui/system';
const styles = { const styles = {
form: { form: {
textAlign: "center" textAlign: "center"
}, },
textField: { textField: {
marginBottom: 30 marginBottom: 20,
//border: "1px solid #234",
display: "inline-block",
boxSizing: "border-box",
}, },
pageTitle: { pageTitle: {
marginBottom: 40 marginBottom: 40
@@ -33,6 +37,14 @@ const styles = {
}, },
progress: { progress: {
position: "absolute" position: "absolute"
},
div: {
borderRadius: "5px",
backgroundColor: "grey",
padding: "20px",
},
p: {
fontFamily: "Segoe UI",
} }
}; };
@@ -92,9 +104,12 @@ export class Signup extends Component {
<Grid item sm /> <Grid item sm />
<Grid item sm> <Grid item sm>
<img src={logo} className="app-logo" alt="logo" /> <img src={logo} className="app-logo" alt="logo" />
<Typography variant="h2" className={classes.pageTitle}> <br></br>
Create a new account <Typography variant="p" className={classes.pageTitle}>
<b>Create a new account</b>
<br></br>
</Typography> </Typography>
<br></br>
<form noValidate onSubmit={this.handleSubmit}> <form noValidate onSubmit={this.handleSubmit}>
<TextField <TextField
id="handle" id="handle"
@@ -146,6 +161,8 @@ export class Signup extends Component {
onChange={this.handleChange} onChange={this.handleChange}
fullWidth fullWidth
/> />
<br></br>
<br></br>
<Button <Button
type="submit" type="submit"
variant="contained" variant="contained"

View File

@@ -6,66 +6,63 @@ import axios from 'axios';
import { makeStyles, styled } from '@material-ui/core/styles'; import { makeStyles, styled } from '@material-ui/core/styles';
import Grid from '@material-ui/core/Grid'; import Grid from '@material-ui/core/Grid';
import Card from '@material-ui/core/Card'; import Card from '@material-ui/core/Card';
import CardMedia from '@material-ui/core/CardMedia';
import CardContent from '@material-ui/core/CardContent';
import Chip from '@material-ui/core/Chip'; import Chip from '@material-ui/core/Chip';
import Paper from '@material-ui/core/Paper';
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';
// component // component
import Profile from '../components/profile/Profile';
import Userline from '../Userline'; import Userline from '../Userline';
import noImage from '../images/no-img.png'; import noImage from '../images/no-img.png';
const PostCard = styled(Card)({
background: 'linear-gradient(45deg, #1da1f2 90%)',
border: 3,
borderRadius: 3,
height:325,
width: 345,
padding: '0 30px',
});
const MyChip = styled(Chip)({ const MyChip = styled(Chip)({
margin: 2, margin: 2,
color: 'primary' color: 'primary'
}); });
const styles = (theme) => ({
...theme
});
const handleDelete = () => {
alert("Delete this topic!");
}
const handleAddCircle = () => {
alert("Add topic");
}
class user extends Component { class user extends Component {
state = { state = {
profile: null, profile: null,
topics: null imageUrl: null,
topics: null,
newTopic: null
}; };
handleDelete = (topic) => {
alert(`Delete topic: ${topic}!`);
}
handleAddCircle = () => {
axios.post('/putTopic', {
topic: this.state.newTopic
})
.then(function () {
location.reload();
})
.catch(function (err) {
console.log(err);
});
}
handleChange(event) {
this.setState({
newTopic: event.target.value
})
}
componentDidMount() { componentDidMount() {
axios axios
.get("/user") .get("/user")
.then(res => { .then(res => {
console.log(res.data.credentials.handle);
this.setState({ this.setState({
profile: res.data.credentials.handle profile: res.data.credentials.handle,
imageUrl: res.data.credentials.imageUrl
}); });
}) })
.catch(err => console.log(err)); .catch(err => console.log(err));
axios axios
.get("/getAllTopics") .get("/getAllTopics")
.then(res => { .then(res => {
console.log(res.data[1]);
this.setState({ this.setState({
topics: res.data topics: res.data
}) })
@@ -83,22 +80,40 @@ class user extends Component {
let topicsMarkup = this.state.topics ? ( let topicsMarkup = this.state.topics ? (
this.state.topics.map(topic => <MyChip this.state.topics.map(topic => <MyChip
label={{topic}.topic.topic} label={{topic}.topic.topic}
onDelete={handleDelete}/>) key={{topic}.topic.topicId}
onDelete={ (topic) => this.handleDelete(topic)}/>)
) : (<p> loading topics...</p>); ) : (<p> loading topics...</p>);
let imageMarkup = this.state.imageUrl ? (
<img
src={this.state.imageUrl}
height="250"
width="250"
/>
) : (<img src={noImage}/>);
return ( return (
<Grid container spacing={16}> <Grid container spacing={16}>
<Grid item sm={8} xs={12}> <Grid item sm={8} xs={12}>
<p>Post</p> <p>Post</p>
</Grid> </Grid>
<Grid item sm={4} xs={12}> <Grid item sm={4} xs={12}>
<img src={noImage}/> {imageMarkup}
{profileMarkup} {profileMarkup}
{topicsMarkup} {topicsMarkup}
<MyChip <TextField
icon={<AddCircle />} id="newTopic"
label="new topic"
defaultValue=""
margin="normal"
variant="outlined"
value={this.state.newTopic}
onChange={ (event) => this.handleChange(event)}
/>
<AddCircle
color="primary"
clickable clickable
onClick={handleAddCircle} onClick={this.handleAddCircle}
/> />
</Grid> </Grid>
</Grid> </Grid>
@@ -106,12 +121,4 @@ class user extends Component {
} }
} }
Userline.PropTypes = {
handle: PropTypes.object.isRequired
};
const mapStateToProps = (state) => ({
user: state.user
});
export default user; export default user;