Merge branch 'master' into edit-profile-image-upload

This commit is contained in:
Clayton Wilson 2019-12-04 00:02:03 -05:00 committed by GitHub
commit 7a0a5725b7
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
20 changed files with 2701 additions and 510 deletions

View File

@ -1,43 +1,355 @@
/* 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");
const { db } = require("../util/admin");
exports.putPost = (req, res) => { 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 = { admin
body: req.body.body, .firestore()
userHandle: req.userData.handle, .collection("posts")
userImage: req.body.userImage, .add(newPost)
userID: req.userData.userId, .then(doc => {
microBlogTitle: req.body.microBlogTitle, doc.update({ postId: doc.id });
createdAt: new Date().toISOString(), const resPost = newPost;
likeCount: 0, resPost.postId = doc.id;
commentCount: 0, return res.status(200).json(resPost);
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);
}) })
.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 went wrong" });
}); });
}; };
exports.getallPostsforUser = (req, res) => { exports.getallPostsforUser = (req, res) => {
admin.firestore().collection('posts').where('userHandle', '==', req.userData.handle ).get() var post_query = admin
.then((data) => { .firestore()
let posts = []; .collection("posts")
data.forEach(function(doc) { .where("userHandle", "==", req.user.handle);
posts.push(doc.data());
}); post_query
return res.status(200).json(posts); .get()
.then(function(myPosts) {
let posts = [];
myPosts.forEach(function(doc) {
posts.push(doc.data());
});
return res.status(200).json(posts);
}) })
.catch((err) => { .then(function() {
console.error(err); return res
return res.status(500).json({error: 'Failed to fetch all posts written by specific user.'}) .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", "==");
}; };

View File

@ -1,52 +1,93 @@
/* 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) => {
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 = { // add stuff
topic: req.body.topic userRef
}; .set({ followedTopics: new_following }, { merge: true })
.then(doc => {
admin.firestore().collection('topics').add(newTopic) return res
.then((doc) => { .status(201)
const resTopic = newTopic; .json({ message: `Following ${req.body.following}` });
newTopic.topicId = doc.id; })
return res.status(200).json(resTopic); .catch(err => {
return res.status(500).json({ err });
});
return res.status(200).json({ message: "OK" });
}) })
.catch((err) => { .catch(err => {
console.error(err); return res.status(500).json({ err });
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()
let topics = []; .collection("topics")
data.forEach(function(doc) { .get()
topics.push(doc.data()); .then(data => {
let topics = [];
data.forEach(function(doc) {
topics.push({
topic: doc.data().topic,
id: doc.id
}); });
return res.status(200).json(topics); });
}) return res.status(200).json(topics);
.catch((err) => {
console.error(err);
return res.status(500).json({error: 'Failed to fetch all topics.'})
}) })
.catch(err => {
console.error(err);
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}`); let new_following = [];
topic.get().then((doc) => { let userRef = db.doc(`/users/${req.userData.handle}`);
if (!doc.exists) { userRef
return res.status(404).json({error: 'Topic not found'}); .get()
} else { .then(doc => {
return topic.delete(); 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(() => { .catch(err => {
res.json({ message: 'Topic successfully deleted!'}); 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) => { .catch(err => {
console.error(err); return res.status(500).json({ err });
return res.status(500).json({error: 'Failed to delete topic.'}) });
}) };
}

View File

@ -8,8 +8,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,
@ -60,7 +58,7 @@ exports.signup = (req, res) => {
db.doc(`/users/${newUser.handle}`) db.doc(`/users/${newUser.handle}`)
.get() .get()
.then((doc) => { .then(doc => {
if (doc.exists) { if (doc.exists) {
return res return res
.status(400) .status(400)
@ -70,27 +68,29 @@ exports.signup = (req, res) => {
.auth() .auth()
.createUserWithEmailAndPassword(newUser.email, newUser.password); .createUserWithEmailAndPassword(newUser.email, newUser.password);
}) })
.then((data) => { .then(data => {
userId = data.user.uid; userId = data.user.uid;
return data.user.getIdToken(); return data.user.getIdToken();
}) })
.then((idToken) => { .then(idToken => {
token = idToken; token = idToken;
const defaultImageUrl = `https://firebasestorage.googleapis.com/v0/b/${config.storageBucket}/o/no-img.png?alt=media`;
const userCred = { const userCred = {
email: newUser.email, email: newUser.email,
handle: newUser.handle, handle: newUser.handle,
createdAt: newUser.createdAt, createdAt: newUser.createdAt,
imageUrl: `https://firebasestorage.googleapis.com/v0/b/${config.storageBucket}/o/${noImg}?alt=media`, imageUrl: `https://firebasestorage.googleapis.com/v0/b/${config.storageBucket}/o/${noImg}?alt=media`,
userId, userId,
followedTopics: [] followedTopics: [],
imageUrl: defaultImageUrl,
verified: false
}; };
handle2Email.set(userCred.handle, userCred.email);
return db.doc(`/users/${newUser.handle}`).set(userCred); return db.doc(`/users/${newUser.handle}`).set(userCred);
}) })
.then(() => { .then(() => {
return res.status(201).json({ token }); return res.status(201).json({ token });
}) })
.catch((err) => { .catch(err => {
console.error(err); console.error(err);
if (err.code === "auth/email-already-in-use") { if (err.code === "auth/email-already-in-use") {
return res.status(500).json({ email: "This email is already taken." }); return res.status(500).json({ email: "This email is already taken." });
@ -102,7 +102,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
}; };
@ -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,}))$/; 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
.auth() if (!user.email.match(emailRegEx)) {
.signInWithEmailAndPassword(user.email, user.password) var userDoc = db.collection("users").doc(`${user.email}`);
.then((data) => { userDoc
return data.user.getIdToken(); .get()
}) .then(function(doc) {
.then((token) => { if (doc.exists) {
return res.status(200).json({ token }); user.email = doc.data().email;
}) } else {
.catch((err) => { return res
console.error(err); .status(403)
if (err.code === "auth/wrong-password" || err.code === "auth/invalid-email" || err.code === "auth/user-not-found") { .json({ general: "Invalid credentials. Please try again." });
return res }
.status(403) return;
.json({ general: "Invalid credentials. Please try again." }); })
} .then(function() {
return res.status(500).json({ error: err.code }); 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) => { 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) { const userId = req.userData.userId;
currentUser = user; let errors = {};
if (currentUser) {
/*db.collection("users").doc(`${currentUser.handle}`).delete() function thenFunction(data) {
.then(function() { console.log(`${data} for ${req.userData.handle} has been deleted.`);
res.status(200).send("Removed user from database."); }
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; return;
}) })
.catch(function(err) { .catch((err) => {
res.status(500).send("Failed to remove user from database.", err); console.log(err);
});*/ reject(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.");
return; 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();
}); });
} return;
else { });
console.log("Cannot get user.");
res.status(500).send("Cannot get user."); 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 // 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") db.collection("users")
.doc(req.user.handle) .doc(req.user.handle)
.get() .get()
.then((data) => { .then(data => {
return res.status(200).json(data.data()); return res.status(200).json(data.data());
}) })
.catch((err) => { .catch(err => {
console.error(err); console.error(err);
return res.status(500).json(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 // 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);
@ -215,13 +423,11 @@ exports.updateProfileInfo = (req, res) => {
.set(profileData) .set(profileData)
.then(() => { .then(() => {
console.log(`${req.user.handle}'s profile info has been updated.`); console.log(`${req.user.handle}'s profile info has been updated.`);
return res return res.status(201).json({
.status(201) general: `${req.user.handle}'s profile info has been updated.`
.json({ });
general: `${req.user.handle}'s profile info has been updated.`
});
}) })
.catch((err) => { .catch(err => {
console.error(err); console.error(err);
return res.status(500).json({ return res.status(500).json({
error: "Error updating profile data" error: "Error updating profile data"
@ -233,37 +439,174 @@ exports.getUserDetails = (req, res) => {
let userData = {}; let userData = {};
db.doc(`/users/${req.body.handle}`) db.doc(`/users/${req.body.handle}`)
.get() .get()
.then((doc) => { .then(doc => {
if (doc.exists) { if (doc.exists) {
userData = doc.data(); userData = doc.data();
return res.status(200).json({userData}); return res.status(200).json({ userData });
} else { } else {
return res.status(400).json({error: "User not found."}) return res.status(400).json({ error: "User not found." });
}}) }
.catch((err) => { })
.catch(err => {
console.error(err); console.error(err);
return res.status(500).json({ error: err.code }); 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 // Returns all data stored for a user
exports.getAuthenticatedUser = (req, res) => { exports.getAuthenticatedUser = (req, res) => {
let credentials = {}; let credentials = {};
db.doc(`/users/${req.user.handle}`) db.doc(`/users/${req.user.handle}`)
.get() .get()
.then((doc) => { .then(doc => {
if (doc.exists) { if (doc.exists) {
credentials = doc.data(); credentials = doc.data();
return res.status(200).json({credentials}); return res.status(200).json({ credentials });
} else { } else {
return res.status(400).json({error: "User not found."}) return res.status(400).json({ error: "User not found." });
}}) }
.catch((err) => { })
.catch(err => {
console.error(err); console.error(err);
return res.status(500).json({ error: err.code }); 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 // Uploads a profile image
exports.uploadProfileImage = (req, res) => { exports.uploadProfileImage = (req, res) => {
const BusBoy = require("busboy"); const BusBoy = require("busboy");
@ -383,3 +726,31 @@ exports.uploadProfileImage = (req, res) => {
// }); // });
// busboy.end(req.rawBody); // 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" });
});
};

View File

@ -11,13 +11,20 @@ app.use(cors());
*------------------------------------------------------------------*/ *------------------------------------------------------------------*/
const { const {
getAuthenticatedUser, getAuthenticatedUser,
getAllHandles,
getUserDetails, getUserDetails,
getProfileInfo, getProfileInfo,
login, login,
signup, signup,
deleteUser, deleteUser,
updateProfileInfo, updateProfileInfo,
uploadProfileImage uploadProfileImage,
verifyUser,
unverifyUser,
getUserHandles,
addSubscription,
getSubs,
removeSub
} = require("./handlers/users"); } = require("./handlers/users");
// Adds a user to the database and registers them in firebase with // Adds a user to the database and registers them in firebase with
@ -30,9 +37,13 @@ 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.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 // Returns all profile data of the currently logged in user
app.get("/getProfileInfo", fbAuth, getProfileInfo); app.get("/getProfileInfo", fbAuth, getProfileInfo);
@ -47,24 +58,65 @@ app.get("/user", fbAuth, getAuthenticatedUser);
// Uploads a profile image // Uploads a profile image
app.post("/user/image", fbAuth, uploadProfileImage); 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 * * handlers/post.js *
*------------------------------------------------------------------*/ *------------------------------------------------------------------*/
const { getallPostsforUser, putPost const {
getallPostsforUser,
getallPosts,
putPost,
likePost,
unlikePost,
quoteWithPost,
quoteWithoutPost,
checkforLikePost,
getOtherUsersPosts
} = require("./handlers/post"); } = require("./handlers/post");
app.get("/getallPostsforUser", getallPostsforUser); app.get("/getallPostsforUser", fbAuth, getallPostsforUser);
app.get("/getallPosts", getallPosts);
// Adds one post to the database // Adds one post to the database
app.post("/putPost", fbAuth, putPost); 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 * * handlers/topic.js *
*------------------------------------------------------------------*/ *------------------------------------------------------------------*/
const { const {
putTopic, putTopic,
getAllTopics, getAllTopics,
deleteTopic deleteTopic,
getUserTopics
} = require("./handlers/topic"); } = require("./handlers/topic");
// add topic to database // add topic to database
@ -74,6 +126,9 @@ app.post("/putTopic", fbAuth, putTopic);
app.get("/getAllTopics", fbAuth, getAllTopics); app.get("/getAllTopics", fbAuth, getAllTopics);
// delete a specific topic // 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); exports.api = functions.https.onRequest(app);

View File

@ -10,11 +10,13 @@
"axios": "^0.19.0", "axios": "^0.19.0",
"clsx": "^1.0.4", "clsx": "^1.0.4",
"create-react-app": "^3.1.2", "create-react-app": "^3.1.2",
"fuse.js": "^3.4.6",
"install": "^0.13.0", "install": "^0.13.0",
"jwt-decode": "^2.2.0", "jwt-decode": "^2.2.0",
"node-pre-gyp": "^0.13.0", "node-pre-gyp": "^0.13.0",
"react": "^16.9.0", "react": "^16.9.0",
"react-dom": "^16.9.0", "react-dom": "^16.9.0",
"react-modal": "^3.11.1",
"react-redux": "^7.1.1", "react-redux": "^7.1.1",
"react-router-dom": "^5.1.0", "react-router-dom": "^5.1.0",
"react-scripts": "0.9.5", "react-scripts": "0.9.5",
@ -41,5 +43,5 @@
"last 1 safari version" "last 1 safari version"
] ]
}, },
"proxy": "https://us-central1-twistter-e4649.cloudfunctions.net/api" "proxy": "http://localhost:5001/twistter-e4649/us-central1/api"
} }

View File

@ -10,33 +10,33 @@ 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";
// 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";
import verify from "./pages/verify";
import Search from "./pages/Search.js";
import otherUser from "./pages/otherUser";
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 +44,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,34 +53,35 @@ 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 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} />
<Route exact path="/logout" component={logout} /> <AuthRoute exact path="/" component={home} />
<Route exact path="/delete" component={Delete} />
<Route exact path="/user" component={user} /> <Route exact path="/logout" component={logout} />
<Route exact path="/home" component={writeMicroblog} /> <Route exact path="/delete" component={Delete} />
<Route exact path="/edit" component={editProfile} />
{/* <Route exact path="/user" component={userLine} /> */}
<AuthRoute exact path="/" component={home}/> <Route exact path="/home" component={home} />
<Route exact path="/user" component={user} />
<Route exact path="/user/edit" component={editProfile} />
<Route exact path="/verify" component={verify} />
<Route exact path="/search" component={Search} />
<Route exact path="/user/:userhandle" component={otherUser} />
<AuthRoute exact path="/" component={home} />
</Switch> </Switch>
</div> </div>
</Router> </Router>
</Provider> </Provider>
</MuiThemeProvider> </MuiThemeProvider>

View File

@ -1,10 +1,10 @@
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';
import Box from '@material-ui/core/Box' import Box from '@material-ui/core/Box'
import {borders} from '@material-ui/system'; // import {borders} from '@material-ui/system';
import { sizing } from '@material-ui/system'; // import { sizing } from '@material-ui/system';
// var moment = require('moment'); // var moment = require('moment');
@ -41,7 +41,7 @@ class Userline extends Component {
<div style={{fontsize: "13px", textAlign: "left", marginLeft: "14px"}}> <div style={{fontsize: "13px", textAlign: "left", marginLeft: "14px"}}>
<p>Userline</p> <p>Userline</p>
</div> </div>
<Box border={1} width="25%" flex="1" height="auto" m={2} fontSize="13px" textAlign= "left" padding="5px" flexWrap= "wrap" flexDirection= "row" > <Box border={1} width="25%" flex="1" height="auto" m={2} fontSize="13px" textAlign="left" padding="5px" flexWrap="wrap" flexDirection="row" >
<div style={{flexWrap: "wrap", flex: "1", flexDirection: "row", wordBreak: "break-word"}}> <div style={{flexWrap: "wrap", flex: "1", flexDirection: "row", wordBreak: "break-word"}}>
<p> <p>
{sortedPosts.map((microBlog) => <p>Microblog Title: {microBlog.microBlogTitle} {sortedPosts.map((microBlog) => <p>Microblog Title: {microBlog.microBlogTitle}
@ -50,7 +50,7 @@ class Userline extends Component {
<br></br>Number of comments: {microBlog.commentCount} <br></br>Number of comments: {microBlog.commentCount}
<br></br>Number of likes: {microBlog.likeCount} <br></br>Number of likes: {microBlog.likeCount}
<br></br>Body of post: {microBlog.body} <br></br>Body of post: {microBlog.body}
<br></br>Tagged topics: {microBlog.microBlogTopics.join("," + " ")} <br></br>Tagged topics: {microBlog.microBlogTopics.join(", ")}
</p>)} </p>)}
</p> </p>
</div> </div>

View File

@ -1,107 +1,165 @@
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 {
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 (
<div>
<div style={{ width: "200px", height: "50px", marginTop: "180px", marginLeft: "50px" }}>
<form>
<textarea placeholder="Enter Microblog Title" value={this.state.title} required onChange={this.handleChange} cols={30} rows={1} />
</form>
</div>
<div style={{ width: "200px", height: "50px", marginLeft: "50px"}} >
<form>
<textarea placeholder="Enter topics seperated by a comma" value={this.state.topics} required onChange={this.handleChangeforTopics} cols={40} rows={1} />
</form>
</div>
<div style={{ width: "200px", marginLeft: "50px"}}>
<form onSubmit={this.handleSubmit}>
<textarea value={this.state.value} 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>
</div>
<div style={{ marginRight: "-100px" }}>
<button onClick>Share Post</button>
</div>
</form>
</div>
</div>
);
}
// Material-UI
import TextField from '@material-ui/core/TextField';
// import Typography from '@material-ui/core/Typography';
import Button from '@material-ui/core/Button';
import withStyles from "@material-ui/styles/withStyles";
const styles = {
container: {
position: "fixed"
},
form: {
width: "300px",
height: "50px",
marginTop: "180px",
marginLeft: "50px"
},
textField: {
marginBottom: 15
}
} }
export default Writing_Microblogs; 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) // TODO: add topics
.then(res => {
// alert("Post was shared successfully!");
console.log(res.data);
})
.catch(err => {
alert("An error occured.");
console.error(err);
});
console.log(postData.microBlogTopics);
postData.microBlogTopics.forEach(topic => {
axios
.post("/putTopic", {
following: topic
})
.then(res => {
console.log(res.data);
})
.catch(err => {
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() {
const { classes } = this.props;
return (
<div className={classes.container}>
<form noValidate className={classes.form}>
<TextField
id="title"
name="title"
label="Title"
className={classes.textField}
value={this.state.title}
variant="outlined"
onChange={this.handleChange}
fullWidth
autoComplete='off'
/>
<TextField
id="topics"
name="topics"
label="Topics"
className={classes.textField}
value={this.state.topics}
variant="outlined"
onChange={this.handleChangeforTopics}
color="primary"
fullWidth
autoComplete='off'
/>
<TextField
id="content"
name="content"
label="Content"
color="primary"
className={classes.textField}
value={this.state.value}
helperText={`${this.state.characterCount} characters left`}
multiline
rows="9"
variant="outlined"
inputProps={{
maxLength: 250
}}
onChange={(e) => {
this.handleChangeforPost(e);
this.handleChangeforCharacterCount(e);
}}
fullWidth
autoComplete='off'
/>
<Button
onClick={this.handleSubmit}
// disabled={loading}
variant="outlined"
color="primary"
>
Share Post
</Button>
</form>
</div>
);
}
}
export default withStyles(styles)(Writing_Microblogs);

View File

@ -1,81 +1,84 @@
/* eslint-disable */ /* eslint-disable */
import React, { Component } from 'react'; import React, { Component } from "react";
import { Link } from 'react-router-dom'; import { Link } from "react-router-dom";
import PropTypes from 'prop-types'; import PropTypes from "prop-types";
// Material UI stuff // Material UI stuff
import AppBar from '@material-ui/core/AppBar'; import AppBar from "@material-ui/core/AppBar";
import ToolBar from '@material-ui/core/Toolbar'; import ToolBar from "@material-ui/core/Toolbar";
import Button from '@material-ui/core/Button'; 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 { connect } from 'react-redux'; import { connect } from "react-redux";
const styles = { const styles = {
form: { form: {
textAlign: "center" textAlign: "center"
}, },
textField: { textField: {
marginBottom: 30 marginBottom: 30
}, },
pageTitle: { pageTitle: {
marginBottom: 40 marginBottom: 40
}, },
button: { button: {
positon: "relative", positon: "relative",
marginBottom: 30 marginBottom: 30
}, },
progress: { progress: {
position: "absolute" position: "absolute"
} }
}; };
export class Navbar extends Component {
render() {
const authenticated = this.props.user.authenticated;
return (
export class Navbar extends Component { <AppBar>
render() { <ToolBar>
const authenticated = this.props.user.authenticated; <Button component={Link} to="/">
return ( Home
<AppBar> </Button>
<ToolBar> {authenticated && (
<Button component={ Link } to='/'> <Button component={Link} to="/user">
Home Profile
</Button> </Button>
{!authenticated && <Button component={ Link } to='/login'> )}
Login {!authenticated && (
</Button>} <Button component={Link} to="/login">
{!authenticated && <Button component={ Link } to='/signup'> Login
Sign Up </Button>
</Button>} )}
{authenticated && <Button component={ Link } to='/logout'> {!authenticated && (
Logout <Button component={Link} to="/signup">
</Button>} Sign Up
{/* Commented out the delete button, because it should probably go on </Button>
the profile or editProfile page instead of the NavBar */} )}
{/* <Button component={ Link } to='/delete'> {authenticated && (
Delete Account <Button component={Link} to="/search">
</Button> */} Search
</ToolBar> </Button>
</AppBar> )}
) {authenticated && (
} <Button component={Link} to="/logout">
Logout
</Button>
)}
</ToolBar>
</AppBar>
);
}
} }
const mapStateToProps = (state) => ({ const mapStateToProps = state => ({
user: state.user user: state.user
}) });
// const mapActionsToProps = { logoutUser };
Navbar.propTypes = { Navbar.propTypes = {
user: PropTypes.object.isRequired, user: PropTypes.object.isRequired,
classes: PropTypes.object.isRequired classes: PropTypes.object.isRequired
} };
export default connect(mapStateToProps)(withStyles(styles)(Navbar)); export default connect(mapStateToProps)(withStyles(styles)(Navbar));
// export default Navbar;

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

@ -1,37 +1,358 @@
import React, { Component } from 'react'; /* eslint-disable */
import React, { Component } from "react";
import PropTypes from "prop-types";
import { connect } from "react-redux";
import axios from "axios";
// Material UI and React Router
import CircularProgress from '@material-ui/core/CircularProgress';
import Grid from "@material-ui/core/Grid";
import Card from "@material-ui/core/Card";
import CardContent from "@material-ui/core/CardContent";
import Typography from "@material-ui/core/Typography";
import withStyles from '@material-ui/styles/withStyles';
// component
import '../App.css'; import '../App.css';
import logo from '../images/twistter-logo.png'; import logo from '../images/twistter-logo.png';
import noImage from '../images/no-img.png';
import Writing_Microblogs from '../Writing_Microblogs';
import ReactModal from 'react-modal';
const styles = {
card: {
marginBottom: 5
}
}
class Home extends Component { class Home extends Component {
state = {
};
componentDidMount() {
axios
.get("/getallPosts")
.then(res => {
// console.log(res.data);
this.setState({
posts: res.data
});
})
.catch(err => console.log(err));
}
formatDate(dateString) {
let newDate = new Date(Date.parse(dateString));
return newDate.toDateString();
}
render() {
const { UI:{ loading } } = this.props;
let authenticated = this.props.user.authenticated;
let {classes} = this.props;
let username = this.props.user.credentials.handle;
let postMarkup = this.state.posts ? (
this.state.posts.map(post =>
<Card className={classes.card} key={post.postId}>
<CardContent>
<Typography>
{
this.state.imageUrl ? (<img src={this.state.imageUrl} height="50" width="50" />) :
(<img src={noImage} height="50" width="50"/>)
}
</Typography>
<Typography variant="h5"><b>{post.userHandle}</b></Typography>
<Typography variant="body2" color={"textSecondary"}>{this.formatDate(post.createdAt)}</Typography>
<br />
<Typography variant="body1"><b>{post.microBlogTitle}</b></Typography>
<Typography variant="body2">{post.quoteBody}</Typography>
<br />
<Typography variant="body2">{post.body}</Typography>
<br />
<Typography variant="body2"><b>Topics:</b> {post.microBlogTopics}</Typography>
<br />
{/* <Typography variant="body2" color={"textSecondary"}>Likes {post.likeCount}</Typography> */}
<Like microBlog = {post.postId} count = {post.likeCount} name = {username}></Like>
<Quote microblog = {post.postId}></Quote>
</CardContent>
</Card>
)
) : (
<p>Loading post...</p>
);
return (
authenticated ? (
<Grid container>
<Grid item sm={4} xs={8}>
<Writing_Microblogs />
</Grid>
<Grid item sm={4} xs={8}>
{postMarkup}
</Grid>
</Grid>
) : loading ?
(<CircularProgress size={60} style={{marginTop: "300px"}}></CircularProgress>)
:
(
<div>
<div>
<img src={logo} className="app-logo" alt="logo" />
<br/><br/>
<b>Welcome to Twistter!</b>
<br/><br/>
<b>See the most interesting topics people are following right now.</b>
</div>
<br/><br/><br/><br/>
<div>
<b>Join today or sign in if you already have an account.</b>
<br/><br/>
<form action="./signup">
<button className="authButtons signup">Sign up</button>
</form>
<br/>
<form action="./login">
<button className="authButtons login">Sign in</button>
</form>
</div>
</div>
));
}
}
class Quote extends Component {
constructor(props) {
super(props);
this.state = {
characterCount: 250,
showModal: false,
value: ""
}
this.handleSubmitWithoutPost = this.handleSubmitWithoutPost.bind(this);
this.handleOpenModal = this.handleOpenModal.bind(this);
this.handleCloseModal = this.handleCloseModal.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}
handleSubmitWithoutPost(event) {
const post = {
userImage: "bing-url",
}
const headers = {
headers: { "Content-Type": "application/json" }
};
axios.post(`/quoteWithoutPost/${this.props.microblog}`, post, headers)
.then((res) => {
console.log(res.data);
})
.catch(err => {
console.error(err);
});
event.preventDefault();
}
handleOpenModal() {
this.setState({ showModal: true });
}
handleCloseModal() {
this.setState({ showModal: false });
}
handleChangeforPost(event) {
this.setState({ value: event.target.value });
}
handleChangeforCharacterCount(event) {
const charCount = event.target.value.length;
const charRemaining = 250 - charCount;
this.setState({ characterCount: charRemaining });
}
handleSubmit(event) {
const quotedPost = {
quoteBody: this.state.value,
userImage: "bing-url",
};
const headers = {
headers: { "Content-Type": "application/json" }
};
axios.post(`/quoteWithPost/${this.props.microblog}`, quotedPost, headers)
.then((res) => {
console.log(res.data);
})
.catch(err => {
console.error(err);
});
event.preventDefault();
this.setState({ showModal: false, characterCount: 250, value: "" });
}
render() { render() {
return ( return (
<div> <div>
<div> <button onClick={this.handleOpenModal}>Quote with Post</button>
<img src={logo} className="app-logo" alt="logo" /> <ReactModal
<br/><br/> isOpen={this.state.showModal}
<b>Welcome to Twistter!</b> style={{content: {height: "50%", width: "25%", marginTop: "auto", marginLeft: "auto", marginRight: "auto", marginBottom : "auto"}}}
<br/><br/> >
<b>See the most interesting topics people are following right now.</b> <div style={{ width: "200px", marginLeft: "50px" }}>
</div> <form>
<textarea
value={this.state.value}
required
maxLength="250"
placeholder="Write Quoted Post 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>
</div>
<button onClick={this.handleSubmit}>Share Quoted Post</button>
<button onClick={this.handleCloseModal}>Cancel</button>
<br/><br/><br/><br/>
<div>
<b>Join today or sign in if you already have an account.</b>
<br/><br/>
<form action="./signup">
<button className="authButtons signup">Sign up</button>
</form>
<br/>
<form action="./login">
<button className="authButtons login">Sign in</button>
</form> </form>
</div> </div>
</ReactModal>
<button onClick={this.handleSubmitWithoutPost}>Quote without Post</button>
</div> </div>
); )
}
}
class Like extends Component {
constructor(props) {
super(props)
this.state = {
num : this.props.count,
} }
this.handleClick = this.handleClick.bind(this);
} }
export default Home; componentDidMount() {
this.setState({
like: localStorage.getItem(this.props.microBlog + this.props.name) === "false"
})
}
handleClick(){
this.setState({
like: !this.state.like
});
localStorage.setItem(this.props.microBlog + this.props.name, this.state.like.toString())
if(this.state.like == false)
{
this.setState(() => {
return {num: this.state.num + 1}
});
axios.get(`/like/${this.props.microBlog}`)
.then((res) => {
console.log(res.data);
})
.catch((err) => {
console.log(err);
})
}
else
{
this.setState(() => {
return {num: this.state.num - 1}
});
axios.get(`/unlike/${this.props.microBlog}`)
.then((res) => {
console.log(res.data);
})
.catch((err) => {
console.log(err);
})
}
}
/* componentDidMount() {
axios.get(`/checkforLikePost/${this.props.microBlog}`)
.then((res) => {
this.setState({
like2: res.data
})
console.log(res.data);
})
.catch((err) => {
console.log(err)
})
if (this.state.like2 === this.state.like)
{
this.setState({
like: false
})
}
} */
render() {
const label = this.state.like ? 'Unlike' : 'Like'
return(
<div>
<Typography variant="body2" color={"textSecondary"}>Likes {this.state.num}</Typography>
<button onClick={this.handleClick}>{label}</button>
</div>
)
}
}
const mapStateToProps = (state) => ({
user: state.user,
UI: state.UI
});
Home.propTypes = {
user: PropTypes.object.isRequired,
classes: PropTypes.object.isRequired,
UI: PropTypes.object.isRequired
}
Like.propTypes = {
user: PropTypes.object.isRequired
}
Quote.propTypes = {
user: PropTypes.object.isRequired
}
export default connect(mapStateToProps)(withStyles(styles)(Home, Like, Quote));

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,14 +109,17 @@ 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="h6" 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"
name="email" name="email"
label="Email*" label="Email or Username*"
className={classes.textField} className={classes.textField}
value={this.state.email} value={this.state.email}
helperText={errors.email} helperText={errors.email}
@ -119,6 +127,7 @@ export class Login extends Component {
variant="outlined" variant="outlined"
onChange={this.handleChange} onChange={this.handleChange}
fullWidth fullWidth
autoComplete='off'
/> />
<TextField <TextField
id="password" id="password"
@ -132,6 +141,7 @@ export class Login extends Component {
variant="outlined" variant="outlined"
onChange={this.handleChange} onChange={this.handleChange}
fullWidth fullWidth
autoComplete='off'
/> />
<Button <Button
type="submit" type="submit"

View File

@ -0,0 +1,129 @@
import React, { Component } from "react";
// import props
// import { TextField, Button } from "@material-ui/core";
import TextField from "@material-ui/core/TextField"
import Grid from "@material-ui/core/Grid";
import axios from "axios";
import Fuse from "fuse.js";
import { BrowserRouter as Router } from "react-router-dom";
import CircularProgress from "@material-ui/core/CircularProgress";
const fuseOptions = {
shouldSort: true,
threshold: 0.6,
location: 0,
distance: 100,
maxPatternLength: 32,
minMatchCharLength: 1,
keys: []
};
let fuse;
export class Search extends Component {
state = {
handles: [],
// searchPhrase: null,
searchResult: null,
loading: false
};
componentDidMount() {
this.setState({loading: true});
axios.get("/getAllHandles")
.then((res) => {
this.setState({
handles: res.data,
loading: false
}, () => {
// console.log(res.data);
fuse = new Fuse(this.state.handles, fuseOptions); // "list" is the item array
})
})
}
// handleSearch = () => {
// console.log(this.state.searchPhase);
// axios.post("/getUserHandles", {
// userHandle: this.state.searchPhase
// })
// .then(res => {
// console.log(res);
// this.setState({
// searchResult: res.data
// });
// })
// .catch(err => {
// console.log(err);
// });
// };
handleChange = (event) => {
let result = fuse.search(event.target.value);
let parsed = [];
result.forEach((res) => {
// console.log(res)
parsed.push(this.state.handles[res])
})
this.setState({
searchResult: parsed.length !== 0 ? parsed : "No Results"
})
}
handleRedirect() {
location.reload();
}
render() {
let resultMarkup = this.state.searchResult && this.state.searchResult !== "No Results" ? (
this.state.searchResult.map(res =>
<Router key={res}>
<div>
<a href={`/user/${res}`}>
{res}
</a>
</div>
</Router>
)
)
:
this.state.searchResult === "No Results" ?
(
<p> No results </p>
)
:
(
null
)
return (
this.state.loading
?
<CircularProgress size={60} style={{marginTop: "300px"}}></CircularProgress>
:
<Grid>
<Grid>
<TextField
id="standard-required"
label="Username"
margin="normal"
// value={this.state.searchPhrase}
onChange={this.handleChange}
/>
</Grid>
<Grid>
{/* <Button color="primary" onClick={this.handleSearch}>
Search
</Button> */}
</Grid>
<Grid>{resultMarkup}</Grid>
</Grid>
);
}
}
export default Search;

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"
@ -107,6 +122,7 @@ export class Signup extends Component {
variant="outlined" variant="outlined"
onChange={this.handleChange} onChange={this.handleChange}
fullWidth fullWidth
autoComplete='off'
/> />
<TextField <TextField
id="email" id="email"
@ -119,6 +135,7 @@ export class Signup extends Component {
variant="outlined" variant="outlined"
onChange={this.handleChange} onChange={this.handleChange}
fullWidth fullWidth
autoComplete='off'
/> />
<TextField <TextField
id="password" id="password"
@ -132,6 +149,7 @@ export class Signup extends Component {
variant="outlined" variant="outlined"
onChange={this.handleChange} onChange={this.handleChange}
fullWidth fullWidth
autoComplete='off'
/> />
<TextField <TextField
id="confirmPassword" id="confirmPassword"
@ -145,7 +163,10 @@ export class Signup extends Component {
variant="outlined" variant="outlined"
onChange={this.handleChange} onChange={this.handleChange}
fullWidth fullWidth
autoComplete='off'
/> />
<br></br>
<br></br>
<Button <Button
type="submit" type="submit"
variant="contained" variant="contained"

View File

@ -1,16 +1,17 @@
import React, { Component } from "react"; import React, { Component } from "react";
import { Link } from 'react-router-dom';
import axios from "axios"; import axios from "axios";
import PropTypes from "prop-types"; import PropTypes from "prop-types";
// TODO: Add a read-only '@' in the left side of the handle input
// TODO: Add a cancel button, that takes the user back to their profile page
import noImage from '../images/no-img.png'; import noImage from '../images/no-img.png';
// Material-UI stuff // Material-UI stuff
import Box from "@material-ui/core/Box"
import Button from "@material-ui/core/Button"; import Button from "@material-ui/core/Button";
import Box from "@material-ui/core/Box"; import Box from "@material-ui/core/Box";
import CircularProgress from "@material-ui/core/CircularProgress"; import CircularProgress from "@material-ui/core/CircularProgress";
import Grid from "@material-ui/core/Grid"; import Grid from "@material-ui/core/Grid";
import Popover from "@material-ui/core/Popover";
import TextField from "@material-ui/core/TextField"; import TextField from "@material-ui/core/TextField";
import Typography from "@material-ui/core/Typography"; import Typography from "@material-ui/core/Typography";
import withStyles from "@material-ui/core/styles/withStyles"; import withStyles from "@material-ui/core/styles/withStyles";
@ -40,6 +41,14 @@ const styles = {
box: { box: {
position: "relative" position: "relative"
}, },
back: {
float: "left",
marginLeft: 15
},
delete: {
float: "right",
marginRight: 15
},
progress: { progress: {
position: "absolute" position: "absolute"
}, },
@ -47,10 +56,18 @@ const styles = {
position: "absolute", position: "absolute",
marginLeft: -155, marginLeft: -155,
marginTop: 95 marginTop: 95
},
popoverBackground: {
marginTop: "-100px",
width: "calc(100vw)",
height: 'calc(100vh + 100px)',
backgroundColor: "gray",
position: "absolute",
opacity: "70%"
} }
}; };
export class edit extends Component { export class editProfile extends Component {
// mapReduxToState = (credentials) => { // mapReduxToState = (credentials) => {
// this.setState({ // this.setState({
// imageUrl: credentials.imageUrl ? credentials.imageUrl : noImage, // imageUrl: credentials.imageUrl ? credentials.imageUrl : noImage,
@ -62,8 +79,6 @@ export class edit extends Component {
// }); // });
// }; // };
// Runs as soon as the page loads. // Runs as soon as the page loads.
// Sets the default values of all the textboxes to the data // Sets the default values of all the textboxes to the data
// that is stored in the database for the user. // that is stored in the database for the user.
@ -71,6 +86,8 @@ export class edit extends Component {
// const { credentials } = this.props; // const { credentials } = this.props;
// console.log(this.props.user); // console.log(this.props.user);
// this.mapReduxToState(credentials); // this.mapReduxToState(credentials);
this.setState({pageLoading: true})
axios axios
.get("/getProfileInfo") .get("/getProfileInfo")
.then((res) => { .then((res) => {
@ -82,16 +99,15 @@ export class edit extends Component {
lastName: res.data.lastName ? res.data.lastName : "", lastName: res.data.lastName ? res.data.lastName : "",
email: res.data.email, email: res.data.email,
handle: res.data.handle, handle: res.data.handle,
bio: res.data.bio ? res.data.bio : "" bio: res.data.bio ? res.data.bio : "",
pageLoading: false
}); });
}) })
.catch((err) => { .catch((err) => {
console.error(err); console.error(err);
if (err.response.status === 403) { if (err.response.status === 403) {
alert("You are not logged in"); // This user is not logged in
// TODO: Redirect them, to the profile they are trying to edit this.props.history.push('/');
// If they are on /itsjimmy/edit, they will be redirected to /itsjimmy
this.props.history.push('../');
} }
}); });
} }
@ -106,7 +122,9 @@ export class edit extends Component {
email: "", email: "",
handle: "", handle: "",
bio: "", bio: "",
anchorEl: null,
loading: false, loading: false,
pageLoading: false,
errors: {} errors: {}
}; };
} }
@ -141,8 +159,7 @@ export class edit extends Component {
this.setState({ this.setState({
loading: false loading: false
}); });
// this.props.history.push('/'); this.props.history.push('/user');
// TODO: Need to redirect user to their profile page
}) })
.catch((err) => { .catch((err) => {
console.log(err); console.log(err);
@ -187,18 +204,26 @@ export class edit extends Component {
// this.mapReduxToState(this.props.credentials); // this.mapReduxToState(this.props.credentials);
// } // }
handleOpenConfirmDelete = (event) => {
this.setState({
// anchorEl: event.currentTarget
anchorEl: document.getElementById("container-grid")
});
};
handleCloseConfirmDelete = () => {
this.setState({
anchorEl: null,
createDMUsername: ''
});
};
render() { render() {
const { classes } = this.props; const { classes } = this.props;
const uploading = this.props.UI.loading; const uploading = this.props.UI.loading;
const { errors, loading } = this.state; const { errors, loading } = this.state;
// let imageMarkup = this.state.imageUrl ? ( // <<<<<<< edit-profile-image-upload
// <img
// src={this.state.imageUrl}
// height="250"
// width="250"
// />
// ) : (<img src={noImage}/>);
let imageMarkup = this.props.user.credentials.imageUrl ? ( let imageMarkup = this.props.user.credentials.imageUrl ? (
<Box <Box
@ -317,22 +342,199 @@ export class edit extends Component {
onChange={this.handleChange} onChange={this.handleChange}
fullWidth fullWidth
/> />
// =======
// Used for the delete button
const open = Boolean(this.state.anchorEl);
const id = open ? 'simple-popover' : undefined;
return (
this.state.pageLoading ?
<CircularProgress size={60} style={{marginTop: "300px"}}></CircularProgress>
:
<Grid container className={classes.form} id="container-grid">
<Grid item sm >
// >>>>>>> master
<Button <Button
type="submit" variant="outlined"
variant="contained"
color="primary" color="primary"
className={classes.button} // className={classes.button}
disabled={loading || uploading} disabled={loading || uploading}
className={classes.back}
component={ Link }
to='/user'
> >
Submit Back to Profile
{loading && (
<CircularProgress size={30} className={classes.progress} />
)}
</Button> </Button>
</form> </Grid>
<Grid item sm>
<Typography variant="h2" className={classes.pageTitle}>
Edit Profile
</Typography>
<form noValidate onSubmit={this.handleSubmit}>
<Grid container className={classes.form} spacing={4}>
<Grid item sm>
<TextField
id="firstName"
name="firstName"
label="First Name"
className={classes.textField}
value={this.state.firstName}
helperText={errors.firstName}
error={errors.firstName ? true : false}
variant="outlined"
onChange={this.handleChange}
fullWidth
autoComplete='off'
/>
</Grid>
<Grid item sm>
<TextField
id="lastName"
name="lastName"
label="Last Name"
className={classes.textField}
value={this.state.lastName}
helperText={errors.lastname}
error={errors.lastName ? true : false}
variant="outlined"
onChange={this.handleChange}
fullWidth
autoComplete='off'
/>
</Grid>
</Grid>
<TextField
id="email"
name="email"
label="Email*"
className={classes.textField}
value={this.state.email}
disabled
helperText="(disabled)"
// INFO: These will be uncommented if changing emails is allowed
// helperText={errors.email}
// error={errors.email ? true : false}
variant="outlined"
onChange={this.handleChange}
fullWidth
autoComplete='off'
/>
<TextField
id="handle"
name="handle"
label="Handle*"
className={classes.textField}
value={"@" + this.state.handle}
disabled
helperText="(disabled)"
// INFO: These will be uncommented if changing usernames is allowed
// helperText={errors.handle}
// error={errors.handle ? true : false}
variant="outlined"
onChange={this.handleChange}
fullWidth
autoComplete='off'
/>
<TextField
id="bio"
name="bio"
label="Bio"
className={classes.textField}
value={this.state.bio}
helperText={errors.bio}
error={errors.bio ? true : false}
multiline
rows="8"
variant="outlined"
onChange={this.handleChange}
fullWidth
autoComplete='off'
/>
<Button
type="submit"
variant="contained"
color="primary"
className={classes.button}
disabled={loading}
//component={ Link }
//to='/user'
>
Submit
{loading && (
<CircularProgress size={30} className={classes.progress} />
)}
</Button>
</form>
</Grid>
<Grid item sm>
<Button
variant="outlined"
color="secondary"
className={classes.delete}
onClick={this.handleOpenConfirmDelete}
>
Delete Account
</Button>
</Grid>
<Box hidden={!Boolean(this.state.anchorEl)} className={classes.popoverBackground}></Box>
<Popover
id={id}
open={open}
anchorEl={this.state.anchorEl}
onClose={this.handleCloseConfirmDelete}
anchorOrigin={{
vertical: 'center',
horizontal: 'center'
}}
transformOrigin={{
vertical: 'top',
horizontal: 'center'
}}
style={{
marginTop: "-200px"
}}
>
<Box
style={{
height: 200,
width: 400
}}
>
<Grid container direction="column" spacing={3}>
<Grid item>
<Typography style={{marginTop: 30, marginLeft: 50, marginRight: 50, textAlign: "center", fontSize: 24}}>Are you sure you want to delete your account?</Typography>
</Grid>
<Grid item>
<Button
color="secondary"
variant="contained"
component={ Link }
to='/delete'
style={{
marginBottom: "-40px",
marginLeft: 10,
width: 90
}}
>
Yes
</Button>
<Button
color="primary"
variant="outlined"
onClick={this.handleCloseConfirmDelete}
style={{
marginBottom: "-40px",
marginLeft: 195
}}
>
Cancel
</Button>
</Grid>
</Grid>
</Box>
</Popover>
</Grid> </Grid>
<Grid item sm />
</Grid>
); );
} }
} }
@ -351,4 +553,4 @@ edit.propTypes = {
}; };
// export default withStyles(styles)(edit); // export default withStyles(styles)(edit);
export default connect(mapStateToProps, mapActionsToProps)(withStyles(styles)(edit)); export default connect(mapStateToProps, mapActionsToProps)(withStyles(styles)(edit));

View File

@ -0,0 +1,283 @@
/* eslint-disable */
import React, { Component } from "react";
import PropTypes from "prop-types";
import { connect } from "react-redux";
import axios from "axios";
//import '../App.css';
// Material UI and React Router
import { makeStyles, styled } from "@material-ui/core/styles";
import withStyles from "@material-ui/core/styles/withStyles";
import { Link } from "react-router-dom";
import Card from "@material-ui/core/Card";
import CardMedia from "@material-ui/core/CardMedia";
import CardContent from "@material-ui/core/CardContent";
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 AddCircle from "@material-ui/icons/AddCircle";
import TextField from "@material-ui/core/TextField";
import VerifiedIcon from "@material-ui/icons/CheckSharp";
import DoneIcon from "@material-ui/icons/Done";
// component
import "../App.css";
import noImage from "../images/no-img.png";
import Writing_Microblogs from "../Writing_Microblogs";
const MyChip = styled(Chip)({
margin: 2,
color: "primary"
});
const styles = {
button: {
positon: "relative",
float: "left",
marginLeft: 30,
marginTop: 20
},
paper: {
// marginLeft: "10%",
// marginRight: "10%"
},
card: {
marginBottom: 5
},
profileImage: {
marginTop: 20
},
topicsContainer: {
border: "lightgray solid 1px",
marginTop: 20,
paddingTop: 10,
paddingBottom: 10,
height: 300
},
addCircle: {
width: 65,
height: 65,
marginTop: 10
},
username: {
marginBottom: 100
}
};
class user extends Component {
constructor() {
super();
this.state = {
profile: window.location.pathname.split("/").pop(),
imageUrl: null,
topics: null,
user: null,
following: null,
posts: null,
myTopics: null
};
}
handleSub = () => {
if (this.state.following === true) {
axios
.post("/removeSub", {
unfollow: this.state.profile
})
.then(res => {
console.log("removed sub");
this.setState({
following: false
});
})
.catch(function(err) {
console.log(err);
});
} else {
axios
.post("/addSubscription", {
following: this.state.profile
})
.then(res => {
console.log("adding sub");
this.setState({
following: true
});
})
.catch(function(err) {
console.log(err);
});
}
};
componentDidMount() {
axios
.post("/getUserDetails", {
handle: this.state.profile
})
.then(res => {
this.setState({
imageUrl: res.data.userData.imageUrl,
topics: res.data.userData.followedTopics
});
})
.catch(err => console.log(err));
axios
.get("/user")
.then(res => {
this.setState({
following: res.data.credentials.following.includes(
this.state.profile
),
myTopics: res.data.credentials.followedTopics
});
})
.catch(err => console.log(err));
axios
.post("/getOtherUsersPosts", {
handle: this.state.profile
})
.then(res => {
// console.log(res.data);
this.setState({
posts: res.data
});
})
.catch(err => console.log(err));
}
render() {
const { classes } = this.props;
let followMarkup = this.state.following ? (
<Button variant="contained" color="primary" onClick={this.handleSub}>
unfollow
</Button>
) : (
<Button variant="contained" color="primary" onClick={this.handleSub}>
follow
</Button>
);
let profileMarkup = this.state.profile ? (
<div>
<Typography variant="h5">
@{this.state.profile}{" "}
{this.state.verified ? (
<VerifiedIcon style={{ fill: "#1397D5" }} />
) : null}
</Typography>
{followMarkup}
</div>
) : (
<p>loading username...</p>
);
console.log(this.state.topics);
console.log(this.state.myTopics);
let topicsMarkup = this.state.topics ? (
this.state.topics.map(
topic =>
this.state.myTopics ? (
this.state.myTopics.includes(topic) ? (
<MyChip
label={topic}
key={{ topic }.topic.id}
onDelete
deleteIcon={<DoneIcon />}
/>
) : (
<MyChip
label={topic}
key={{ topic }.topic.id}
color="secondary"
/>
)
) : (
<p></p>
)
// topic => <MyChip label={topic} key={{ topic }.topic.id} /> // console.log({ topic }.topic.id)
)
) : (
<p> no topic yet</p>
);
let imageMarkup = this.state.imageUrl ? (
<img src={this.state.imageUrl} height="150" width="150" />
) : (
<img src={noImage} height="150" width="150" />
);
let postMarkup = this.state.posts ? (
this.state.posts.map(post => (
<Card className={classes.card}>
<CardContent>
<Typography>
{this.state.imageUrl ? (
<img src={this.state.imageUrl} height="50" width="50" />
) : (
<img src={noImage} height="50" width="50" />
)}
</Typography>
<Typography variant="h7">
<b>{post.userHandle}</b>
</Typography>
<Typography variant="body2" color={"textSecondary"}>
{post.createdAt}
</Typography>
<br />
<Typography variant="body1">
<b>{post.microBlogTitle}</b>
</Typography>
<Typography variant="body2">{post.quoteBody}</Typography>
<br />
<Typography variant="body2">{post.body}</Typography>
<br />
<Typography variant="body2">
<b>Topics:</b> {post.microBlogTopics}
</Typography>
<br />
<Typography variant="body2" color={"textSecondary"}>
Likes {post.likeCount}
</Typography>
</CardContent>
</Card>
))
) : (
<p>Posts</p>
);
return (
<Grid container spacing={24}>
<Grid item sm={4} xs={8}>
{imageMarkup}
{profileMarkup}
{/* {followMarkup} */}
{topicsMarkup}
<br />
</Grid>
<Grid item sm={4} xs={8}>
{postMarkup}
<br />
</Grid>
</Grid>
);
}
}
const mapStateToProps = state => ({
user: state.user
});
user.propTypes = {
user: PropTypes.object.isRequired,
classes: PropTypes.object.isRequired
};
export default connect(mapStateToProps)(withStyles(styles)(user));

View File

@ -1,53 +1,129 @@
/* eslint-disable */ /* eslint-disable */
import React, { Component } from 'react'; import React, { Component } from "react";
import PropTypes from 'prop-types'; import PropTypes from "prop-types";
import axios from 'axios'; import { connect } from "react-redux";
import axios from "axios";
//import '../App.css'; //import '../App.css';
import { makeStyles, styled } from '@material-ui/core/styles'; // Material-UI
import Grid from '@material-ui/core/Grid'; import withStyles from "@material-ui/core/styles/withStyles";
import Card from '@material-ui/core/Card'; import { makeStyles, styled } from "@material-ui/core/styles";
import Chip from '@material-ui/core/Chip'; import { Link } from "react-router-dom";
import Card from "@material-ui/core/Card";
import CardMedia from "@material-ui/core/CardMedia";
import CardContent from "@material-ui/core/CardContent";
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";
import VerifiedIcon from "@material-ui/icons/CheckSharp";
import Paper from "@material-ui/core/Paper";
import GridList from "@material-ui/core/GridList";
import GridListTile from "@material-ui/core/GridListTile";
import GridListTileBar from "@material-ui/core/GridListTileBar";
import Container from "@material-ui/core/Container";
// component // component
import Userline from '../Userline'; import "../App.css";
import noImage from '../images/no-img.png'; import noImage from "../images/no-img.png";
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 { const styles = {
state = { button: {
profile: null, positon: "relative",
imageUrl: null, float: "left",
topics: null, marginLeft: 30,
newTopic: null marginTop: 20
},
paper: {
// marginLeft: "10%",
// marginRight: "10%"
},
card: {
marginBottom: 5
},
profileImage: {
marginTop: 20
},
topicsContainer: {
border: "lightgray solid 1px",
marginTop: 20,
paddingTop: 10,
paddingBottom: 10,
height: 300
},
addCircle: {
width: 65,
height: 65,
marginTop: 10
},
username: {
marginBottom: 100
}
};
class user extends Component {
constructor() {
super();
this.state = {
profile: null,
imageUrl: null,
topics: null,
newTopic: ""
};
}
handleDelete = topic => {
console.log(topic);
axios
.post(`/deleteTopic`, {
unfollow: topic
})
.then(() => {
let tempTopics = this.state.topics;
tempTopics.forEach((oldTopic, index) => {
if (oldTopic === topic) {
tempTopics.splice(index, 1);
}
});
this.setState({
topics: tempTopics
});
})
.catch(function(err) {
console.log(err);
});
}; };
handleDelete = (topic) => {
alert(`Delete topic: ${topic}!`);
}
handleAddCircle = () => { handleAddCircle = () => {
axios.post('/putTopic', { axios
topic: this.state.newTopic .post("/putTopic", {
}) following: this.state.newTopic
.then(function () { })
location.reload(); .then(() => {
}) let tempTopics = this.state.topics;
.catch(function (err) { tempTopics.push(this.state.newTopic);
console.log(err); this.setState({
}); topics: tempTopics,
} newTopic: ""
});
})
.catch(function(err) {
console.log(err);
});
};
handleChange(event) { handleChange(event) {
this.setState({ this.setState({
newTopic: event.target.value newTopic: event.target.value
}) });
} }
componentDidMount() { componentDidMount() {
@ -56,69 +132,196 @@ class user extends Component {
.then(res => { .then(res => {
this.setState({ this.setState({
profile: res.data.credentials.handle, profile: res.data.credentials.handle,
imageUrl: res.data.credentials.imageUrl imageUrl: res.data.credentials.imageUrl,
verified: res.data.credentials.verified
? res.data.credentials.verified
: false,
topics: res.data.credentials.followedTopics
}); });
}) })
.catch(err => console.log(err)); .catch(err => console.log(err));
axios axios
.get("/getAllTopics") .get("/getallPostsforUser")
.then(res => { .then(res => {
// console.log(res.data);
this.setState({ this.setState({
topics: res.data posts: res.data
}) });
}) })
.catch(err => console.log(err)); .catch(err => console.log(err));
} }
formatDate(dateString) {
let newDate = new Date(Date.parse(dateString));
return newDate.toDateString();
}
render() { render() {
const classes = this.props; const { classes } = this.props;
let authenticated = this.props.user.authenticated;
let profileMarkup = this.state.profile ? ( let profileMarkup = this.state.profile ? (
<p> <div>
<Typography variant='h5'>{this.state.profile}</Typography> <Typography variant="h5" className={classes.username}>
</p>) : (<p>loading username...</p>); @{this.state.profile}{" "}
{this.state.verified ? (
<VerifiedIcon style={{ fill: "#1397D5" }} />
) : null}
</Typography>
</div>
) : (
<p className={classes.username}>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}
) : (<p> loading topics...</p>); key={topic}
onDelete={key => this.handleDelete(topic)}
/>
) // console.log({ topic }.topic.id)
)
) : (
<p> loading topics...</p>
);
let imageMarkup = this.state.imageUrl ? ( let imageMarkup = this.state.imageUrl ? (
<img <img
src={this.state.imageUrl} className={classes.profileImage}
height="250" src={this.state.imageUrl}
width="250" height="250"
width="250"
/> />
) : (<img src={noImage}/>); ) : (
<img
className={classes.profileImage}
src={noImage}
height="250"
width="250"
/>
);
let postMarkup = this.state.posts ? (
this.state.posts.map(post => (
<Card className={classes.card} key={post.postId}>
<CardContent>
<Typography>
{this.state.imageUrl ? (
<img src={this.state.imageUrl} height="50" width="50" />
) : (
<img src={noImage} height="50" width="50" />
)}
</Typography>
<Typography variant="h6">
<b>{post.userHandle}</b>
</Typography>
<Typography variant="body2" color={"textSecondary"}>
{post.createdAt}
</Typography>
<br />
<Typography variant="body1">
<b>{post.microBlogTitle}</b>
</Typography>
<Typography variant="body2">{post.quoteBody}</Typography>
<br />
<Typography variant="body2">{post.body}</Typography>
<br />
<Typography variant="body2">
<b>Topics:</b> {post.microBlogTopics}
</Typography>
<br />
<Typography variant="body2" color={"textSecondary"}>
Likes {post.likeCount}
</Typography>
</CardContent>
</Card>
))
) : (
<p>My Posts</p>
);
// FIX: This needs to check if user's profile page being displayed
// is the same as the user who is logged in
// Can't check for that right now, because this page is always
// showing the logged in users profile, instead of retreiving the
// profile based on the URL entered
let editButtonMarkup = true ? (
<Link to="/user/edit">
<Button className={classes.button} variant="outlined" color="primary">
Edit Profile
</Button>
</Link>
) : null;
return ( return (
<Grid container spacing={16}> <div>
<Grid item sm={8} xs={12}> {/* <Paper className={classes.paper}> */}
<p>Post</p> <Grid container direction="column">
<Grid item>
<Grid container>
<Grid item sm>
{editButtonMarkup}
</Grid>
<Grid item sm>
{/* <Grid container direction="column"> */}
{/* <Grid item sm> */}
{imageMarkup}
{profileMarkup}
{/* </Grid> */}
{/* <Grid item sm> */}
{/* {postMarkup} */}
{/* </Grid> */}
{/* </Grid> */}
</Grid>
<Grid item sm>
<Container className={classes.topicsContainer} maxWidth="xs">
{topicsMarkup}
</Container>
<TextField
id="newTopic"
label="new topic"
// defaultValue=""
margin="normal"
variant="outlined"
value={this.state.newTopic}
onChange={event => this.handleChange(event)}
/>
<AddCircle
className={classes.addCircle}
color="primary"
// iconStyle={classes.addCircle}
clickable="true"
onClick={this.handleAddCircle}
cursor="pointer"
/>
</Grid>
</Grid>
</Grid>
<Grid item>
<Grid container>
<Grid item sm />
<Grid item>{postMarkup}</Grid>
<Grid item sm />
</Grid>
</Grid>
</Grid> </Grid>
<Grid item sm={4} xs={12}> </div>
{imageMarkup}
{profileMarkup}
{topicsMarkup}
<TextField
id="newTopic"
label="new topic"
defaultValue=""
margin="normal"
variant="outlined"
value={this.state.newTopic}
onChange={ (event) => this.handleChange(event)}
/>
<AddCircle
color="primary"
clickable
onClick={this.handleAddCircle}
/>
</Grid>
</Grid>
); );
} }
} }
export default user; const mapStateToProps = state => ({
user: state.user
});
user.propTypes = {
user: PropTypes.object.isRequired,
classes: PropTypes.object.isRequired
};
export default connect(mapStateToProps)(withStyles(styles)(user));

View File

@ -0,0 +1,153 @@
import React, { Component } from "react";
import axios from "axios";
import PropTypes from "prop-types";
// TODO: Add a read-only '@' in the left side of the handle input
// TODO: Add a cancel button, that takes the user back to their profile page
// Material-UI stuff
import Button from "@material-ui/core/Button";
import { Link } from 'react-router-dom';
import CircularProgress from "@material-ui/core/CircularProgress";
import Grid from "@material-ui/core/Grid";
import TextField from "@material-ui/core/TextField";
import Typography from "@material-ui/core/Typography";
import withStyles from "@material-ui/core/styles/withStyles";
const styles = {
form: {
textAlign: "center"
},
textField: {
marginBottom: 30
},
pageTitle: {
// marginTop: 20,
marginBottom: 40
},
button: {
positon: "relative",
marginBottom: 10
},
progress: {
position: "absolute"
}
};
export class verify extends Component {
// Constructor for the state
constructor() {
super();
this.state = {
handle: "",
loading: false,
errors: {}
};
}
// // Runs whenever the submit button is clicked.
handleSubmit = (event) => {
event.preventDefault();
this.setState({
loading: true
});
const verifyHandle = {
user: this.state.handle
};
axios
.post("/verifyUser", verifyHandle)
.then((res) => {
console.log(res);
this.setState({
loading: false
});
// this.props.history.push('/');
// TODO: Need to redirect user to their profile page
})
.catch((err) => {
console.log(err);
this.setState({
errors: err.response.data,
loading: false
});
});
};
// Updates the state whenever one of the textboxes changes.
// The key is the name of the textbox and the value is the
// value in the text box.
// Also sets errors to null of textboxes that have been edited
handleChange = (event) => {
this.setState({
[event.target.name]: event.target.value,
errors: {
[event.target.name]: null
}
});
};
render() {
const { classes } = this.props;
const { loading } = this.state;
return (
<Grid container className={classes.form}>
<Grid item sm />
<Grid item sm>
<Typography variant="h4" className={classes.pageTitle}>
Verify Users
</Typography>
<form noValidate onSubmit={this.handleSubmit}>
<TextField
id="handle"
name="handle"
label="Username"
className={classes.textField}
value={this.state.handle}
// helperText={errors.handle}
// error={errors.handle ? true : false}
variant="outlined"
onChange={this.handleChange}
fullWidth
/>
<Grid container direction="column">
<Grid item>
<Button
type="submit"
variant="contained"
color="primary"
className={classes.button}
disabled={loading}
>
Submit
{loading && (
<CircularProgress size={30} className={classes.progress} />
)}
</Button>
</Grid>
<Grid item>
<Button
variant="oulined"
color="primary"
// className={classes.button}
component={ Link }
to='/user'
>
Back to Profile
</Button>
</Grid>
</Grid>
</form>
</Grid>
<Grid item sm />
</Grid>
);
}
}
verify.propTypes = {
classes: PropTypes.object.isRequired
};
export default withStyles(styles)(verify);

View File

@ -1,6 +1,20 @@
import {SET_USER, SET_ERRORS, CLEAR_ERRORS, LOADING_UI, SET_AUTHENTICATED, SET_UNAUTHENTICATED, LOADING_USER} from '../types'; import {
SET_USER,
SET_ERRORS,
CLEAR_ERRORS,
LOADING_UI,
// SET_AUTHENTICATED,
SET_UNAUTHENTICATED,
LOADING_USER
} from '../types';
import axios from 'axios'; import axios from 'axios';
const setAuthorizationHeader = (token) => {
const FBIdToken = `Bearer ${token}`;
localStorage.setItem('FBIdToken', FBIdToken);
axios.defaults.headers.common['Authorization'] = FBIdToken;
}
// Gets Database info for the logged in user and sets it in Redux // Gets Database info for the logged in user and sets it in Redux
export const getUserData = () => (dispatch) => { export const getUserData = () => (dispatch) => {
dispatch({ type: LOADING_USER }); dispatch({ type: LOADING_USER });
@ -24,7 +38,7 @@ export const loginUser = (loginData, history) => (dispatch) => {
// Save the login token // Save the login token
setAuthorizationHeader(res.data.token); setAuthorizationHeader(res.data.token);
dispatch(getUserData()); dispatch(getUserData());
dispatch({ type: CLEAR_ERRORS }) // dispatch({ type: CLEAR_ERRORS })
// Redirects to home page // Redirects to home page
history.push('/home'); history.push('/home');
}) })
@ -47,7 +61,7 @@ export const signupUser = (newUserData, history) => (dispatch) => {
// Save the signup token // Save the signup token
setAuthorizationHeader(res.data.token); setAuthorizationHeader(res.data.token);
dispatch(getUserData()); dispatch(getUserData());
dispatch({ type: CLEAR_ERRORS }) // dispatch({ type: CLEAR_ERRORS })
// Redirects to home page // Redirects to home page
history.push('/home'); history.push('/home');
}) })
@ -105,4 +119,4 @@ export const uploadImage = (formData) => (dispatch) => {
.catch(err => { .catch(err => {
console.log(err); console.log(err);
}) })
} }

View File

@ -1,4 +1,12 @@
import {SET_USER, SET_ERRORS, CLEAR_ERRORS, LOADING_UI, SET_AUTHENTICATED, SET_UNAUTHENTICATED, LOADING_USER} from '../types'; import {
SET_USER,
// SET_ERRORS,
// CLEAR_ERRORS,
// LOADING_UI,
SET_AUTHENTICATED,
SET_UNAUTHENTICATED,
LOADING_USER
} from '../types';
const initialState = { const initialState = {
authenticated: false, authenticated: false,