Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 0 additions & 9 deletions lib/core/users/usecase.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,6 @@ import { EventBus, EventBusEvents } from '../../server/eventBus';
import { FramesRepository } from '../frames/Repository';
import { BasicUser, User } from './User';

const disposable = require('disposable-email');

function isEmailValid(email: string) {
// RFC 5322 Official Standard
// eslint-disable-next-line no-control-regex
Expand Down Expand Up @@ -144,13 +142,6 @@ export class UsersUsecase {
throw new InvalidDataFormatError('Invalid email address provided');
}

const emailDomain = emailMatch[2];
const allowedEmail = disposable.validate(emailDomain);

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is a filter for spammy emails, why do you remove it?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@sg-gs it wasn't working in prod, so instead of keeping a useless lib that adds tech debt every time axios has a vulnerability, I removed it.

I could've added a dependency-free library that actually works, but suddenly enabling a filter that hasn't worked in prod for a long time could start blocking signups that work today. This check could fit better in drive-server, where we have more control and visibility.


if (!allowedEmail) {
throw new InvalidDataFormatError('Invalid email address provided');
}

const maybeAlreadyExistentUser = await this.usersRepository.findByEmail(email);
const userAlreadyExists = !!maybeAlreadyExistentUser;

Expand Down
24 changes: 0 additions & 24 deletions lib/server/http/users/controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ import { Logger } from 'winston';

import {
InvalidDataFormatError,
UserAlreadyExistsError,
UserNotFoundError,
UsersUsecase
} from '../../../core';
Expand All @@ -16,29 +15,6 @@ export class HTTPUsersController {
private logger: Logger
) {}

async createUser(req: Request<{}, {}, { email?: string, password?: string }, {}>, res: Response) {
if (!req.body || !req.body.email || !req.body.password) {
return res.status(400).send();
}

const { email, password } = req.body;

try {
const user = await this.usersUsecase.createUser(email.toLowerCase().trim(), password);

res.status(200).send(user);
} catch (err) {
if (err instanceof UserAlreadyExistsError || err instanceof InvalidDataFormatError) {
res.status(400).send({ message: err.message });
} else {
// TODO: Global middleware for 500
this.logger.error('Error creating user %s: %s. %s', email, (err as Error).message, (err as Error).stack);

res.status(500).send({ message: 'Internal Server Error' });
}
}
}

async resetPassword(
req: Request<{ token?: string }, {}, { password?: string }>,
res: Response
Expand Down
2 changes: 0 additions & 2 deletions lib/server/http/users/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,6 @@ export const createUsersHTTPRouter = (
): Router => {
const router = Router();

router.post('/', controller.createUser.bind(controller));

router.post('/:id/request-password-reset', controller.requestPasswordReset.bind(controller));
router.post('/confirm-password-reset/:token', controller.resetPassword.bind(controller));

Expand Down
181 changes: 0 additions & 181 deletions lib/server/routes/users.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,14 +4,11 @@ const Router = require('./index');
const rawbody = require('../middleware/raw-body');
const log = require('../../logger');
const errors = require('../error-types');
const merge = require('merge');
const inherits = require('util').inherits;
const authenticate = require('../middleware/authenticate');
const crypto = require('crypto');
const limiter = require('../limiter').DEFAULTS;
const rateLimiter = require('../middleware/rate-limiter');
const disposable = require('disposable-email');
const { trackUserActivated } = require('../../analytics');
const url = require('url');
const sendGridMail = require('@sendgrid/mail');

Expand Down Expand Up @@ -86,183 +83,6 @@ UsersRouter.prototype._dispatchActivationEmail = function (user, redir, cb) {
callback(null);
};

/**
* Sends a delayed activation email with optional `url` for beta signup
* @private
*/
UsersRouter.prototype._dispatchDelayedActivationEmail = function (user, cb) {
let self = this;
self.mailer.dispatchSendGrid(
user.email,
'delayed-activation',
{},
function (err) {
if (err) {
log.error(
'failed to send signup throttling email, reason: %s',
err.message
);
cb(err);
} else {
cb(null);
}
}
);
};

/**
* Sends an activation email based on configuration options
* @private
*/
UsersRouter.prototype._dispatchActivationEmailSwitch = function (user, cb) {
if (this.config.application.delayedActivation) {
this._dispatchDelayedActivationEmail(user, cb);
} else {
this._dispatchActivationEmail(user, cb);
}
};

/**
* Registers a new user
* @param {http.IncomingMessage} req
* @param {http.ServerResponse} res
* @param {Function} next
*/
UsersRouter.prototype.createUser = async function (req, res, next) {
const self = this;
const User = this.storage.models.User;

if (!req.body.email) {
return next(new errors.BadRequestError('Not valid email address'));
}

if (!req.body.password) {
return next(new errors.BadRequestError('Not valid password'));
}

// Ensure email address is lowercase & trimmed to avoid future search errors
req.body.email = req.body.email.toLowerCase().trim();

// Check if email address if valid.
// RFC 5322 Official Standard
// eslint-disable-next-line no-control-regex
const emailPattern =
/^((?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*|'(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21\x23-\x5b\x5d-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])*'))@((?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21-\x5a\x53-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])+)\]))$/;
const match = req.body.email.match(emailPattern);

if (!match) {
return next(new errors.BadRequestError('Not valid email address'));
}

// Check if disposable email
const emailDomain = match[2];
const allowedEmail = disposable.validate(emailDomain);

if (!allowedEmail) {
log.error('User %s is a fake email', req.body.email);

return next(new errors.BadRequestError('Not valid email address provider'));
}

// Register
log.debug('registering user account for %s', req.body.email);


try {
const user = await User.create({
email: req.body.email,
password: req.body.password,
maxSpaceBytes: 1024 * 1024 * 1024 * 1,
activated: true,
});

trackUserActivated(user.uuid, req.body.email);
self._dispatchAndCreatePubKey(user, req, res, next);
} catch (err) {
return next(err);
}
};

/**
* Dispatch activation email and create pubkey if none
* @param {Object} user
* @param {http.IncomingMessage} req
* @param {http.ServerResponse} res
* @param {Function} next
*/
UsersRouter.prototype._dispatchAndCreatePubKey = async function (
user,
req,
res,
next
) {
const self = this;
const PublicKey = this.storage.models.PublicKey;

if (!req.body.pubkey) {
self._dispatchActivationEmailSwitch(user, function (err) {
if (err) {
log.error('failed to send deactivation email, reason: %s', err.message);
}
});

return res.status(201).send(user.toObject());
}

PublicKey.create(user, req.body.pubkey, async function (err, pubkey) {
if (err) {
await user.deleteOne();

return next(new errors.BadRequestError(err.message));
}

// NB: Don't send activation email, send beta list email
// NB: Send email explaining why they cant activate yet
self._dispatchActivationEmailSwitch(user, function (err) {
if (err) {
log.error('failed to send deactivation email, reason: %s', err.message);
}
});

res.status(201).send(
merge(user.toObject(), {
pubkey: pubkey.key,
})
);
});
};

/**
* Creates user with opts object, does extra logic involved
* @param {http.IncomingMessage} req
* @param {http.ServerResponse} res
* @param {Function} next
*/
UsersRouter.prototype._createUserWithOpts = async function (req, res, next) {
const self = this;
const User = this.storage.models.User;
const Partner = this.storage.models.Partner;
const opts = {
email: req.body.email,
password: req.body.password,
};

try {
const partner = await Partner.findOne({ name: req.body.referralPartner });
opts.referralPartner = partner ? partner.id : null;

User.create(opts, function (err, user) {
if (err) {
return next(err);
}

self._dispatchAndCreatePubKey(user, req, res, next);
});
} catch (err) {
return next(err);
}
};

/**
* Confirms a user account
* @param {http.IncomingMessage} req
Expand Down Expand Up @@ -519,7 +339,6 @@ UsersRouter.prototype.confirmDestroyUserStripe = async function (req, res, next)
*/
UsersRouter.prototype._definitions = function () {
return [
['POST', '/users', this.getLimiter(limiter(5)), rawbody, this.createUser],
[
'POST',
'/activations',
Expand Down
1 change: 0 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -109,7 +109,6 @@
"commander": "8.3.0",
"concat-stream": "^1.6.2",
"cors": "^2.8.5",
"disposable-email": "internxt/disposable#v0.2.6",
"express": "^4.17.1",
"hat": "0.0.3",
"helmet": "^3.20.0",
Expand Down
11 changes: 0 additions & 11 deletions tests/lib/core/users/usecase.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -129,17 +129,6 @@ describe('Users usecases', () => {
}));
});

// it(`Should reject a disposable email`, async () => {
// const disposableEmail = 'e@bel.kr';

// try {
// await usecase.createUser(disposableEmail, fakeUser.password);
// expect(true).toBeFalsy();
// } catch (err) {
// expect(err).toBeInstanceOf(InvalidDataFormatError);
// }
// });

it(`Should reject if the user already exists`, async () => {
stub(usersRepository, 'findByEmail').resolves(fakeUser);

Expand Down
Loading
Loading