Skip to content

Commit

Permalink
bug: called createCustomer twice with the same token + lean for mongoose
Browse files Browse the repository at this point in the history
  • Loading branch information
tima101 committed Oct 19, 2018
1 parent 1bdb0ba commit dffb18a
Show file tree
Hide file tree
Showing 10 changed files with 58 additions and 48 deletions.
2 changes: 1 addition & 1 deletion api/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
"license": "MIT",
"scripts": {
"dev": "nodemon server/app.ts",
"build": "tsc --project tsconfig.json",
"build": "rm -rf production-server/ && tsc --project tsconfig.json",
"start": "NODE_ENV=production node production-server/app.js",
"now": "now && now alias",
"now-rm": "now rm saas-api --safe --yes",
Expand Down
2 changes: 1 addition & 1 deletion api/server/app.ts
Original file line number Diff line number Diff line change
Expand Up @@ -98,7 +98,7 @@ server.get('/uploaded-file', async (req, res) => {
if (teamSlug) {
const team = await Team.findOne({ slug: teamSlug })
.select('memberIds')
.lean();
.setOptions({ lean: true });

if (!team || !team.memberIds.includes(req.user.id)) {
res.status(401).end('You do not have permission.');
Expand Down
4 changes: 2 additions & 2 deletions api/server/aws-s3.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,9 +9,9 @@ async function checkPrefix(prefix, user) {
return;
}

const teams: any[] = await Team.find({ memberIds: user.id })
const teams = await Team.find({ memberIds: user.id })
.select('slug')
.lean();
.setOptions({ lean: true });

if (!teams.find(t => t.slug === prefix)) {
throw new Error('Wrong prefix.');
Expand Down
14 changes: 8 additions & 6 deletions api/server/models/Discussion.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@ import { generateNumberSlug } from '../utils/slugify';
import Post, { deletePostFiles } from './Post';
import Team from './Team';

mongoose.set('useFindAndModify', false);

const mongoSchema = new mongoose.Schema({
createdUserId: {
type: String,
Expand Down Expand Up @@ -85,7 +87,7 @@ class DiscussionClass extends mongoose.Model {

const team = await Team.findById(teamId)
.select('memberIds teamLeaderId')
.lean();
.setOptions({ lean: true });

if (!team || team.memberIds.indexOf(userId) === -1) {
throw new Error('Team not found');
Expand All @@ -106,7 +108,7 @@ class DiscussionClass extends mongoose.Model {

const filter: any = { teamId, memberIds: userId };

const discussions: any[] = await this.find(filter).lean();
const discussions: any[] = await this.find(filter).setOptions({ lean: true });

return { discussions };
}
Expand Down Expand Up @@ -137,7 +139,7 @@ class DiscussionClass extends mongoose.Model {

const discussion = await this.findById(id)
.select('teamId createdUserId')
.lean();
.setOptions({ lean: true });

const { team } = await this.checkPermission({
userId,
Expand Down Expand Up @@ -167,14 +169,14 @@ class DiscussionClass extends mongoose.Model {

const discussion = await this.findById(id)
.select('teamId')
.lean();
.setOptions({ lean: true });

await this.checkPermission({ userId, teamId: discussion.teamId });

deletePostFiles(
await Post.find({ discussionId: id })
.select('content')
.lean(),
.setOptions({ lean: true }),
);

await Post.deleteMany({ discussionId: id });
Expand All @@ -185,7 +187,7 @@ class DiscussionClass extends mongoose.Model {
}

public static findBySlug(teamId: string, slug: string) {
return this.findOne({ teamId, slug }).lean();
return this.findOne({ teamId, slug }).setOptions({ lean: true });
}
}

Expand Down
26 changes: 14 additions & 12 deletions api/server/models/Invitation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@ const dev = process.env.NODE_ENV !== 'production';
const { PRODUCTION_URL_APP } = process.env;
const ROOT_URL = dev ? 'http://localhost:3000' : PRODUCTION_URL_APP;

mongoose.set('useFindAndModify', false);

const mongoSchema = new mongoose.Schema({
teamId: {
type: String,
Expand Down Expand Up @@ -76,14 +78,14 @@ class InvitationClass extends mongoose.Model {
throw new Error('Bad data');
}

const team = await Team.findById(teamId).lean();
const team = await Team.findById(teamId).setOptions({ lean: true });
if (!team || team.teamLeaderId !== userId) {
throw new Error('Team does not exist or you have no permission');
}

const registeredUser = await User.findOne({ email })
.select('defaultTeamSlug')
.lean();
.setOptions({ lean: true });

if (registeredUser) {
if (team.memberIds.includes(registeredUser._id.toString())) {
Expand All @@ -102,7 +104,7 @@ class InvitationClass extends mongoose.Model {
let token;
const invitation = await this.findOne({ teamId, email })
.select('token')
.lean();
.setOptions({ lean: true });

if (invitation) {
token = invitation.token;
Expand Down Expand Up @@ -133,37 +135,37 @@ class InvitationClass extends mongoose.Model {
logger.error('Email sending error:', err);
});

return await this.findOne({ teamId, email }).lean();
return await this.findOne({ teamId, email }).setOptions({ lean: true });
}

public static async getTeamInvitedUsers({ userId, teamId }) {
const team = await Team.findOne({ _id: teamId })
.select('teamLeaderId')
.lean();
.setOptions({ lean: true });

if (userId !== team.teamLeaderId) {
throw new Error('You have no permission.');
}

return this.find({ teamId })
.select('email')
.lean();
.setOptions({ lean: true });
}

public static async getTeamByToken({ token }) {
if (!token) {
throw new Error('Bad data');
}

const invitation = await this.findOne({ token }).lean();
const invitation = await this.findOne({ token }).setOptions({ lean: true });

if (!invitation) {
throw new Error('Invitation not found');
}

const team = await Team.findById(invitation.teamId)
.select('name slug avatarUrl memberIds')
.lean();
.setOptions({ lean: true });

if (!team) {
throw new Error('Team does not exist');
Expand All @@ -177,15 +179,15 @@ class InvitationClass extends mongoose.Model {
throw new Error('Bad data');
}

const invitation = await this.findOne({ token }).lean();
const invitation = await this.findOne({ token }).setOptions({ lean: true });

if (!invitation) {
throw new Error('Invitation not found');
}

const team = await Team.findById(invitation.teamId)
.select('name slug avatarUrl memberIds')
.lean();
.setOptions({ lean: true });

if (team && team.memberIds.includes(userId)) {
this.deleteOne({ token }).exec();
Expand All @@ -197,7 +199,7 @@ class InvitationClass extends mongoose.Model {
throw new Error('Bad data');
}

const invitation = await this.findOne({ token }).lean();
const invitation = await this.findOne({ token }).setOptions({ lean: true });

if (!invitation || invitation.email !== user.email) {
throw new Error('Invitation not found');
Expand All @@ -207,7 +209,7 @@ class InvitationClass extends mongoose.Model {

const team = await Team.findById(invitation.teamId)
.select('memberIds slug teamLeaderId')
.lean();
.setOptions({ lean: true });

if (team && !team.memberIds.includes(user._id)) {
await Team.updateOne({ _id: team._id }, { $addToSet: { memberIds: user._id } });
Expand Down
10 changes: 6 additions & 4 deletions api/server/models/Post.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,8 @@ import logger from '../logs';
import Discussion from './Discussion';
import Team from './Team';

mongoose.set('useFindAndModify', false);

function deletePostFiles(posts: IPostDocument[]) {
const imgRegEx = /\<img.+data-src=[\"|\'](.+?)[\"|\']/g;
const files: { [key: string]: string[] } = {};
Expand Down Expand Up @@ -191,7 +193,7 @@ class PostClass extends mongoose.Model {

const post = await this.findById(id)
.select('createdUserId discussionId')
.lean();
.setOptions({ lean: true });

await this.checkPermission({ userId, discussionId: post.discussionId, post });

Expand All @@ -212,7 +214,7 @@ class PostClass extends mongoose.Model {

const post = await this.findById(id)
.select('createdUserId discussionId content')
.lean();
.setOptions({ lean: true });

await this.checkPermission({ userId, discussionId: post.discussionId, post });

Expand All @@ -232,7 +234,7 @@ class PostClass extends mongoose.Model {

const discussion = await Discussion.findById(discussionId)
.select('teamId memberIds slug')
.lean();
.setOptions({ lean: true });

if (!discussion) {
throw new Error('Discussion not found');
Expand All @@ -244,7 +246,7 @@ class PostClass extends mongoose.Model {

const team = await Team.findById(discussion.teamId)
.select('memberIds slug')
.lean();
.setOptions({ lean: true });

if (!team || team.memberIds.indexOf(userId) === -1) {
throw new Error('Team not found');
Expand Down
18 changes: 10 additions & 8 deletions api/server/models/Team.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@ import User from './User';

import { cancelSubscription, createSubscription } from '../stripe';

mongoose.set('useFindAndModify', false);

const mongoSchema = new mongoose.Schema({
teamLeaderId: {
type: String,
Expand Down Expand Up @@ -182,15 +184,15 @@ class TeamClass extends mongoose.Model {
return this.findById(
teamId,
'name avatarUrl slug defaultTeam isSubscriptionActive stripeSubscription',
).lean();
).setOptions({ lean: true });
}

public static findBySlug(slug: string) {
return this.findOne({ slug }).lean();
return this.findOne({ slug }).setOptions({ lean: true });
}

public static getList(userId: string) {
return this.find({ memberIds: userId }).lean();
return this.find({ memberIds: userId }).setOptions({ lean: true });
}

public static async removeMember({ teamId, teamLeaderId, userId }) {
Expand Down Expand Up @@ -235,7 +237,7 @@ class TeamClass extends mongoose.Model {
{ new: true, runValidators: true },
)
.select('isSubscriptionActive stripeSubscription')
.lean();
.setOptions({ lean: true });
}

public static async cancelSubscription({ teamLeaderId, teamId }) {
Expand All @@ -262,13 +264,13 @@ class TeamClass extends mongoose.Model {
{ new: true, runValidators: true },
)
.select('isSubscriptionActive stripeSubscription')
.lean();
.setOptions({ lean: true });
}

public static async cancelSubscriptionAfterFailedPayment({ subscriptionId }) {
const team = await this.find({ 'stripeSubscription.id': subscriptionId })
const team: any = await this.find({ 'stripeSubscription.id': subscriptionId })
.select('teamLeaderId isSubscriptionActive stripeSubscription isPaymentFailed')
.lean();
.setOptions({ lean: true });
if (!team.isSubscriptionActive) {
throw new Error('Team is already unsubscribed.');
}
Expand All @@ -288,7 +290,7 @@ class TeamClass extends mongoose.Model {
{ new: true, runValidators: true },
)
.select('isSubscriptionActive stripeSubscription isPaymentFailed')
.lean();
.setOptions({ lean: true });
}
}

Expand Down
16 changes: 9 additions & 7 deletions api/server/models/User.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,8 @@ import {
updateCustomer,
} from '../stripe';

mongoose.set('useFindAndModify', false);

const mongoSchema = new mongoose.Schema({
googleId: {
type: String,
Expand Down Expand Up @@ -218,7 +220,7 @@ class UserClass extends mongoose.Model {

return this.findByIdAndUpdate(userId, { $set: modifier }, { new: true, runValidators: true })
.select('displayName avatarUrl slug')
.lean();
.setOptions({ lean: true });
}

public static async createCustomer({ userId, stripeToken }) {
Expand All @@ -241,7 +243,7 @@ class UserClass extends mongoose.Model {

return this.findByIdAndUpdate(userId, { $set: modifier }, { new: true, runValidators: true })
.select('stripeCustomer stripeCard hasCardInformation')
.lean();
.setOptions({ lean: true });
}

public static async createNewCardUpdateCustomer({ userId, stripeToken }) {
Expand All @@ -265,7 +267,7 @@ class UserClass extends mongoose.Model {

return this.findByIdAndUpdate(userId, { $set: modifier }, { new: true, runValidators: true })
.select('stripeCard')
.lean();
.setOptions({ lean: true });
}

public static async getListOfInvoicesForCustomer({ userId }) {
Expand All @@ -287,23 +289,23 @@ class UserClass extends mongoose.Model {

return this.findByIdAndUpdate(userId, { $set: modifier }, { new: true, runValidators: true })
.select('stripeListOfInvoices')
.lean();
.setOptions({ lean: true });
}

public static async getTeamMembers({ userId, teamId }) {
const team = await this.checkPermissionAndGetTeam({ userId, teamId });

return this.find({ _id: { $in: team.memberIds } })
.select(this.publicFields().join(' '))
.lean();
.setOptions({ lean: true });
}

public static async signInOrSignUp({
googleId, email, googleToken, displayName, avatarUrl,
}) {
const user = await this.findOne({ googleId })
.select(this.publicFields().join(' '))
.lean();
.setOptions({ lean: true });

if (user) {
if (_.isEmpty(googleToken)) {
Expand Down Expand Up @@ -392,7 +394,7 @@ class UserClass extends mongoose.Model {

const team = await Team.findById(teamId)
.select('memberIds')
.lean();
.setOptions({ lean: true });

if (!team || team.memberIds.indexOf(userId) === -1) {
throw new Error('Team not found');
Expand Down
Loading

0 comments on commit dffb18a

Please sign in to comment.