Added function to follow and unfollow users

This commit is contained in:
Leon Liang 2019-11-15 17:47:47 -05:00
parent 903ea35662
commit 1d26eb97ad
2 changed files with 137 additions and 51 deletions

View File

@ -201,10 +201,10 @@ exports.deleteUser = (req, res) => {
// Get the profile image filename // Get the profile image filename
// `https://firebasestorage.googleapis.com/v0/b/${config.storageBucket}/o/${imageFileName}?alt=media` // `https://firebasestorage.googleapis.com/v0/b/${config.storageBucket}/o/${imageFileName}?alt=media`
let imageFileName; let imageFileName;
req.userData.imageUrl ? req.userData.imageUrl
imageFileName = req.userData.imageUrl.split('/o/')[1].split('?alt=')[0] : ? (imageFileName = req.userData.imageUrl.split("/o/")[1].split("?alt=")[0])
imageFileName = 'no-img.png' : (imageFileName = "no-img.png");
const userId = req.userData.userId; const userId = req.userData.userId;
let errors = {}; let errors = {};
@ -221,56 +221,58 @@ exports.deleteUser = (req, res) => {
let auth = admin.auth().deleteUser(userId); let auth = admin.auth().deleteUser(userId);
// Deletes database data // Deletes database data
let data = db.collection("users").doc(`${req.user.handle}`).delete(); let data = db
.collection("users")
.doc(`${req.user.handle}`)
.delete();
// Deletes any custom profile image // Deletes any custom profile image
let image; let image;
if (imageFileName !== 'no-img.png') { if (imageFileName !== "no-img.png") {
image = admin.storage().bucket().file(imageFileName).delete() image = admin
.storage()
.bucket()
.file(imageFileName)
.delete();
} else { } else {
image = Promise.resolve(); image = Promise.resolve();
} }
// Deletes all users posts // Deletes all users posts
let posts = db.collection("posts") let posts = db
.collection("posts")
.where("userHandle", "==", req.user.handle) .where("userHandle", "==", req.user.handle)
.get() .get()
.then((query) => { .then(query => {
query.forEach((snap) => { query.forEach(snap => {
snap.ref.delete(); snap.ref.delete();
}); });
return; return;
}) });
let promises = [ let promises = [
auth auth.then(thenFunction("auth")).catch(err => catchFunction("auth", err)),
.then(thenFunction('auth')) data.then(thenFunction("data")).catch(err => catchFunction("data", err)),
.catch((err) => catchFunction('auth', err)), image.then(thenFunction("image")).catch(err => catchFunction("image", err)),
data posts.then(thenFunction("posts")).catch(err => catchFunction("image", err))
.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 // Wait for all promises to resolve
let waitPromise = Promise.all(promises); let waitPromise = Promise.all(promises);
waitPromise.then(() => { waitPromise
if (Object.keys(errors) > 0) { .then(() => {
return res.status(500).json(errors); if (Object.keys(errors) > 0) {
} else { return res.status(500).json(errors);
return res.status(200).json({message: `All data for ${req.userData.handle} has been deleted.`}); } 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}); }
}) })
.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
@ -351,55 +353,67 @@ exports.getAuthenticatedUser = (req, res) => {
// Must be run by the Admin user // Must be run by the Admin user
exports.verifyUser = (req, res) => { exports.verifyUser = (req, res) => {
if (req.userData.handle !== "Admin") { if (req.userData.handle !== "Admin") {
return res.status(403).json({error: "This must be done as Admin"}); return res.status(403).json({ error: "This must be done as Admin" });
} }
db.doc(`/users/${req.body.user}`) db.doc(`/users/${req.body.user}`)
.get() .get()
.then((doc) => { .then(doc => {
if (doc.exists) { if (doc.exists) {
let verifiedUser = doc.data(); let verifiedUser = doc.data();
verifiedUser.verified = true; verifiedUser.verified = true;
return db.doc(`/users/${req.body.user}`).set(verifiedUser, {merge: true}); return db
.doc(`/users/${req.body.user}`)
.set(verifiedUser, { merge: true });
} else { } else {
return res.status(400).json({error: `User ${req.body.user} was not found`}); return res
.status(400)
.json({ error: `User ${req.body.user} was not found` });
} }
}) })
.then(() => { .then(() => {
return res.status(201).json({message: `${req.body.user} is now verified`}); return res
.status(201)
.json({ message: `${req.body.user} is now verified` });
}) })
.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 });
}); });
} };
// Unverifies the user sent to the request // Unverifies the user sent to the request
// Must be run by admin // Must be run by admin
exports.unverifyUser = (req, res) => { exports.unverifyUser = (req, res) => {
if (req.userData.handle !== "Admin") { if (req.userData.handle !== "Admin") {
return res.status(403).json({error: "This must be done as Admin"}); return res.status(403).json({ error: "This must be done as Admin" });
} }
db.doc(`/users/${req.body.user}`) db.doc(`/users/${req.body.user}`)
.get() .get()
.then((doc) => { .then(doc => {
if (doc.exists) { if (doc.exists) {
let unverifiedUser = doc.data(); let unverifiedUser = doc.data();
unverifiedUser.verified = false; unverifiedUser.verified = false;
return db.doc(`/users/${req.body.user}`).set(unverifiedUser, {merge: true}); return db
.doc(`/users/${req.body.user}`)
.set(unverifiedUser, { merge: true });
} else { } else {
return res.status(400).json({error: `User ${req.body.user} was not found`}); return res
.status(400)
.json({ error: `User ${req.body.user} was not found` });
} }
}) })
.then(() => { .then(() => {
return res.status(201).json({message: `${req.body.user} is no longer verified`}); return res
.status(201)
.json({ message: `${req.body.user} is no longer verified` });
}) })
.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.getUserHandles = (req, res) => { exports.getUserHandles = (req, res) => {
admin admin
.firestore() .firestore()
@ -417,3 +431,63 @@ exports.getUserHandles = (req, res) => {
return res.status(500).json({ error: "Failed to get all user handles." }); 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 });
});
});
};
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 });
});
});
};

View File

@ -19,7 +19,10 @@ const {
updateProfileInfo, updateProfileInfo,
verifyUser, verifyUser,
unverifyUser, unverifyUser,
getUserHandles 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
@ -55,6 +58,15 @@ app.post("/unverifyUser", fbAuth, unverifyUser);
// get user handles with search phase // get user handles with search phase
app.get("/getUserHandles", fbAuth, getUserHandles); app.get("/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.delete("/removeSub", fbAuth, removeSub);
/*------------------------------------------------------------------* /*------------------------------------------------------------------*
* handlers/post.js * * handlers/post.js *
*------------------------------------------------------------------*/ *------------------------------------------------------------------*/