Pulled latest version from master and fixed all conflicts

This commit is contained in:
Aaron Sun
2019-11-24 17:08:13 -08:00
parent ad0b21e629
commit 1482830131
15 changed files with 1306 additions and 383 deletions

View File

@@ -1,3 +1,4 @@
/* eslint-disable prefer-arrow-callback */
/* eslint-disable promise/always-return */
const admin = require('firebase-admin');
@@ -16,6 +17,7 @@ exports.putPost = (req, res) => {
admin.firestore().collection('posts').add(newPost)
.then((doc) => {
doc.update({postId: doc.id})
const resPost = newPost;
resPost.postId = doc.id;
return res.status(200).json(resPost);
@@ -37,11 +39,11 @@ exports.getallPostsforUser = (req, res) => {
return res.status(200).json(posts);
})
.then(function() {
res.status(200).send("Successfully retrieved all user's posts from database.");
return;
res.status(200).send("Successfully retrieved all user's posts from database.");
return;
})
.catch(function(err) {
res.status(500).send("Failed to retrieve user's posts from database.", err);
res.status(500).send("Failed to retrieve user's posts from database.", err);
});
};
@@ -56,14 +58,18 @@ exports.getallPosts = (req, res) => {
return res.status(200).json(posts);
})
.then(function() {
res.status(200).send("Successfully retrieved every post from database.");
return;
res.status(200).send("Successfully retrieved every post from database.");
return;
})
.catch(function(err) {
res.status(500).send("Failed to retrieve posts from database.", err);
res.status(500).send("Failed to retrieve posts from database.", err);
});
};
exports.getFilteredPosts = (req, res) => {
admin.firestore().collection('posts').where('userHandle', '==', 'new user').where('microBlogTopics', '==')
};
exports.getFollowedPosts = (req, res) => {
var followers_list = admin.firestore().collection("users").doc(req.user.handle).collection("followedUsers");
var post_query = admin.firestore().collection("posts");
@@ -104,4 +110,4 @@ exports.getFollowedPosts = (req, res) => {
.catch(function(err) {
res.status(500).send("Failed to retrieve any posts.", err);
});
};
};

View File

@@ -1,52 +1,93 @@
/* eslint-disable promise/always-return */
const { admin, db } = require("../util/admin");
exports.putTopic = (req, res) => {
let new_following = [];
let userRef = db.doc(`/users/${req.userData.handle}`);
userRef
.get()
.then(doc => {
new_following = doc.data().followedTopics;
new_following.push(req.body.following);
const newTopic = {
topic: req.body.topic
};
admin.firestore().collection('topics').add(newTopic)
.then((doc) => {
const resTopic = newTopic;
newTopic.topicId = doc.id;
return res.status(200).json(resTopic);
// add stuff
userRef
.set({ followedTopics: new_following }, { merge: true })
.then(doc => {
return res
.status(201)
.json({ message: `Following ${req.body.following}` });
})
.catch(err => {
return res.status(500).json({ err });
});
return res.status(200).json({ message: "OK" });
})
.catch((err) => {
console.error(err);
return res.status(500).json({ error: 'something is wrong'});
.catch(err => {
return res.status(500).json({ err });
});
};
exports.getAllTopics = (req, res) => {
admin.firestore().collection('topics').get()
.then((data) => {
let topics = [];
data.forEach(function(doc) {
topics.push(doc.data());
admin
.firestore()
.collection("topics")
.get()
.then(data => {
let topics = [];
data.forEach(function(doc) {
topics.push({
topic: doc.data().topic,
id: doc.id
});
return res.status(200).json(topics);
})
.catch((err) => {
console.error(err);
return res.status(500).json({error: 'Failed to fetch all topics.'})
});
return res.status(200).json(topics);
})
.catch(err => {
console.error(err);
return res.status(500).json({ error: "Failed to fetch all topics." });
});
};
exports.deleteTopic = (req, res) => {
const topic = db.doc(`/topics/${req.params.topicId}`);
topic.get().then((doc) => {
if (!doc.exists) {
return res.status(404).json({error: 'Topic not found'});
} else {
return topic.delete();
let new_following = [];
let userRef = db.doc(`/users/${req.userData.handle}`);
userRef
.get()
.then(doc => {
new_following = doc.data().followedTopics;
// remove username from array
new_following.forEach(function(follower, index) {
if (follower === `${req.body.unfollow}`) {
new_following.splice(index, 1);
}
});
// update database
userRef
.set({ followedTopics: new_following }, { merge: true })
.then(doc => {
return res
.status(202)
.json({ message: `Successfully unfollow ${req.body.unfollow}` });
})
.catch(err => {
return res.status(500).json({ err });
});
return res.status(200).json({ message: "ok" });
})
.then(() => {
res.json({ message: 'Topic successfully deleted!'});
.catch(err => {
return res.status(500).json({ err });
});
};
exports.getUserTopics = (req, res) => {
let data = [];
db.doc(`/users/${req.body.handle}`)
.get()
.then(doc => {
data = doc.data().followedTopics;
return res.status(200).json({ data });
})
.catch((err) => {
console.error(err);
return res.status(500).json({error: 'Failed to delete topic.'})
})
}
.catch(err => {
return res.status(500).json({ err });
});
};

View File

@@ -54,7 +54,7 @@ exports.signup = (req, res) => {
db.doc(`/users/${newUser.handle}`)
.get()
.then((doc) => {
.then(doc => {
if (doc.exists) {
return res
.status(400)
@@ -64,25 +64,28 @@ exports.signup = (req, res) => {
.auth()
.createUserWithEmailAndPassword(newUser.email, newUser.password);
})
.then((data) => {
.then(data => {
userId = data.user.uid;
return data.user.getIdToken();
})
.then((idToken) => {
.then(idToken => {
token = idToken;
const defaultImageUrl = `https://firebasestorage.googleapis.com/v0/b/${config.storageBucket}/o/no-img.png?alt=media`;
const userCred = {
email: newUser.email,
handle: newUser.handle,
createdAt: newUser.createdAt,
userId,
followedTopics: []
followedTopics: [],
imageUrl: defaultImageUrl,
verified: false
};
return db.doc(`/users/${newUser.handle}`).set(userCred);
})
.then(() => {
return res.status(201).json({ token });
})
.catch((err) => {
.catch(err => {
console.error(err);
if (err.code === "auth/email-already-in-use") {
return res.status(500).json({ email: "This email is already taken." });
@@ -120,116 +123,156 @@ exports.login = (req, res) => {
// Email/username field is username since it's not in email format
if (!user.email.match(emailRegEx)) {
var userDoc = db.collection("users").doc(`${user.email}`);
userDoc.get()
.then(function(doc) {
userDoc
.get()
.then(function(doc) {
if (doc.exists) {
user.email = doc.data().email;
}
else {
return res.status(403).json({ general: "Invalid credentials. Please try again." });
} else {
return res
.status(403)
.json({ general: "Invalid credentials. Please try again." });
}
return;
})
.then(function() {
firebase
.auth()
.signInWithEmailAndPassword(user.email, user.password)
.then((data) => {
return data.user.getIdToken();
})
.then((token) => {
return res.status(200).json({ token });
.then(function() {
firebase
.auth()
.signInWithEmailAndPassword(user.email, user.password)
.then(data => {
return data.user.getIdToken();
})
.then(token => {
return res.status(200).json({ token });
})
.catch(err => {
console.error(err);
if (
err.code === "auth/user-not-found" ||
err.code === "auth/invalid-email" ||
err.code === "auth/wrong-password"
) {
return res
.status(403)
.json({ general: "Invalid credentials. Please try again." });
}
return res.status(500).json({ error: err.code });
});
return;
})
.catch((err) => {
console.error(err);
if (err.code === "auth/user-not-found" || err.code === "auth/invalid-email" || err.code === "auth/wrong-password") {
return res.status(403).json({ general: "Invalid credentials. Please try again." });
.catch(function(err) {
if (!doc.exists) {
return res
.status(403)
.json({ general: "Invalid credentials. Please try again." });
}
return res.status(500).json({ error: err.code });
return res.status(500).send(err);
});
return;
})
.catch(function(err) {
if(!doc.exists) {
return res.status(403).json({ general: "Invalid credentials. Please try again." });
}
return res.status(500).send(err);
});
}
// Email/username field is username
else {
firebase
.auth()
.signInWithEmailAndPassword(user.email, user.password)
.then((data) => {
return data.user.getIdToken();
})
.then((token) => {
return res.status(200).json({ token });
})
.catch((err) => {
console.error(err);
if (err.code === "auth/user-not-found" || err.code === "auth/invalid-email" || err.code === "auth/wrong-password") {
return res
.status(403)
.json({ general: "Invalid credentials. Please try again." });
}
return res.status(500).json({ error: err.code });
});
.auth()
.signInWithEmailAndPassword(user.email, user.password)
.then(data => {
return data.user.getIdToken();
})
.then(token => {
return res.status(200).json({ token });
})
.catch(err => {
console.error(err);
if (
err.code === "auth/user-not-found" ||
err.code === "auth/invalid-email" ||
err.code === "auth/wrong-password"
) {
return res
.status(403)
.json({ general: "Invalid credentials. Please try again." });
}
return res.status(500).json({ error: err.code });
});
}
};
//Deletes user account
//Deletes user account and all associated data
exports.deleteUser = (req, res) => {
var currentUser;
firebase.auth().onAuthStateChanged(function(user) {
currentUser = user;
if (currentUser) {
var post_query = db.collection("posts").where("userHandle", "==", req.user.handle);
post_query.get()
.then(function(myPosts) {
myPosts.forEach(function(doc) {
doc.ref.delete();
// Get the profile image filename
// `https://firebasestorage.googleapis.com/v0/b/${config.storageBucket}/o/${imageFileName}?alt=media`
let imageFileName;
req.userData.imageUrl
? (imageFileName = req.userData.imageUrl.split("/o/")[1].split("?alt=")[0])
: (imageFileName = "no-img.png");
const userId = req.userData.userId;
let errors = {};
function thenFunction(data) {
console.log(`${data} data for ${req.userData.handle} has been deleted.`);
}
function catchFunction(data, err) {
console.error(err);
errors[data] = err;
}
// Deletes user from authentication
let auth = admin.auth().deleteUser(userId);
// Deletes database data
let data = db
.collection("users")
.doc(`${req.user.handle}`)
.delete();
// Deletes any custom profile image
let image;
if (imageFileName !== "no-img.png") {
image = admin
.storage()
.bucket()
.file(imageFileName)
.delete();
} else {
image = Promise.resolve();
}
// Deletes all users posts
let posts = db
.collection("posts")
.where("userHandle", "==", req.user.handle)
.get()
.then(query => {
query.forEach(snap => {
snap.ref.delete();
});
return;
});
let promises = [
auth.then(thenFunction("auth")).catch(err => catchFunction("auth", err)),
data.then(thenFunction("data")).catch(err => catchFunction("data", err)),
image.then(thenFunction("image")).catch(err => catchFunction("image", err)),
posts.then(thenFunction("posts")).catch(err => catchFunction("image", err))
];
// Wait for all promises to resolve
let waitPromise = Promise.all(promises);
waitPromise
.then(() => {
if (Object.keys(errors) > 0) {
return res.status(500).json(errors);
} else {
return res.status(200).json({
message: `All data for ${req.userData.handle} has been deleted.`
});
return;
})
.then(function() {
res.status(200).send("Successfully removed all user's posts from database.");
return;
})
.catch(function(err) {
res.status(500).send("Failed to remove all user's posts from database.", err);
});
db.collection("users").doc(`${req.user.handle}`).delete()
.then(function() {
res.status(200).send("Sucessfully removed user from database.");
return;
})
.catch(function(err) {
res.status(500).send("Failed to remove user from database.", err);
});
currentUser.delete()
.then(function() {
console.log("Successfully deleted user.");
res.status(200).send("Sucessfully deleted user.");
return;
})
.catch(function(err) {
console.log("Failed to delete user.", err);
res.status(500).send("Failed to delete user.");
});
}
else {
console.log("Failed to deleter user or cannot get user.");
res.status(500).send("Failed to deleter user or cannot get user.");
}
});
}
})
.catch(err => {
return res.status(500).json({ error: err });
});
};
// Returns all data in the database for the user who is currently signed in
@@ -237,10 +280,10 @@ exports.getProfileInfo = (req, res) => {
db.collection("users")
.doc(req.user.handle)
.get()
.then((data) => {
.then(data => {
return res.status(200).json(data.data());
})
.catch((err) => {
.catch(err => {
console.error(err);
return res.status(500).json(err);
});
@@ -258,13 +301,11 @@ exports.updateProfileInfo = (req, res) => {
.set(profileData, { merge: true })
.then(() => {
console.log(`${req.user.handle}'s profile info has been updated.`);
return res
.status(201)
.json({
general: `${req.user.handle}'s profile info has been updated.`
});
return res.status(201).json({
general: `${req.user.handle}'s profile info has been updated.`
});
})
.catch((err) => {
.catch(err => {
console.error(err);
return res.status(500).json({
error: "Error updating profile data"
@@ -276,14 +317,15 @@ exports.getUserDetails = (req, res) => {
let userData = {};
db.doc(`/users/${req.body.handle}`)
.get()
.then((doc) => {
.then(doc => {
if (doc.exists) {
userData = doc.data();
return res.status(200).json({userData});
} else {
return res.status(400).json({error: "User not found."})
}})
.catch((err) => {
return res.status(200).json({ userData });
} else {
return res.status(400).json({ error: "User not found." });
}
})
.catch(err => {
console.error(err);
return res.status(500).json({ error: err.code });
});
@@ -293,17 +335,160 @@ exports.getAuthenticatedUser = (req, res) => {
let credentials = {};
db.doc(`/users/${req.user.handle}`)
.get()
.then((doc) => {
.then(doc => {
if (doc.exists) {
credentials = doc.data();
return res.status(200).json({credentials});
} else {
return res.status(400).json({error: "User not found."})
}})
.catch((err) => {
return res.status(200).json({ credentials });
} else {
return res.status(400).json({ error: "User not found." });
}
})
.catch(err => {
console.error(err);
return res.status(500).json({ error: err.code });
});
};
// Verifies the user sent to the request
// Must be run by the Admin user
exports.verifyUser = (req, res) => {
if (req.userData.handle !== "Admin") {
return res.status(403).json({ error: "This must be done as Admin" });
}
db.doc(`/users/${req.body.user}`)
.get()
.then(doc => {
if (doc.exists) {
let verifiedUser = doc.data();
verifiedUser.verified = true;
return db
.doc(`/users/${req.body.user}`)
.set(verifiedUser, { merge: true });
} else {
return res
.status(400)
.json({ error: `User ${req.body.user} was not found` });
}
})
.then(() => {
return res
.status(201)
.json({ message: `${req.body.user} is now verified` });
})
.catch(err => {
console.error(err);
return res.status(500).json({ error: err.code });
});
};
// Unverifies the user sent to the request
// Must be run by admin
exports.unverifyUser = (req, res) => {
if (req.userData.handle !== "Admin") {
return res.status(403).json({ error: "This must be done as Admin" });
}
db.doc(`/users/${req.body.user}`)
.get()
.then(doc => {
if (doc.exists) {
let unverifiedUser = doc.data();
unverifiedUser.verified = false;
return db
.doc(`/users/${req.body.user}`)
.set(unverifiedUser, { merge: true });
} else {
return res
.status(400)
.json({ error: `User ${req.body.user} was not found` });
}
})
.then(() => {
return res
.status(201)
.json({ message: `${req.body.user} is no longer verified` });
})
.catch(err => {
console.error(err);
return res.status(500).json({ error: err.code });
});
};
exports.getUserHandles = (req, res) => {
db.doc(`/users/${req.body.userHandle}`)
.get()
.then(doc => {
if (doc.exists) {
let userHandle = doc.data().handle;
return res.status(200).json(userHandle);
} else {
return res.status(404).json({ error: "user not found" });
}
})
.catch(err => {
console.error(err);
return res.status(500).json({ error: "Failed to get all user handles." });
});
};
exports.addSubscription = (req, res) => {
let new_following = [];
let userRef = db.doc(`/users/${req.userData.handle}`);
userRef.get().then(doc => {
new_following = doc.data().following;
new_following.push(req.body.following);
// add stuff
userRef
.set({ following: new_following }, { merge: true })
.then(doc => {
return res
.status(201)
.json({ message: `Following ${req.body.following}` });
})
.catch(err => {
return res.status(500).json({ err });
});
return res.status(200).json({ error: "Follow success!" });
});
};
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 });
});
};
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(500).json({ error: "shouldn't execute" });
});
};

View File

@@ -16,7 +16,13 @@ const {
login,
signup,
deleteUser,
updateProfileInfo
updateProfileInfo,
verifyUser,
unverifyUser,
getUserHandles,
addSubscription,
getSubs,
removeSub
} = require("./handlers/users");
// Adds a user to the database and registers them in firebase with
@@ -31,7 +37,7 @@ app.post("/login", login);
//Deletes user account
app.delete("/delete", fbAuth, deleteUser);
app.get("/getUser", fbAuth, getUserDetails);
app.post("/getUserDetails", fbAuth, getUserDetails);
// Returns all profile data of the currently logged in user
app.get("/getProfileInfo", fbAuth, getProfileInfo);
@@ -41,6 +47,26 @@ app.post("/updateProfileInfo", fbAuth, updateProfileInfo);
app.get("/user", fbAuth, getAuthenticatedUser);
// 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 *
*------------------------------------------------------------------*/
@@ -61,7 +87,8 @@ app.post("/putPost", fbAuth, putPost);
const {
putTopic,
getAllTopics,
deleteTopic
deleteTopic,
getUserTopics
} = require("./handlers/topic");
// add topic to database
@@ -71,6 +98,9 @@ app.post("/putTopic", fbAuth, putTopic);
app.get("/getAllTopics", fbAuth, getAllTopics);
// delete a specific topic
app.delete("/deleteTopic/:topicId", fbAuth, deleteTopic);
app.post("/deleteTopic", fbAuth, deleteTopic);
// get topic for this user
app.post("/getUserTopics", fbAuth, getUserTopics);
exports.api = functions.https.onRequest(app);