chore: update routes to use new req.user

This commit is contained in:
Paul Bienkowski 2020-11-24 00:30:55 +01:00
parent 29269dcfcd
commit e607a1d64d
4 changed files with 58 additions and 126 deletions

View file

@ -32,6 +32,22 @@ TrackSchema.methods.slugify = function () {
this.slug = slug(this.title) + '-' + ((Math.random() * Math.pow(36, 6)) | 0).toString(36); this.slug = slug(this.title) + '-' + ((Math.random() * Math.pow(36, 6)) | 0).toString(36);
}; };
TrackSchema.methods.isVisibleTo = function (user) {
if (this.visible) {
return true;
}
if (!user) {
return false;
}
if (user._id.toString() === this.author._id.toString()) {
return true;
}
return false;
};
TrackSchema.methods.toJSONFor = function (user, include) { TrackSchema.methods.toJSONFor = function (user, include) {
return { return {
slug: this.slug, slug: this.slug,

View file

@ -24,16 +24,7 @@ router.get(
'/:username', '/:username',
auth.optional, auth.optional,
wrapRoute(async (req, res) => { wrapRoute(async (req, res) => {
if (!req.payload) { return res.json({ profile: req.profile.toProfileJSONFor(req.user) });
return res.json({ profile: req.profile.toProfileJSONFor(false) });
}
const user = await User.findById(req.payload.id);
if (!user) {
return res.json({ profile: req.profile.toProfileJSONFor(false) });
}
return res.json({ profile: req.profile.toProfileJSONFor(user) });
}), }),
); );
@ -41,14 +32,7 @@ router.post(
'/:username/follow', '/:username/follow',
auth.required, auth.required,
wrapRoute(async (req, res) => { wrapRoute(async (req, res) => {
const profileId = req.profile._id; await req.user.follow(req.profile._id);
const user = await User.findById(req.payload.id);
if (!user) {
return res.sendStatus(401);
}
await user.follow(profileId);
return res.json({ profile: req.profile.toProfileJSONFor(user) }); return res.json({ profile: req.profile.toProfileJSONFor(user) });
}), }),
); );
@ -57,14 +41,7 @@ router.delete(
'/:username/follow', '/:username/follow',
auth.required, auth.required,
wrapRoute(async (req, res) => { wrapRoute(async (req, res) => {
const profileId = req.profile._id; await req.user.unfollow(req.profile._id);
const user = User.findById(req.payload.id);
if (!user) {
return res.sendStatus(401);
}
await user.unfollow(profileId);
return res.json({ profile: req.profile.toProfileJSONFor(user) }); return res.json({ profile: req.profile.toProfileJSONFor(user) });
}), }),
); );

View file

@ -78,16 +78,13 @@ router.get(
query._id = { $in: [] }; query._id = { $in: [] };
} }
const results = await Promise.all([ const [tracks, tracksCount] = await Promise.all([
Track.find(query).limit(Number(limit)).skip(Number(offset)).sort({ createdAt: 'desc' }).populate('author').exec(), Track.find(query).limit(Number(limit)).skip(Number(offset)).sort({ createdAt: 'desc' }).populate('author').exec(),
Track.countDocuments(query).exec(), Track.countDocuments(query).exec(),
req.payload ? User.findById(req.payload.id) : null,
]); ]);
const [tracks, tracksCount, user] = results;
return res.json({ return res.json({
tracks: tracks.map((track) => track.toJSONFor(user)), tracks: tracks.map((track) => track.toJSONFor(req.user)),
tracksCount, tracksCount,
}); });
}), }),
@ -108,13 +105,7 @@ router.get(
offset = req.query.offset; offset = req.query.offset;
} }
const user = await User.findById(req.payload.id); const showByUserIds = [req.user.id, ...(req.user.following || [])];
if (!user) {
return res.sendStatus(401);
}
const showByUserIds = [req.payload.id, ...(user.following || [])];
const [tracks, tracksCount] = await Promise.all([ const [tracks, tracksCount] = await Promise.all([
Track.find({ author: { $in: showByUserIds } }) Track.find({ author: { $in: showByUserIds } })
@ -127,7 +118,7 @@ router.get(
return res.json({ return res.json({
tracks: tracks.map(function (track) { tracks: tracks.map(function (track) {
return track.toJSONFor(user); return track.toJSONFor(req.user);
}), }),
tracksCount: tracksCount, tracksCount: tracksCount,
}); });
@ -190,18 +181,12 @@ router.post(
auth.required, auth.required,
busboy(), // parse multipart body busboy(), // parse multipart body
wrapRoute(async (req, res) => { wrapRoute(async (req, res) => {
const user = await User.findById(req.payload.id);
if (!user) {
return res.sendStatus(401);
}
const { body } = await getMultipartOrJsonBody(req, (body) => body.track); const { body } = await getMultipartOrJsonBody(req, (body) => body.track);
const track = new Track(body); const track = new Track(body);
const trackData = new TrackData(); const trackData = new TrackData();
track.trackData = trackData._id; track.trackData = trackData._id;
track.author = user; track.author = req.user;
if (track.body) { if (track.body) {
track.body = track.body.trim(); track.body = track.body.trim();
@ -218,31 +203,25 @@ router.post(
await track.save(); await track.save();
// console.log(track.author); // console.log(track.author);
return res.json({ track: track.toJSONFor(user) }); return res.json({ track: track.toJSONFor(req.user) });
}), }),
); );
router.post( router.post(
'/begin', '/begin',
auth.optional, auth.required,
wrapRoute(async (req, res) => { wrapRoute(async (req, res) => {
const user = await User.findById(req.body.id);
if (!user) {
return res.sendStatus(401);
}
const track = new Track(req.body.track); const track = new Track(req.body.track);
const trackData = new TrackData(); const trackData = new TrackData();
track.trackData = trackData._id; track.trackData = trackData._id;
track.author = user; track.author = req.user;
track.uploadedByUserAgent = normalizeUserAgent(req.headers['user-agent']); track.uploadedByUserAgent = normalizeUserAgent(req.headers['user-agent']);
await track.save(); await track.save();
await trackData.save(); await trackData.save();
// remember which is the actively building track for this user // remember which is the actively building track for this user
currentTracks.set(user.id, track._id); currentTracks.set(req.user.id, track._id);
return res.sendStatus(200); return res.sendStatus(200);
}), }),
@ -250,19 +229,13 @@ router.post(
router.post( router.post(
'/add', '/add',
auth.optional, auth.required,
wrapRoute(async (req, res) => { wrapRoute(async (req, res) => {
const user = await User.findById(req.body.id); if (!currentTracks.has(req.user.id)) {
if (!user) {
return res.sendStatus(401);
}
if (!currentTracks.has(user.id)) {
throw new Error('current user has no active track, start one with POST to /tracks/begin'); throw new Error('current user has no active track, start one with POST to /tracks/begin');
} }
const trackId = currentTracks.get(user.id); const trackId = currentTracks.get(req.user.id);
const track = await Track.findById(trackId); const track = await Track.findById(trackId);
if (!track) { if (!track) {
@ -278,20 +251,14 @@ router.post(
router.post( router.post(
'/end', '/end',
auth.optional, auth.required,
wrapRoute(async (req, res) => { wrapRoute(async (req, res) => {
const user = await User.findById(req.body.id);
if (!user) {
return res.sendStatus(401);
}
let track; let track;
let trackData; let trackData;
if (currentTracks.has(user.id)) { if (currentTracks.has(req.user.id)) {
// the file is less than 100 lines // the file is less than 100 lines
const trackId = currentTracks.get(user.id); const trackId = currentTracks.get(req.user.id);
track = await Track.findById(trackId); track = await Track.findById(trackId);
if (!track) { if (!track) {
throw new Error('current user active track is gone, retry upload'); throw new Error('current user active track is gone, retry upload');
@ -303,7 +270,7 @@ router.post(
track = new Track(req.body.track); track = new Track(req.body.track);
trackData = new TrackData(); trackData = new TrackData();
track.trackData = trackData._id; track.trackData = trackData._id;
track.author = user; track.author = req.user;
} }
trackData.points = Array.from(parseTrackPoints(track.body)); trackData.points = Array.from(parseTrackPoints(track.body));
@ -312,7 +279,7 @@ router.post(
await trackData.save(); await trackData.save();
// We are done with this track, it is complete. // We are done with this track, it is complete.
currentTracks.delete(user.id); currentTracks.delete(req.user.id);
return res.sendStatus(200); return res.sendStatus(200);
}), }),
@ -323,16 +290,11 @@ router.get(
'/:track', '/:track',
auth.optional, auth.optional,
wrapRoute(async (req, res) => { wrapRoute(async (req, res) => {
const [user] = await Promise.all([ if (!req.track.isVisibleTo(req.user)) {
req.payload ? User.findById(req.payload.id) : null,
req.track.populate('author').execPopulate(),
]);
if (!req.track.visible && (!req.payload || req.track.author._id.toString() !== req.payload.id.toString())) {
return res.sendStatus(403); return res.sendStatus(403);
} }
return res.json({ track: req.track.toJSONFor(user, { body: true }) }); return res.json({ track: req.track.toJSONFor(req.user, { body: true }) });
}), }),
); );
@ -342,9 +304,7 @@ router.put(
busboy(), busboy(),
auth.required, auth.required,
wrapRoute(async (req, res) => { wrapRoute(async (req, res) => {
const user = await User.findById(req.payload.id); if (req.track.author._id.toString() !== req.user.id.toString()) {
if (req.track.author._id.toString() !== req.payload.id.toString()) {
return res.sendStatus(403); return res.sendStatus(403);
} }
@ -377,7 +337,7 @@ router.put(
req.track.visible = body.visible; req.track.visible = body.visible;
const track = await req.track.save(); const track = await req.track.save();
return res.json({ track: track.toJSONFor(user) }); return res.json({ track: track.toJSONFor(req.user) });
}), }),
); );
@ -386,11 +346,7 @@ router.delete(
'/:track', '/:track',
auth.required, auth.required,
wrapRoute(async (req, res) => { wrapRoute(async (req, res) => {
const user = await User.findById(req.payload.id); if (req.track.author._id.toString() === req.user.id.toString()) {
if (!user) {
return res.sendStatus(401);
}
if (req.track.author._id.toString() === req.payload.id.toString()) {
await TrackData.findByIdAndDelete(req.track.trackData); await TrackData.findByIdAndDelete(req.track.trackData);
await req.track.remove(); await req.track.remove();
return res.sendStatus(204); return res.sendStatus(204);
@ -407,14 +363,9 @@ router.post(
wrapRoute(async (req, res) => { wrapRoute(async (req, res) => {
const trackId = req.track._id; const trackId = req.track._id;
const user = await User.findById(req.payload.id); await req.user.favorite(trackId);
if (!user) {
return res.sendStatus(401);
}
await user.favorite(trackId);
const track = await req.track.updateFavoriteCount(); const track = await req.track.updateFavoriteCount();
return res.json({ track: track.toJSONFor(user) }); return res.json({ track: track.toJSONFor(req.user) });
}), }),
); );
@ -425,14 +376,9 @@ router.delete(
wrapRoute(async (req, res) => { wrapRoute(async (req, res) => {
const trackId = req.track._id; const trackId = req.track._id;
const user = await User.findById(req.payload.id); await req.user.unfavorite(trackId);
if (!user) {
return res.sendStatus(401);
}
await user.unfavorite(trackId);
const track = await req.track.updateFavoriteCount(); const track = await req.track.updateFavoriteCount();
return res.json({ track: track.toJSONFor(user) }); return res.json({ track: track.toJSONFor(req.user) });
}), }),
); );
@ -441,7 +387,9 @@ router.get(
'/:track/comments', '/:track/comments',
auth.optional, auth.optional,
wrapRoute(async (req, res) => { wrapRoute(async (req, res) => {
const user = await Promise.resolve(req.payload ? User.findById(req.payload.id) : null); if (!req.track.isVisibleTo(req.user)) {
return res.sendStatus(403);
}
await req.track await req.track
.populate({ .populate({
@ -459,7 +407,7 @@ router.get(
return res.json({ return res.json({
comments: req.track.comments.map(function (comment) { comments: req.track.comments.map(function (comment) {
return comment.toJSONFor(user); return comment.toJSONFor(req.user);
}), }),
}); });
}), }),
@ -470,21 +418,16 @@ router.post(
'/:track/comments', '/:track/comments',
auth.required, auth.required,
wrapRoute(async (req, res) => { wrapRoute(async (req, res) => {
const user = await User.findById(req.payload.id);
if (!user) {
return res.sendStatus(401);
}
const comment = new Comment(req.body.comment); const comment = new Comment(req.body.comment);
comment.track = req.track; comment.track = req.track;
comment.author = user; comment.author = req.user;
await comment.save(); await comment.save();
req.track.comments.push(comment); req.track.comments.push(comment);
await req.track.save(); await req.track.save();
return res.json({ comment: comment.toJSONFor(user) }); return res.json({ comment: comment.toJSONFor(req.user) });
}), }),
); );
@ -492,7 +435,7 @@ router.delete(
'/:track/comments/:comment', '/:track/comments/:comment',
auth.required, auth.required,
wrapRoute(async (req, res) => { wrapRoute(async (req, res) => {
if (req.comment.author.toString() === req.payload.id.toString()) { if (req.comment.author.toString() === req.user.id.toString()) {
req.track.comments.remove(req.comment._id); req.track.comments.remove(req.comment._id);
await req.track.save(); await req.track.save();
await Comment.find({ _id: req.comment._id }).remove(); await Comment.find({ _id: req.comment._id }).remove();
@ -508,6 +451,10 @@ router.get(
'/:track/TrackData', '/:track/TrackData',
auth.optional, auth.optional,
wrapRoute(async (req, res) => { wrapRoute(async (req, res) => {
if (!req.track.isVisibleTo(req.user)) {
return res.sendStatus(403);
}
// console.log("requestTrackData"+req.track); // console.log("requestTrackData"+req.track);
const trackData = await TrackData.findById(req.track.trackData); const trackData = await TrackData.findById(req.track.trackData);
// console.log({trackData: trackData}); // console.log({trackData: trackData});

View file

@ -9,12 +9,7 @@ router.get(
'/user', '/user',
auth.required, auth.required,
wrapRoute(async (req, res) => { wrapRoute(async (req, res) => {
const user = await User.findById(req.payload.id); return res.json({ user: req.user.toAuthJSON() });
if (!user) {
return res.sendStatus(401);
}
return res.json({ user: user.toAuthJSON() });
}), }),
); );
@ -22,10 +17,7 @@ router.put(
'/user', '/user',
auth.required, auth.required,
wrapRoute(async (req, res) => { wrapRoute(async (req, res) => {
const user = await User.findById(req.payload.id); const user = req.user;
if (!user) {
return res.sendStatus(401);
}
// only update fields that were actually passed... // only update fields that were actually passed...
if (typeof req.body.user.username !== 'undefined') { if (typeof req.body.user.username !== 'undefined') {