From b1465d5f82c05f83b66eaa22dbca1824baa1d38d Mon Sep 17 00:00:00 2001 From: Sergio Gutierrez Villalba Date: Thu, 13 Jun 2024 10:23:56 +0200 Subject: [PATCH 1/2] refactor(teams): remove dead code --- src/app/middleware/teams.js | 29 -- src/app/models/index.ts | 12 - src/app/models/team.ts | 39 --- src/app/models/teaminvitation.ts | 37 --- src/app/models/teammember.ts | 48 --- src/app/routes/auth.ts | 4 +- src/app/routes/plan.js | 25 -- src/app/routes/routes.ts | 2 - src/app/routes/storage.ts | 3 - src/app/routes/stripe.js | 81 ----- src/app/routes/teams.js | 289 ------------------ src/app/services/appsumo.js | 6 - src/app/services/files.js | 27 -- src/app/services/folder.js | 16 +- src/app/services/mail.js | 25 -- src/app/services/stripe.js | 46 --- src/app/services/team.js | 72 ----- src/app/services/teaminvitations.js | 54 ---- src/app/services/teamsmembers.js | 96 ------ src/config/initializers/middleware.js | 9 - src/config/pm2/dev.pm2.config.js | 11 - .../pm2/inactivity-remove.pm2.config.js | 11 - src/config/pm2/inactivity.pm2.config.js | 11 - src/config/pm2/staging.pm2.config.js | 11 - tests/controllers/auth.test.ts | 1 - 25 files changed, 5 insertions(+), 960 deletions(-) delete mode 100644 src/app/middleware/teams.js delete mode 100644 src/app/models/team.ts delete mode 100644 src/app/models/teaminvitation.ts delete mode 100644 src/app/models/teammember.ts delete mode 100644 src/app/routes/teams.js delete mode 100644 src/app/services/team.js delete mode 100644 src/app/services/teaminvitations.js delete mode 100644 src/app/services/teamsmembers.js delete mode 100644 src/config/pm2/dev.pm2.config.js delete mode 100644 src/config/pm2/inactivity-remove.pm2.config.js delete mode 100644 src/config/pm2/inactivity.pm2.config.js delete mode 100644 src/config/pm2/staging.pm2.config.js diff --git a/src/app/middleware/teams.js b/src/app/middleware/teams.js deleted file mode 100644 index a788bf86..00000000 --- a/src/app/middleware/teams.js +++ /dev/null @@ -1,29 +0,0 @@ -// TODO: The auth should be replaced by an auth token that will -// provide the team id of the user making the request -const build = (Service) => async (req, res, next) => { - try { - const teamId = req.params.idTeam || null; - - if (!req.behalfUser) { - req.behalfUser = req.user; - } - - let teamMember = null; - - if (teamId) { - teamMember = await Service.TeamsMembers.getMemberByIdTeam(teamId, req.behalfUser.email); - } - - if (teamId && !teamMember) { - return res.status(401).send(); - } - - return next(); - } catch (err) { - return next(err); - } -}; - -module.exports = { - build, -}; diff --git a/src/app/models/index.ts b/src/app/models/index.ts index c95806d3..79f22acd 100644 --- a/src/app/models/index.ts +++ b/src/app/models/index.ts @@ -12,9 +12,6 @@ import initMailLimit, { MailLimitModel } from './mailLimit'; import initPlan, { PlanModel } from './plan'; import initReferral, { ReferralModel } from './referral'; import initShare, { ShareModel } from './share'; -import initTeam, { TeamModel } from './team'; -import initTeamInvitation, { TeamInvitationModel } from './teaminvitation'; -import initTeamMember, { TeamMemberModel } from './teammember'; import initThumbnail, { ThumbnailModel } from './thumbnail'; import initUser, { UserModel } from './user'; import initUserReferral, { UserReferralModel } from './userReferral'; @@ -43,9 +40,6 @@ export type ModelType = | PlanModel | ReferralModel | ShareModel - | TeamModel - | TeamInvitationModel - | TeamMemberModel | UserModel | UserReferralModel | FriendInvitationModel @@ -74,9 +68,6 @@ export default (database: Sequelize) => { const Plan = initPlan(database); const Referral = initReferral(database); const Share = initShare(database); - const Team = initTeam(database); - const TeamMember = initTeamMember(database); - const TeamInvitation = initTeamInvitation(database); const User = initUser(database); const UserReferral = initUserReferral(database); const FriendInvitation = initFriendInvitation(database); @@ -192,9 +183,6 @@ export default (database: Sequelize) => { [Plan.name]: Plan, [Referral.name]: Referral, [Share.name]: Share, - [Team.name]: Team, - [TeamMember.name]: TeamMember, - [TeamInvitation.name]: TeamInvitation, [User.name]: User, [UserReferral.name]: UserReferral, [FriendInvitation.name]: FriendInvitation, diff --git a/src/app/models/team.ts b/src/app/models/team.ts deleted file mode 100644 index 2bc9dd20..00000000 --- a/src/app/models/team.ts +++ /dev/null @@ -1,39 +0,0 @@ -import { Sequelize, ModelDefined, DataTypes } from 'sequelize'; - -interface TeamAttributes { - id: number; - admin: string; - name: string; - bridgeUser: string; - bridgePassword: string; - bridgeMnemonic: string; - totalMembers: number; -} - -export type TeamModel = ModelDefined; - -export default (database: Sequelize): TeamModel => { - const Team: TeamModel = database.define( - 'teams', - { - id: { - type: DataTypes.INTEGER, - primaryKey: true, - allowNull: false, - autoIncrement: true, - }, - admin: DataTypes.STRING, - name: DataTypes.STRING, - bridge_user: DataTypes.STRING, - bridge_password: DataTypes.STRING, - bridge_mnemonic: DataTypes.STRING, - total_members: DataTypes.INTEGER, - }, - { - timestamps: false, - underscored: true, - }, - ); - - return Team; -}; diff --git a/src/app/models/teaminvitation.ts b/src/app/models/teaminvitation.ts deleted file mode 100644 index 58a0d792..00000000 --- a/src/app/models/teaminvitation.ts +++ /dev/null @@ -1,37 +0,0 @@ -import { Sequelize, ModelDefined, DataTypes } from 'sequelize'; - -interface TeamInvitationAttributes { - id: number; - idTeam: number; - user: string; - token: string; - bridgePassword: string; - mnemonic: string; -} - -export type TeamInvitationModel = ModelDefined; - -export default (database: Sequelize): TeamInvitationModel => { - const TeamInvitation: TeamInvitationModel = database.define( - 'teamsinvitations', - { - id: { - type: DataTypes.INTEGER, - primaryKey: true, - allowNull: false, - autoIncrement: true, - }, - id_team: DataTypes.INTEGER, - user: DataTypes.STRING, - token: DataTypes.STRING, - bridge_password: DataTypes.STRING, - mnemonic: DataTypes.STRING, - }, - { - timestamps: false, - underscored: true, - }, - ); - - return TeamInvitation; -}; diff --git a/src/app/models/teammember.ts b/src/app/models/teammember.ts deleted file mode 100644 index c06893da..00000000 --- a/src/app/models/teammember.ts +++ /dev/null @@ -1,48 +0,0 @@ -import { Sequelize, ModelDefined, DataTypes } from 'sequelize'; - -interface TeamsMembersAttributes { - id: number; - idTeam: number; - user: string; - bridgePassword: string; - bridgeMnemonic: string; -} - -export type TeamMemberModel = ModelDefined; - -export default (database: Sequelize): TeamMemberModel => { - const TeamMember: TeamMemberModel = database.define( - 'teamsmembers', - { - id: { - type: DataTypes.INTEGER, - primaryKey: true, - allowNull: false, - autoIncrement: true, - }, - id_team: { - type: DataTypes.INTEGER, - allowNull: false, - }, - user: { - type: DataTypes.STRING, - allowNull: false, - }, - bridge_password: { - type: DataTypes.STRING, - allowNull: false, - }, - bridge_mnemonic: { - type: DataTypes.STRING, - allowNull: false, - }, - }, - { - tableName: 'teamsmembers', - timestamps: false, - underscored: true, - }, - ); - - return TeamMember; -}; diff --git a/src/app/routes/auth.ts b/src/app/routes/auth.ts index 34c0e94f..cefc117f 100644 --- a/src/app/routes/auth.ts +++ b/src/app/routes/auth.ts @@ -17,7 +17,6 @@ interface Services { ReCaptcha: any; Crypt: any; KeyServer: any; - Team: any; AppSumo: any; UsersReferrals: any; Newsletter: any; @@ -169,7 +168,6 @@ export class AuthController { } const keys = await this.service.KeyServer.getKeys(userData); - const hasTeams = !!(await this.service.Team.getTeamByMember(req.body.email)); const rootFolder = await this.service.Folder.getById(userData.root_folder_id); const user = { @@ -188,7 +186,7 @@ export class AuthController { revocateKey: keys ? keys.revocation_key : null, bucket: userBucket, registerCompleted: userData.registerCompleted, - teams: hasTeams, + teams: false, username: userData.username, bridgeUser: userData.bridgeUser, sharedWorkspace: userData.sharedWorkspace, diff --git a/src/app/routes/plan.js b/src/app/routes/plan.js index 9b377576..fc452d24 100644 --- a/src/app/routes/plan.js +++ b/src/app/routes/plan.js @@ -37,29 +37,4 @@ module.exports = (Router, Service) => { return res.status(500).send({ error: errorMessage }); } }); - - Router.get('/plan/team', passportAuth, async (req, res) => { - try { - const team = await Service.Team.getTeamByMember(req.user.email); - - if (!team) { - throw createHttpError(404, `Team not found by member email: ${req.user.email}`); - } - - const teamAdminUser = await Service.User.FindUserByEmail(team.admin); - const plan = await Service.Plan.getTeamPlan(teamAdminUser.email, teamAdminUser.userId); - - if (!plan) { - throw createHttpError(404, 'Team plan not found'); - } - - return res.status(200).json(plan); - } catch (error) { - const statusCode = error.statusCode || 500; - const errorMessage = error.message || ''; - - Logger.error(`Error getting stripe team plan ${req.user.email}: ${error.message}`); - return res.status(statusCode).send({ error: errorMessage }); - } - }); }; diff --git a/src/app/routes/routes.ts b/src/app/routes/routes.ts index f940b459..6084cf7a 100644 --- a/src/app/routes/routes.ts +++ b/src/app/routes/routes.ts @@ -20,7 +20,6 @@ import NewsletterRoutes from './newsletter'; import UserRoutes from './user'; import AnalyticsRoutes from './analytics'; import { Sign, passportAuth } from '../middleware/passport'; -import TeamsRoutes from './teams'; import logger from '../../lib/logger'; import * as ReCaptchaV3 from '../../lib/recaptcha'; import * as AnalyticsService from '../../lib/analytics/AnalyticsService'; @@ -42,7 +41,6 @@ export default (router: Router, service: any, App: any): Router => { DesktopRoutes(router, service); MobileRoutes(router, service, App); TwoFactorRoutes(router, service, App); - TeamsRoutes(router, service, App); AppSumoRoutes(router, service, App); PlanRoutes(router, service); ShareRoutes(router, service); diff --git a/src/app/routes/storage.ts b/src/app/routes/storage.ts index 9cc29b7b..19250b1a 100644 --- a/src/app/routes/storage.ts +++ b/src/app/routes/storage.ts @@ -6,7 +6,6 @@ import { Logger } from 'winston'; import { default as logger } from '../../lib/logger'; import createHttpError, { HttpError } from 'http-errors'; import { FolderAttributes } from '../models/folder'; -import teamsMiddlewareBuilder from '../middleware/teams'; import Validator from '../../lib/Validator'; import { FileAttributes } from '../models/file'; import CONSTANTS from '../constants'; @@ -809,7 +808,6 @@ export default (router: Router, service: any) => { const Logger = logger.getInstance(); const { passportAuth } = passport; const sharedAdapter = sharedMiddlewareBuilder.build(service); - const teamsAdapter = teamsMiddlewareBuilder.build(service); const resourceSharingAdapter = resourceSharingMiddlewareBuilder.build(service); const controller = new StorageController(service, Logger); @@ -841,7 +839,6 @@ export default (router: Router, service: any) => { '/storage/v2/folder/:id/:idTeam?', passportAuth, sharedAdapter, - teamsAdapter, controller.getFolderContents.bind(controller), ); router.post('/storage/move/file', passportAuth, sharedAdapter, controller.moveFile.bind(controller)); diff --git a/src/app/routes/stripe.js b/src/app/routes/stripe.js index 0b92bc5f..9a516d70 100644 --- a/src/app/routes/stripe.js +++ b/src/app/routes/stripe.js @@ -121,61 +121,6 @@ module.exports = (Router, Service) => { ); }); - /** - * Should create a new Stripe Session token. - * Stripe Session is neccesary to perform a new payment - */ - Router.post('/stripe/teams/session', passportAuth, async (req, res) => { - const test = req.body.test || false; - const stripe = test ? StripeTest : StripeProduction; - const { mode, successUrl, canceledUrl, priceId, quantity } = req.body; - - let bridgeUser = await Service.Team.getTeamByEmail(req.user.email); - - if (!bridgeUser) { - const newRandomTeam = Service.Team.randomEmailBridgeUserTeam(); - bridgeUser = await Service.Team.create({ - name: 'My team', - admin: req.user.email, - bridge_user: newRandomTeam.bridge_user, - bridge_password: newRandomTeam.password, - bridge_mnemonic: req.body.mnemonicTeam, - }); - } - - const sessionParams = { - payment_method_types: ['card'], - success_url: successUrl || `${process.env.HOST_DRIVE_WEB}/team/success/{CHECKOUT_SESSION_ID}`, - cancel_url: canceledUrl || `${process.env.HOST_DRIVE_WEB}/account?tab=plans`, - mode, - line_items: [ - { - price: priceId, - quantity, - }, - ], - metadata: { - is_teams: true, - total_members: quantity, - team_email: bridgeUser.bridge_user, - admin_email: req.user.email, - }, - customer_email: req.user.email, - allow_promotion_codes: true, - billing_address_collection: 'required', - }; - - if (sessionParams.customer) { - delete sessionParams.customer_email; - } else { - delete sessionParams.customer; - } - - const result = await stripe.checkout.sessions.create(sessionParams); - - res.status(200).send(result); - }); - /** * Should create a new Stripe Session token. * Stripe Session is neccesary to perform a new payment @@ -308,30 +253,4 @@ module.exports = (Router, Service) => { res.status(500).send({ error: err.message }); }); }); - - Router.get('/stripe/teams/products', passportAuth, (req, res) => { - const test = req.query.test || false; - - Service.Stripe.getTeamProducts(test) - .then((products) => { - res.status(200).send(products); - }) - .catch((err) => { - res.status(500).send({ error: err }); - }); - }); - - Router.post('/stripe/teams/plans', passportAuth, (req, res) => { - const stripeProduct = req.body.product; - const test = req.body.test || false; - - Service.Stripe.getTeamPlans(stripeProduct, test) - .then((plans) => { - res.status(200).send(plans); - }) - .catch((err) => { - res.status(500).send({ error: err.message }); - }); - }); - }; diff --git a/src/app/routes/teams.js b/src/app/routes/teams.js deleted file mode 100644 index 01ed2dd9..00000000 --- a/src/app/routes/teams.js +++ /dev/null @@ -1,289 +0,0 @@ -const crypto = require('crypto'); -const sgMail = require('@sendgrid/mail'); -const Stripe = require('stripe'); -const _ = require('lodash'); -const { passportAuth, Sign } = require('../middleware/passport'); -const logger = require('../../lib/logger').default; - -const Logger = logger.getInstance(); - -const StripeProduction = Stripe(process.env.STRIPE_SK, { apiVersion: '2020-08-27' }); -const StripeTest = Stripe(process.env.STRIPE_SK_TEST, { apiVersion: '2020-08-27' }); - -module.exports = (Router, Service, App) => { - Router.post('/teams/team/invitations', passportAuth, async (req, res) => { - // Datas - const { email } = req.body; - const token = crypto.randomBytes(20).toString('hex'); - const bridgePassword = req.body.bridgePass; - const Encryptmnemonic = req.body.mnemonicTeam; - const user = req.user.email; - // Datas for control the 10-person limit - const teamInfo = await Service.Team.getTeamBridgeUser(user); - const totalUsers = await Service.TeamsMembers.getPeople(teamInfo.id); - - if (totalUsers.length >= teamInfo.total_members) { - return res.status(500).send({ error: `You cannot exceed the limit of ${teamInfo.total_members} members` }); - } - // Datas needed for invite a user - const existsUser = await Service.User.FindUserByEmail(email).catch(() => null); - const existsKeys = await Service.KeyServer.keysExists(existsUser); - // It is checked that the user exists and has passwords - if (!existsUser && !existsKeys) { - return res - .status(400) - .send({ error: 'You cannot invite this user. Please make sure that the user has an active Internxt account.' }); - } - // Check if the invitation exists - const existsInvitation = await Service.TeamInvitations.getTeamInvitationByUser(email); - // If it exists, forward mail, otherwise, check if is a member - if (!existsInvitation) { - const existsMember = await Service.Team.getIdTeamByUser(email); - // If not a member, check if the user teams of the bridge can send emails - if (!existsMember) { - const existsBridgeUser = await Service.Team.getTeamBridgeUser(req.user.email); - if (!existsBridgeUser) { - return res.status(400).send({ error: 'You are not allow to invite' }); - } - // If this user is allow to invite, save the invitation and send mail - const saveInvitations = await Service.TeamInvitations.save({ - id_team: existsBridgeUser.id, - user: email, - token, - bridge_password: bridgePassword, - mnemonic: Encryptmnemonic, - }); - if (!saveInvitations) { - return res.status(400).send({ error: 'The invitation can not saved' }); - } - - return Service.Mail.sendEmailTeamsMember(existsUser.name, email, token, req.team) - .then(() => { - Logger.info('User %s sends invitations to %s to join a team', req.user.email, req.body.email); - res.status(200).send({}); - }) - .catch(() => { - Logger.error('Error: Send invitation mail from %s to %s', req.user.email, req.body.email); - res.status(500).send({}); - }); - } - // Check that the member's status is 200 - if (existsMember.status === 200) { - res.status(200).send({}); - } else { - res.status(400).send({ error: 'This user is alredy a member' }); - } - } - // Forward email - return Service.Mail.sendEmailTeamsMember(existsUser.name, email, existsInvitation.token, req.team) - .then(() => { - Logger.info('The email is forwarded to the user %s', email); - res.status(200).send({}); - }) - .catch(() => { - Logger.error('Error: Send invitation mail from %s to %s', req.user.email, email); - res.status(500).send({ error: 'Error: Send invitation mail' }); - }); - }); - - Router.post('/teams/join/:token', async (req, res) => { - const { token } = req.params; - // Datas need for join a team - const getToken = await Service.TeamInvitations.getByToken(token); - const getTeam = await Service.Team.getTeamById(getToken.id_team); - const findUser = await Service.User.FindUserByEmail(getToken.user); - const keysExists = await Service.KeyServer.keysExists(findUser); - // Control that the token,team, user and keys exists - if (!getToken && !getTeam && !findUser && !keysExists) { - Logger.error('Token %s doesn\'t exists', token); - return res.status(500).send({ error: 'Invalid Team invitation link' }); - } - // Save the member - const saveMember = await Service.TeamsMembers.saveMembersFromInvitations({ - id_team: getToken.id_team, - user: getToken.user, - bridge_password: getToken.bridge_password, - bridge_mnemonic: getToken.mnemonic, - }); - if (!saveMember) { - Logger.error('Error: User %s could not be saved in teamMember ', getToken.user); - return res.status(500).send({ error: 'Invalid Team invitation link' }); - } - // Destroy the invitation - return getToken - .destroy() - .then(() => { - res.status(200).send({}); - }) - .catch(() => { - Logger.error('Error:The invitation could not be destroyed'); - res.status(500).send({ error: 'The invitation could not be destroyed' }); - }); - }); - - Router.get('/teams-members/:user', passportAuth, (req, res) => { - const userEmail = req.params.user; - - Service.Team.getIdTeamByUser(userEmail) - .then((team) => { - Service.Team.getTeamById(team.id_team) - .then((team2) => { - res.status(200).json(team2.dataValues); - }) - .catch(() => { - Logger.error('Error: Team not exists'); - }); - }) - .catch((err) => { - Logger.error('Error: This user %s not is a member', userEmail); - res.status(500).json(err); - }); - }); - - Router.get('/teams/members', passportAuth, async (req, res) => { - const user = req.user.email; - try { - const teamInfo = await Service.Team.getTeamByEmail(user); - const members = await Service.TeamsMembers.getPeople(teamInfo.id); - const result = _.remove(members, (member) => member.user !== user); - res.status(200).send(result); - } catch (e) { - res.status(500).send(); - } - }); - - Router.delete('/teams/member', passportAuth, async (req, res) => { - const removeUser = req.body.item.user; - const teamInfo = await Service.Team.getTeamByEmail(req.user.email); - if (!teamInfo) { - res.status(500).send({ info: 'You not have permissions' }); - } - const deleteMember = await Service.TeamsMembers.removeMembers(removeUser); - if (deleteMember === 1) { - res.status(200).send({ info: 'Successfully member deleted' }); - } else { - res.status(500).send({ err: 'Error, the member can not be deleted' }); - } - }); - - Router.delete('/teams/invitation', passportAuth, async (req, res) => { - const removeUser = req.body.item.user; - const teamInfo = await Service.Team.getTeamByEmail(req.user.email); - if (!teamInfo) { - res.status(500).send({ info: 'You not have permissions' }); - } - const deleteInvitation = await Service.TeamInvitations.removeInvitations(removeUser); - if (deleteInvitation === 1) { - res.status(200).send({ info: 'Successfully invitation deleted' }); - } else { - res.status(500).send({ err: 'Error, the invitation can not be deleted' }); - } - }); - - Router.post('/teams/deleteAccount', passportAuth, (req, res) => { - sgMail.setApiKey(process.env.SENDGRID_API_KEY); - const msg = { - to: 'hello@internxt.com', - from: 'hello@internxt.com', - subject: 'Delete Teams Account', - text: `Hello Internxt! I need to delete my team account ${req.user.email}`, - }; - sgMail - .send(msg) - .then(() => { - res.status(200).send({}); - }) - .catch((err) => { - Logger.error('Error: Error send deactivation email teams account of user %s', req.user.email); - res.status(500).send(err); - }); - }); - - Router.get('/teams/info', passportAuth, (req, res) => { - Service.Team.getTeamByMember(req.user.email) - .then(async (team) => { - if (!team) { - throw Error('No teams'); - } - const userTeam = team.toJSON(); - delete userTeam.id; - const internxtClient = req.headers['internxt-client']; - const tokenTeams = Sign(userTeam.bridge_user, App.config.get('secrets').JWT, internxtClient === 'drive-web'); - - const user = await Service.User.FindUserByEmail(userTeam.bridge_user); - userTeam.root_folder_id = user.root_folder_id; - const userBucket = await Service.User.GetUserBucket(user); - - const member = await Service.TeamsMembers.getMemberByIdTeam(team.id, req.user.email); - - userTeam.bridge_mnemonic = member.bridge_mnemonic; - userTeam.isAdmin = userTeam.admin === req.user.email; - userTeam.bucket = userBucket; - - res.status(200).send({ userTeam, tokenTeams }); - }) - .catch(() => { - res.status(400).json({ error: 'Team not found' }); - }); - }); - - Router.get('/teams/team/info', passportAuth, (req, res) => { - Service.Team.getTeamByEmail(req.user.email) - .then(async (team) => { - if (!team) { - throw Error('No teams'); - } - return team; - }) - .then((teamInfo) => { - res.status(200).send(teamInfo); - }) - .catch(() => { - res.status(400).json({ error: 'Team not found' }); - }); - }); - - Router.post('/teams/checkout/session', passportAuth, async (req, res) => { - const { email } = req.user; - const { mnemonic } = req.body; - const salt = crypto.randomBytes(128 / 8).toString('hex'); - const encryptedSalt = App.services.Crypt.encryptText(salt); - const newPassword = App.services.Crypt.encryptText('team', salt); - const encryptedPassword = App.services.Crypt.encryptText(newPassword); - const { checkoutSessionId } = req.body; - const stripe = req.body.test ? StripeTest : StripeProduction; - const session = await stripe.checkout.sessions.retrieve(checkoutSessionId); - - try { - if (session.payment_status === 'paid') { - const team = await Service.Team.getTeamByEmail(email); - const user = { - email: team.bridge_user, - password: encryptedPassword, - salt: encryptedSalt, - mnemonic, - bridgeUser: team.bridge_user - }; - const userRegister = await Service.User.FindOrCreate(user); - await team.update({ - bridge_password: userRegister.userId, - total_members: session.metadata.total_members, - }); - const subscription = await stripe.subscriptions.retrieve(session.subscription); - const product = await stripe.products.retrieve(subscription.plan.product); - const sizeBytes = parseInt(product.metadata.size_bytes, 10); - await Service.User.InitializeUser({ email: team.bridge_user, mnemonic }); - await Service.Team.ApplyLicenseTeams(team.bridge_user, sizeBytes * session.metadata.total_members); - await Service.TeamsMembers.addTeamMember(team.id, team.admin, team.bridge_password, team.bridge_mnemonic); - - res.status(200).send({ team }); - } else { - throw new Error('Team is not paid!'); - } - } catch (error) { - res.status(400).send({ error }); - } - }); - - return Router; -}; diff --git a/src/app/services/appsumo.js b/src/app/services/appsumo.js index 6ed2a2c1..5da6ac13 100644 --- a/src/app/services/appsumo.js +++ b/src/app/services/appsumo.js @@ -28,11 +28,6 @@ module.exports = (Model, App) => { const UserServiceInstance = UserService(Model, App); const CryptServiceInstance = CryptService(Model, App); - const UserExists = async (email) => { - const user = await Model.users.findOne({ where: { username: email }, attributes: ['id'] }); - return !!user; - }; - const ApplyLicense = async (user, plan) => { const { GATEWAY_USER, GATEWAY_PASS } = process.env; @@ -160,7 +155,6 @@ module.exports = (Model, App) => { return { Name: 'AppSumo', - UserExists, RegisterIncomplete, CompleteInfo, GetDetails, diff --git a/src/app/services/files.js b/src/app/services/files.js index 76df1a0d..ee5694a4 100644 --- a/src/app/services/files.js +++ b/src/app/services/files.js @@ -332,32 +332,6 @@ module.exports = (Model, App) => { }; }; - const isFileOfTeamFolder = (fileId) => - new Promise((resolve, reject) => { - Model.file - .findOne({ - where: { - file_id: { [Op.eq]: fileId }, - }, - include: [ - { - model: Model.folder, - where: { - id_team: { [Op.ne]: null }, - }, - }, - ], - }) - .then((file) => { - if (!file) { - throw Error('File not found on database, please refresh'); - } - - resolve(file); - }) - .catch(reject); - }); - const getFileByFolder = (fileId, folderId, userId) => { return Model.file.findOne({ where: { @@ -458,7 +432,6 @@ module.exports = (Model, App) => { DeleteFile, UpdateMetadata, MoveFile, - isFileOfTeamFolder, getRecentFiles, getFileByFolder, getByFolderAndUserId, diff --git a/src/app/services/folder.js b/src/app/services/folder.js index dfa278e9..c98b27b6 100644 --- a/src/app/services/folder.js +++ b/src/app/services/folder.js @@ -71,17 +71,10 @@ module.exports = (Model, App) => { }); } - if (teamId) { - whereCondition.where = { - id: { [Op.eq]: parentFolderId }, - id_team: { [Op.eq]: teamId }, - }; - } else { - whereCondition.where = { - id: { [Op.eq]: parentFolderId }, - user_id: { [Op.eq]: user.id }, - }; - } + whereCondition.where = { + id: { [Op.eq]: parentFolderId }, + user_id: { [Op.eq]: user.id }, + }; const parentFolder = await Model.folder.findOne(whereCondition); @@ -116,7 +109,6 @@ module.exports = (Model, App) => { bucket: null, parentId: parentFolderId || null, parentUuid: parentFolder.uuid, - id_team: teamId, }); return folder; diff --git a/src/app/services/mail.js b/src/app/services/mail.js index 39b16670..411bde4c 100644 --- a/src/app/services/mail.js +++ b/src/app/services/mail.js @@ -24,30 +24,6 @@ module.exports = (Model) => { return new InternxtMailer(mailConfig); }; - const sendEmailTeamsMember = (name, member, cryptedToken, teamName) => { - const mailer = mailInstance(); - return new Promise((resolve, reject) => { - mailer.dispatchSendGrid( - member, - 'join-team', - { - template: 'join-team', - go: { in: 'here' }, - memberName: name, - teamName, - urlAcceptInvitation: `${process.env.HOST_DRIVE_WEB}/teams/join/${cryptedToken}`, - }, - (err) => { - if (!err) { - resolve(`Mail team's invitation send to ${member}!`); - } else { - reject(Error(`Error sending mail team's invitation to ${member}`)); - } - }, - ); - }); - }; - const sendGuestInvitation = async (user, guestEmail) => { const mailer = mailInstance(); @@ -96,7 +72,6 @@ module.exports = (Model) => { return { Name: 'Mail', - sendEmailTeamsMember, sendGuestInvitation, sendInviteFriendMail, sendVerifyEmailMail, diff --git a/src/app/services/stripe.js b/src/app/services/stripe.js index b59eb541..755bd8a1 100644 --- a/src/app/services/stripe.js +++ b/src/app/services/stripe.js @@ -171,50 +171,6 @@ module.exports = () => { return products; }; - const getTeamProducts = (test = false) => - new Promise((resolve, reject) => { - const stripe = getStripe(test); - - stripe.products.list( - { - limit: 100, - }, - (err, products) => { - if (err) { - reject(err); - } else { - const productsMin = products.data - .filter((p) => p.metadata.is_teams === '1' && p.metadata.show === '1') - .map((p) => ({ id: p.id, name: p.name, metadata: p.metadata })) - .sort((a, b) => a.metadata.size_bytes * 1 - b.metadata.size_bytes * 1); - resolve(productsMin); - } - }, - ); - }); - - const getTeamPlans = (stripeProduct, test = false) => - new Promise((resolve, reject) => { - const stripe = getStripe(test); - - stripe.plans.list({ product: stripeProduct, active: true }, (err, plans) => { - if (err) { - reject(err.message); - } else { - const plansMin = plans.data - .map((p) => ({ - id: p.id, - price: p.amount, - name: p.nickname, - interval: p.interval, - interval_count: p.interval_count, - })) - .sort((a, b) => a.price * 1 - b.price * 1); - resolve(plansMin); - } - }); - }); - const findCustomerByEmail = async (email, isTest = false) => { const stripe = getStripe(isTest); const result = await stripe.customers.list({ email, limit: 1 }); @@ -297,8 +253,6 @@ module.exports = () => { getAllStorageProducts2, getStoragePlans, getProductPrices, - getTeamProducts, - getTeamPlans, findCustomerByEmail, getBilling, getUserSubscriptionPlans, diff --git a/src/app/services/team.js b/src/app/services/team.js deleted file mode 100644 index 7953f23b..00000000 --- a/src/app/services/team.js +++ /dev/null @@ -1,72 +0,0 @@ -const sequelize = require('sequelize'); -const axios = require('axios'); -const bcrypt = require('bcryptjs'); -const crypto = require('crypto'); - -const { Op } = sequelize; - -module.exports = (Model) => { - const create = (team) => - Model.teams - .create({ - admin: team.admin, - name: team.name, - bridge_user: team.bridge_user, - bridge_password: team.bridge_password, - bridge_mnemonic: team.bridge_mnemonic, - }) - .then((newTeam) => newTeam.dataValues); - - const getTeamByEmail = (user) => Model.teams.findOne({ where: { admin: { [Op.eq]: user } } }); - - const getTeamById = (idTeam) => Model.teams.findOne({ where: { id: { [Op.eq]: idTeam } } }); - - const randomEmailBridgeUserTeam = () => { - const rnd = crypto.randomBytes(8).toString('hex'); - const newEmail = `${rnd}-team@internxt.com`; - const passwd = bcrypt.hashSync(newEmail, 8); - - return { - bridge_user: newEmail, - password: passwd, - }; - }; - - const getIdTeamByUser = (user) => Model.teamsmembers.findOne({ where: { user: { [Op.eq]: user } } }); - - const getTeamBridgeUser = (user) => - Model.teams.findOne({ - where: { bridge_user: { [Op.eq]: user } }, - }); - - const getTeamByMember = (email) => - getIdTeamByUser(email).then((team) => (!team ? Promise.resolve() : getTeamById(team.id_team))); - - const ApplyLicenseTeams = async (user, size) => { - const { GATEWAY_USER, GATEWAY_PASS } = process.env; - - return axios.post( - `${process.env.STORJ_BRIDGE}/gateway/upgrade`, - { - email: user, - bytes: size, - }, - { - headers: { 'Content-Type': 'application/json' }, - auth: { username: GATEWAY_USER, password: GATEWAY_PASS }, - }, - ); - }; - - return { - Name: 'Team', - create, - getTeamByEmail, - getTeamById, - randomEmailBridgeUserTeam, - getIdTeamByUser, - getTeamByMember, - getTeamBridgeUser, - ApplyLicenseTeams, - }; -}; diff --git a/src/app/services/teaminvitations.js b/src/app/services/teaminvitations.js deleted file mode 100644 index 38e4de26..00000000 --- a/src/app/services/teaminvitations.js +++ /dev/null @@ -1,54 +0,0 @@ -const sequelize = require('sequelize'); - -const { Op } = sequelize; - -module.exports = (Model) => { - const save = (teamInvitation) => - new Promise((resolve, reject) => { - Model.teamsinvitations - .create({ - id_team: teamInvitation.id_team, - user: teamInvitation.user, - token: teamInvitation.token, - bridge_password: teamInvitation.bridge_password, - mnemonic: teamInvitation.mnemonic, - }) - .then((newTeamInvitation) => { - resolve({ teamInvitation: newTeamInvitation }); - }) - .catch((err) => { - reject(err); - }); - }); - - const getByToken = (token) => Model.teamsinvitations.findOne({ where: { token: { [Op.eq]: token } } }); - - const getTeamInvitationById = (idInvitation) => - Model.teamsinvitations.findOne({ where: { id: { [Op.eq]: idInvitation } } }); - - const getTeamInvitationByUser = (user) => - new Promise((resolve, reject) => { - Model.teamsinvitations - .findOne({ - where: { user: { [Op.eq]: user } }, - }) - .then((teaminvitations) => { - resolve(teaminvitations); - }) - .catch(() => { - reject(Error('Error querying database')); - }); - }); - - const removeInvitations = (userInvitation) => - Model.teamsinvitations.destroy({ where: { user: { [Op.eq]: userInvitation } } }); - - return { - Name: 'TeamInvitations', - save, - getByToken, - getTeamInvitationByUser, - getTeamInvitationById, - removeInvitations, - }; -}; diff --git a/src/app/services/teamsmembers.js b/src/app/services/teamsmembers.js deleted file mode 100644 index dd364510..00000000 --- a/src/app/services/teamsmembers.js +++ /dev/null @@ -1,96 +0,0 @@ -const sequelize = require('sequelize'); - -const { Op } = sequelize; - -module.exports = (Model) => { - const removeMembers = (member) => Model.teamsmembers.destroy({ where: { user: { [Op.eq]: member } } }); - - const getTeamsAdminById = (idTeam) => Model.teams.findOne({ where: { id: { [Op.eq]: idTeam } } }); - - const getMembersByIdTeam = (idTeam) => Model.teamsmembers.findAll({ where: { id_team: { [Op.eq]: idTeam } } }); - - const getInvitationsByIdTeam = (idTeam) => - Model.teamsinvitations.findAll({ where: { id_team: { [Op.eq]: idTeam } } }); - - const getPeople = async (idTeam) => { - const result = []; - const members = await getMembersByIdTeam(idTeam); - const invitations = await getInvitationsByIdTeam(idTeam); - members.forEach((m) => result.push({ isMember: true, isInvitation: false, user: m.user })); - invitations.forEach((m) => result.push({ isMember: false, isInvitation: true, user: m.user })); - return result; - }; - - const getMemberByIdTeam = (idTeam, email) => - Model.teamsmembers.findOne({ - where: { - id_team: { [Op.eq]: idTeam }, - user: { [Op.eq]: email }, - }, - }); - - const addTeamMember = (idTeam, userEmail, bridgePassword, bridgeMnemonic) => - Model.teamsmembers - .findOne({ - where: { - id_team: { [Op.eq]: idTeam }, - user: { [Op.eq]: userEmail }, - }, - }) - .then((teamMember) => - teamMember - ? null - : Model.teamsmembers.create({ - id_team: idTeam, - user: userEmail, - bridge_password: bridgePassword, - bridge_mnemonic: bridgeMnemonic, - }), - ); - - const saveMembersFromInvitations = (invitedMembers) => - new Promise((resolve, reject) => { - Model.teamsmembers - .findOne({ - where: { - user: { [Op.eq]: invitedMembers.user }, - id_team: { [Op.eq]: invitedMembers.id_team }, - bridge_password: { [Op.eq]: invitedMembers.bridge_password }, - bridge_mnemonic: { [Op.eq]: invitedMembers.bridge_mnemonic }, - }, - }) - .then((teamMember) => { - if (teamMember) { - reject(); - } - Model.teamsmembers - .create({ - id_team: invitedMembers.id_team, - user: invitedMembers.user, - bridge_password: invitedMembers.bridge_password, - bridge_mnemonic: invitedMembers.bridge_mnemonic, - }) - .then((newMember) => { - resolve(newMember); - }) - .catch((err) => { - reject(err); - }); - }) - .catch((err) => { - reject(err); - }); - }); - - return { - Name: 'TeamsMembers', - getMembersByIdTeam, - addTeamMember, - saveMembersFromInvitations, - getMemberByIdTeam, - getInvitationsByIdTeam, - getPeople, - removeMembers, - getTeamsAdminById, - }; -}; diff --git a/src/config/initializers/middleware.js b/src/config/initializers/middleware.js index 8389d130..309665ed 100644 --- a/src/config/initializers/middleware.js +++ b/src/config/initializers/middleware.js @@ -100,15 +100,6 @@ module.exports = (App, Config) => { }), ); - App.express.use( - '/api/teams/team-invitations', - rateLimit({ - windowMs: 30 * 60 * 1000, - max: 10, - keyGenerator: limiterKeyGenerator, - }), - ); - App.express.use( '/user/refresh', rateLimit({ diff --git a/src/config/pm2/dev.pm2.config.js b/src/config/pm2/dev.pm2.config.js deleted file mode 100644 index 2f40fbee..00000000 --- a/src/config/pm2/dev.pm2.config.js +++ /dev/null @@ -1,11 +0,0 @@ -module.exports = { - apps: [ - { - name: 'drive-server-dev', - script: './app.js', - env: { - NODE_ENV: 'development', - }, - }, - ], -}; diff --git a/src/config/pm2/inactivity-remove.pm2.config.js b/src/config/pm2/inactivity-remove.pm2.config.js deleted file mode 100644 index 522dcc5a..00000000 --- a/src/config/pm2/inactivity-remove.pm2.config.js +++ /dev/null @@ -1,11 +0,0 @@ -module.exports = { - apps: [ - { - name: 'inactivity notify', - script: './app/scripts/deleteInactiveAccounts.js', - env: { - NODE_ENV: 'staging', - }, - }, - ], -}; diff --git a/src/config/pm2/inactivity.pm2.config.js b/src/config/pm2/inactivity.pm2.config.js deleted file mode 100644 index ba1f92c9..00000000 --- a/src/config/pm2/inactivity.pm2.config.js +++ /dev/null @@ -1,11 +0,0 @@ -module.exports = { - apps: [ - { - name: 'inactivity notify', - script: './app/scripts/sendAccountDeletionMail.js', - env: { - NODE_ENV: 'staging', - }, - }, - ], -}; diff --git a/src/config/pm2/staging.pm2.config.js b/src/config/pm2/staging.pm2.config.js deleted file mode 100644 index 4b1c224b..00000000 --- a/src/config/pm2/staging.pm2.config.js +++ /dev/null @@ -1,11 +0,0 @@ -module.exports = { - apps: [ - { - name: 'drive-server', - script: './app.js', - env: { - NODE_ENV: 'staging', - }, - }, - ], -}; diff --git a/tests/controllers/auth.test.ts b/tests/controllers/auth.test.ts index 5b5f09a6..3c78d939 100644 --- a/tests/controllers/auth.test.ts +++ b/tests/controllers/auth.test.ts @@ -439,7 +439,6 @@ describe('Auth controller', () => { expect(services.User.GetUserBucket.calledOnce).to.be.true; expect(services.KeyServer.keysExists.calledOnce).to.be.true; expect(services.KeyServer.getKeys.calledOnce).to.be.true; - expect(services.Team.getTeamByMember.calledOnce).to.be.true; expect(services.AppSumo.GetDetails.calledOnce).to.be.true; expect(services.UsersReferrals.hasReferralsProgram.calledOnce).to.be.true; expect(jsonSpy.calledOnce).to.be.true; From 3fb7fca3592b8141a2db34b0f1bce678881be359 Mon Sep 17 00:00:00 2001 From: Sergio Gutierrez Villalba Date: Thu, 13 Jun 2024 11:14:33 +0200 Subject: [PATCH 2/2] fix(users): handle response status not existing on user check existence --- src/app/services/stripe.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/app/services/stripe.js b/src/app/services/stripe.js index 755bd8a1..14fa9af1 100644 --- a/src/app/services/stripe.js +++ b/src/app/services/stripe.js @@ -58,7 +58,7 @@ module.exports = () => { }); } catch (err) { - if (err.response.status !== 404) { + if (err.response?.status !== 404) { throw err; }