Get linting passing again

This commit is contained in:
Jonathan Cremin 2016-06-06 15:37:00 +01:00
parent 4f95f27400
commit 494f66d388
21 changed files with 367 additions and 212 deletions

View file

@ -15,10 +15,10 @@ const router = new Router();
router.use(errors({
engine: 'ejs',
template: path.join(__dirname, 'public', 'error.html')
template: path.join(__dirname, 'public', 'error.html'),
}));
const statsdOpts = {prefix: 'hostr-web', host: process.env.STATSD_HOST};
const statsdOpts = { prefix: 'hostr-web', host: process.env.STATSD_HOST };
router.use(stats(statsdOpts));
const statsd = new StatsD(statsdOpts);
router.use(function* statsMiddleware(next) {
@ -41,7 +41,7 @@ router.use(function* stateMiddleware(next) {
router.use(csrf());
router.use(views(path.join(__dirname, 'views'), {
extension: 'ejs'
extension: 'ejs',
}));
router.get('/', index.main);
@ -75,7 +75,7 @@ router.get('/file/:id/:name', file.get);
router.get('/file/:size/:id/:name', file.get);
router.get('/files/:id/:name', file.get);
router.get('/download/:id/:name', function* downloadRedirect(id) {
this.redirect('/' + id);
this.redirect(`/${id}`);
});
router.get('/updaters/mac', function* macUpdater() {

View file

@ -2,12 +2,16 @@ import crypto from 'crypto';
import passwords from 'passwords';
import uuid from 'node-uuid';
import views from 'co-views';
const render = views(__dirname + '/../views', { default: 'ejs'});
import { join } from 'path';
const render = views(join(__dirname, '..', 'views'), { default: 'ejs' });
import debugname from 'debug';
const debug = debugname('hostr-web:auth');
import sendgridInit from 'sendgrid';
const sendgrid = sendgridInit(process.env.SENDGRID_KEY);
const from = process.env.EMAIL_FROM;
const fromname = process.env.EMAIL_NAME;
export function* authenticate(email, password) {
const Users = this.db.Users;
const Logins = this.db.Logins;
@ -17,30 +21,38 @@ export function* authenticate(email, password) {
debug('No password, or password too short');
return new Error('Invalid login details');
}
const count = yield Logins.count({ip: remoteIp, successful: false, at: { '$gt': Math.ceil(Date.now() / 1000) - 600}});
const count = yield Logins.count({
ip: remoteIp,
successful: false,
at: { $gt: Math.ceil(Date.now() / 1000) - 600 },
});
if (count > 25) {
debug('Throttling brute force');
return new Error('Invalid login details');
}
const login = {ip: remoteIp, at: Math.ceil(Date.now() / 1000), successful: null};
const login = { ip: remoteIp, at: Math.ceil(Date.now() / 1000), successful: null };
yield Logins.save(login);
const user = yield Users.findOne({email: email.toLowerCase(), banned: {'$exists': false}, status: {'$ne': 'deleted'}});
const user = yield Users.findOne({
email: email.toLowerCase(),
banned: { $exists: false }, status: { $ne: 'deleted' },
});
if (user) {
const verified = yield passwords.verify(password, user.salted_password);
if (verified) {
debug('Password verified');
login.successful = true;
yield Logins.updateOne({_id: login._id}, login);
yield Logins.updateOne({ _id: login._id }, login);
return user;
}
debug('Password invalid');
login.successful = false;
yield Logins.updateOne({_id: login._id}, login);
yield Logins.updateOne({ _id: login._id }, login);
} else {
debug('Email invalid');
login.successful = false;
yield Logins.updateOne({_id: login._id}, login);
yield Logins.updateOne({ _id: login._id }, login);
}
return new Error('Invalid login details');
}
@ -50,15 +62,17 @@ export function* setupSession(user) {
yield this.redis.set(token, user._id, 'EX', 604800);
const sessionUser = {
'id': user._id,
'email': user.email,
'dailyUploadAllowance': 15,
'maxFileSize': 20971520,
'joined': user.joined,
'plan': user.type || 'Free',
'uploadsToday': yield this.db.Files.count({owner: user._id, 'time_added': {'$gt': Math.ceil(Date.now() / 1000) - 86400}}),
'token': token,
'md5': crypto.createHash('md5').update(user.email).digest('hex'),
id: user._id,
email: user.email,
dailyUploadAllowance: 15,
maxFileSize: 20971520,
joined: user.joined,
plan: user.type || 'Free',
uploadsToday: yield this.db.Files.count({
owner: user._id, time_added: { $gt: Math.ceil(Date.now() / 1000) - 86400 },
}),
md5: crypto.createHash('md5').update(user.email).digest('hex'),
token,
};
if (sessionUser.plan === 'Pro') {
@ -70,8 +84,8 @@ export function* setupSession(user) {
if (this.request.body.remember && this.request.body.remember === 'on') {
const Remember = this.db.Remember;
const rememberToken = uuid();
Remember.save({_id: rememberToken, 'user_id': user.id, created: new Date().getTime()});
this.cookies.set('r', rememberToken, { maxAge: 1209600000, httpOnly: true});
Remember.save({ _id: rememberToken, user_id: user.id, created: new Date().getTime() });
this.cookies.set('r', rememberToken, { maxAge: 1209600000, httpOnly: true });
}
debug('Session set up');
}
@ -79,36 +93,38 @@ export function* setupSession(user) {
export function* signup(email, password, ip) {
const Users = this.db.Users;
const existingUser = yield Users.findOne({email: email, status: {'$ne': 'deleted'}});
const existingUser = yield Users.findOne({ email, status: { $ne: 'deleted' } });
if (existingUser) {
debug('Email already in use.');
throw new Error('Email already in use.');
}
const cryptedPassword = yield passwords.crypt(password);
const user = {
email: email,
'salted_password': cryptedPassword,
email,
salted_password: cryptedPassword,
joined: Math.round(new Date().getTime() / 1000),
'signup_ip': ip,
signup_ip: ip,
activationCode: uuid(),
};
Users.insertOne(user);
const html = yield render('email/inlined/activate', {activationUrl: process.env.WEB_BASE_URL + '/activate/' + user.activationCode});
const html = yield render('email/inlined/activate', {
activationUrl: `${process.env.WEB_BASE_URL}/activate/${user.activationCode}`,
});
const text = `Thanks for signing up to Hostr!
Please confirm your email address by clicking the link below.
${process.env.WEB_BASE_URL + '/activate/' + user.activationCode}
${process.env.WEB_BASE_URL}/activate/${user.activationCode}
Jonathan Cremin, Hostr Founder
`;
const mail = new sendgrid.Email({
to: user.email,
from: 'jonathan@hostr.co',
fromname: 'Jonathan from Hostr',
html: html,
text: text,
subject: 'Welcome to Hostr',
from,
fromname,
html,
text,
});
mail.addCategory('activate');
sendgrid.send(mail);
@ -118,25 +134,27 @@ ${process.env.WEB_BASE_URL + '/activate/' + user.activationCode}
export function* sendResetToken(email) {
const Users = this.db.Users;
const Reset = this.db.Reset;
const user = yield Users.findOne({email: email});
const user = yield Users.findOne({ email });
if (user) {
const token = uuid.v4();
Reset.save({
'_id': user._id,
'token': token,
'created': Math.round(new Date().getTime() / 1000),
_id: user._id,
created: Math.round(new Date().getTime() / 1000),
token,
});
const html = yield render('email/inlined/forgot', {
forgotUrl: `${process.env.WEB_BASE_URL}/forgot/${token}`,
});
const html = yield render('email/inlined/forgot', {forgotUrl: process.env.WEB_BASE_URL + '/forgot/' + token});
const text = `It seems you've forgotten your password :(
Visit ${process.env.WEB_BASE_URL + '/forgot/' + token} to set a new one.
Visit ${process.env.WEB_BASE_URL}/forgot/${token} to set a new one.
`;
const mail = new sendgrid.Email({
to: user.email,
from: 'jonathan@hostr.co',
fromname: 'Jonathan from Hostr',
html: html,
text: text,
subject: 'Hostr Password Reset',
html,
text,
});
mail.addCategory('password-reset');
sendgrid.send(mail);
@ -149,36 +167,36 @@ Visit ${process.env.WEB_BASE_URL + '/forgot/' + token} to set a new one.
export function* fromToken(token) {
const Users = this.db.Users;
const reply = yield this.redis.get(token);
return yield Users.findOne({_id: reply});
return yield Users.findOne({ _id: reply });
}
export function* fromCookie(cookie) {
const Remember = this.db.Remember;
const Users = this.db.Users;
const remember = yield Remember.findOne({_id: cookie});
return yield Users.findOne({_id: remember.user_id});
const remember = yield Remember.findOne({ _id: cookie });
return yield Users.findOne({ _id: remember.user_id });
}
export function* validateResetToken() {
const Reset = this.db.Reset;
return yield Reset.findOne({token: this.params.token});
return yield Reset.findOne({ token: this.params.token });
}
export function* updatePassword(userId, password) {
const Users = this.db.Users;
const cryptedPassword = yield passwords.crypt(password);
yield Users.updateOne({_id: userId}, {'$set': {'salted_password': cryptedPassword}});
yield Users.updateOne({ _id: userId }, { $set: { salted_password: cryptedPassword } });
}
export function* activateUser(code) {
const Users = this.db.Users;
const user = yield Users.findOne({activationCode: code});
const user = yield Users.findOne({ activationCode: code });
if (user) {
Users.updateOne({_id: user._id}, {'$unset': {activationCode: ''}});
Users.updateOne({ _id: user._id }, { $unset: { activationCode: '' } });
yield setupSession.call(this, user);
return true;
}

View file

@ -1,10 +1,16 @@
import path from 'path';
import { join } from 'path';
import mime from 'mime-types';
import hostrFileStream from '../../lib/hostr-file-stream';
import { formatFile } from '../../lib/format';
const storePath = process.env.UPLOAD_STORAGE_PATH;
const referrerRegexes = [
/^https:\/\/hostr.co/,
/^https:\/\/localhost.hostr.co/,
/^http:\/\/localhost:4040/,
];
function userAgentCheck(userAgent) {
if (!userAgent) {
return false;
@ -12,34 +18,45 @@ function userAgentCheck(userAgent) {
return userAgent.match(/^(wget|curl|vagrant)/i);
}
function referrerCheck(referrer) {
return referrer && referrerRegexes.some((regex) => referrer.match(regex));
}
function hotlinkCheck(file, userAgent, referrer) {
return !userAgentCheck(userAgent) && !file.width && (!referrer || !(referrer.match(/^https:\/\/hostr.co/) || referrer.match(/^http:\/\/localhost:4040/)));
return userAgentCheck(userAgent) || file.width || referrerCheck(referrer);
}
export function* get() {
const file = yield this.db.Files.findOne({_id: this.params.id, 'file_name': this.params.name, 'status': 'active'});
const file = yield this.db.Files.findOne({
_id: this.params.id,
file_name: this.params.name,
status: 'active',
});
this.assert(file, 404);
if (hotlinkCheck(file, this.headers['user-agent'], this.headers.referer)) {
return this.redirect('/' + file._id);
if (!hotlinkCheck(file, this.headers['user-agent'], this.headers.referer)) {
this.redirect(`/${file._id}`);
return;
}
if (!file.width && this.request.query.warning !== 'on') {
return this.redirect('/' + file._id);
this.redirect(`/${file._id}`);
return;
}
if (file.malware) {
const alert = this.request.query.alert;
if (!alert || !alert.match(/i want to download malware/i)) {
return this.redirect('/' + file._id);
this.redirect(`/${file._id}`);
return;
}
}
let localPath = path.join(storePath, file._id[0], file._id + '_' + file.file_name);
let remotePath = path.join(file._id[0], file._id + '_' + file.file_name);
let localPath = join(storePath, file._id[0], `${file._id}_${file.file_name}`);
let remotePath = join(file._id[0], `${file._id}_${file.file_name}`);
if (this.params.size > 0) {
localPath = path.join(storePath, file._id[0], this.params.size, file._id + '_' + file.file_name);
remotePath = path.join(file._id[0], this.params.size, file._id + '_' + file.file_name);
localPath = join(storePath, file._id[0], this.params.size, `${file._id}_${file.file_name}`);
remotePath = join(file._id[0], this.params.size, `${file._id}_${file.file_name}`);
}
if (file.malware) {
@ -57,7 +74,7 @@ export function* get() {
}
if (userAgentCheck(this.headers['user-agent'])) {
this.set('Content-Disposition', 'attachment; filename=' + file.file_name);
this.set('Content-Disposition', `attachment; filename=${file.file_name}`);
}
this.set('Content-type', type);
@ -66,10 +83,9 @@ export function* get() {
if (!this.params.size || (this.params.size && this.params.size > 150)) {
this.db.Files.updateOne(
{'_id': file._id},
{'$set': {'last_accessed': Math.ceil(Date.now() / 1000)}, '$inc': {downloads: 1}},
{'w': 0}
);
{ _id: file._id },
{ $set: { last_accessed: Math.ceil(Date.now() / 1000) }, $inc: { downloads: 1 } },
{ w: 0 });
}
this.body = yield hostrFileStream(localPath, remotePath);
@ -80,14 +96,15 @@ export function* resized() {
}
export function* landing() {
const file = yield this.db.Files.findOne({_id: this.params.id, status: 'active'});
const file = yield this.db.Files.findOne({ _id: this.params.id, status: 'active' });
this.assert(file, 404);
if (userAgentCheck(this.headers['user-agent'])) {
this.params.name = file.file_name;
return yield get.call(this);
yield get.call(this);
return;
}
this.statsd.incr('file.landing', 1);
const formattedFile = formatFile(file);
yield this.render('file', {file: formattedFile});
yield this.render('file', { file: formattedFile });
}

View file

@ -4,12 +4,13 @@ import auth from '../lib/auth';
export function* main() {
if (this.session.user) {
if (this.query['app-token']) {
return this.redirect('/');
this.redirect('/');
return;
}
const token = uuid.v4();
yield this.redis.set(token, this.session.user.id, 'EX', 604800);
this.session.user.token = token;
yield this.render('index', {user: this.session.user});
yield this.render('index', { user: this.session.user });
} else {
if (this.query['app-token']) {
const user = yield auth.fromToken(this, this.query['app-token']);
@ -30,26 +31,26 @@ export function* staticPage(next) {
const token = uuid.v4();
yield this.redis.set(token, this.session.user.id, 'EX', 604800);
this.session.user.token = token;
yield this.render('index', {user: this.session.user});
yield this.render('index', { user: this.session.user });
} else {
switch (this.originalUrl) {
case '/terms':
yield this.render('terms');
break;
case '/privacy':
yield this.render('privacy');
break;
case '/pricing':
yield this.render('pricing');
break;
case '/apps':
yield this.render('apps');
break;
case '/stats':
yield this.render('index', {user: {}});
break;
default:
yield next;
case '/terms':
yield this.render('terms');
break;
case '/privacy':
yield this.render('privacy');
break;
case '/pricing':
yield this.render('pricing');
break;
case '/apps':
yield this.render('apps');
break;
case '/stats':
yield this.render('index', { user: {} });
break;
default:
yield next;
}
}
}

View file

@ -1,13 +1,13 @@
import path from 'path';
import views from 'co-views';
const render = views(path.join(__dirname, '/../views'), { default: 'ejs'});
const render = views(path.join(__dirname, '/../views'), { default: 'ejs' });
import Stripe from 'stripe';
const stripe = new Stripe(process.env.STRIPE_SECRET_KEY);
import sendgridInit from 'sendgrid';
const sendgrid = sendgridInit(process.env.SENDGRID_KEY);
const fromEmail = process.env.EMAIL_FROM;
const fromName = process.env.EMAIL_NAME;
const from = process.env.EMAIL_FROM;
const fromname = process.env.EMAIL_NAME;
export function* create() {
const Users = this.db.Users;
@ -26,10 +26,11 @@ export function* create() {
delete customer.subscriptions;
yield Users.updateOne({_id: this.session.user.id}, {'$set': {'stripe_customer': customer, type: 'Pro'}});
yield Users.updateOne({ _id: this.session.user.id },
{ $set: { stripe_customer: customer, type: 'Pro' } });
const transaction = {
'user_id': this.session.user.id,
user_id: this.session.user.id,
amount: customer.subscription.plan.amount,
desc: customer.subscription.plan.name,
date: new Date(customer.subscription.plan.created * 1000),
@ -38,7 +39,7 @@ export function* create() {
yield Transactions.insertOne(transaction);
this.session.user.plan = 'Pro';
this.body = {status: 'active'};
this.body = { status: 'active' };
const html = yield render('email/inlined/pro');
const text = `Hey, thanks for upgrading to Hostr Pro!
@ -50,11 +51,11 @@ export function* create() {
const mail = new sendgrid.Email({
to: this.session.user.email,
from: fromEmail,
fromname: fromName,
html: html,
text: text,
subject: 'Hostr Pro',
from,
fromname,
html,
text,
});
mail.addCategory('pro-upgrade');
sendgrid.send(mail);
@ -63,16 +64,17 @@ export function* create() {
export function* cancel() {
this.assertCSRF();
const Users = this.db.Users;
const user = yield Users.findOne({_id: this.session.user.id});
const user = yield Users.findOne({ _id: this.session.user.id });
const confirmation = yield stripe.customers.cancelSubscription(
user.stripe_customer.id,
user.stripe_customer.subscription.id,
{ 'at_period_end': true }
{ at_period_end: true }
);
yield Users.updateOne({_id: this.session.user.id}, {'$set': {'stripe_customer.subscription': confirmation, type: 'Free'}});
yield Users.updateOne({ _id: this.session.user.id },
{ $set: { 'stripe_customer.subscription': confirmation, type: 'Free' } });
this.session.user.plan = 'Pro';
this.body = {status: 'inactive'};
this.body = { status: 'inactive' };
}

View file

@ -1,10 +1,14 @@
import { authenticate, setupSession, signup as signupUser, activateUser, sendResetToken, validateResetToken, updatePassword } from '../lib/auth';
import {
authenticate, setupSession, signup as signupUser, activateUser, sendResetToken,
validateResetToken, updatePassword,
} from '../lib/auth';
import debugname from 'debug';
const debug = debugname('hostr-web:user');
export function* signin() {
if (!this.request.body.email) {
return yield this.render('signin', {csrf: this.csrf});
yield this.render('signin', { csrf: this.csrf });
return;
}
this.statsd.incr('auth.attempt', 1);
@ -12,9 +16,14 @@ export function* signin() {
const user = yield authenticate.call(this, this.request.body.email, this.request.body.password);
if (!user) {
this.statsd.incr('auth.failure', 1);
return yield this.render('signin', {error: 'Invalid login details', csrf: this.csrf});
yield this.render('signin', { error: 'Invalid login details', csrf: this.csrf });
return;
} else if (user.activationCode) {
return yield this.render('signin', {error: 'Your account hasn\'t been activated yet. Check your for an activation email.', csrf: this.csrf});
yield this.render('signin', {
error: 'Your account hasn\'t been activated yet. Check your for an activation email.',
csrf: this.csrf,
});
return;
}
this.statsd.incr('auth.success', 1);
yield setupSession.call(this, user);
@ -24,16 +33,22 @@ export function* signin() {
export function* signup() {
if (!this.request.body.email) {
return yield this.render('signup', {csrf: this.csrf});
yield this.render('signup', { csrf: this.csrf });
return;
}
this.assertCSRF(this.request.body);
if (this.request.body.email !== this.request.body.confirm_email) {
return yield this.render('signup', {error: 'Emails do not match.', csrf: this.csrf});
yield this.render('signup', { error: 'Emails do not match.', csrf: this.csrf });
return;
} else if (this.request.body.email && !this.request.body.terms) {
return yield this.render('signup', {error: 'You must agree to the terms of service.', csrf: this.csrf});
yield this.render('signup', { error: 'You must agree to the terms of service.',
csrf: this.csrf });
return;
} else if (this.request.body.password && this.request.body.password.length < 7) {
return yield this.render('signup', {error: 'Password must be at least 7 characters long.', csrf: this.csrf});
yield this.render('signup', { error: 'Password must be at least 7 characters long.',
csrf: this.csrf });
return;
}
const ip = this.headers['x-real-ip'] || this.ip;
const email = this.request.body.email;
@ -41,10 +56,15 @@ export function* signup() {
try {
yield signupUser.call(this, email, password, ip);
} catch (e) {
return yield this.render('signup', {error: e.message, csrf: this.csrf});
yield this.render('signup', { error: e.message, csrf: this.csrf });
return;
}
this.statsd.incr('auth.signup', 1);
return yield this.render('signup', {message: 'Thanks for signing up, we\'ve sent you an email to activate your account.', csrf: ''});
yield this.render('signup', {
message: 'Thanks for signing up, we\'ve sent you an email to activate your account.',
csrf: '',
});
return;
}
@ -55,14 +75,19 @@ export function* forgot() {
if (this.request.body.password) {
if (this.request.body.password.length < 7) {
return yield this.render('forgot', {error: 'Password needs to be at least 7 characters long.', token: token, csrf: this.csrf});
yield this.render('forgot', {
error: 'Password needs to be at least 7 characters long.',
csrf: this.csrf,
token,
});
return;
}
this.assertCSRF(this.request.body);
const tokenUser = yield validateResetToken.call(this, token);
const userId = tokenUser._id;
yield updatePassword.call(this, userId, this.request.body.password);
yield Reset.deleteOne({_id: userId});
const user = yield Users.findOne({_id: userId});
yield Reset.deleteOne({ _id: userId });
const user = yield Users.findOne({ _id: userId });
yield setupSession.call(this, user);
this.statsd.incr('auth.reset.success', 1);
this.redirect('/');
@ -70,28 +95,40 @@ export function* forgot() {
const tokenUser = yield validateResetToken.call(this, token);
if (!tokenUser) {
this.statsd.incr('auth.reset.fail', 1);
return yield this.render('forgot', {error: 'Invalid password reset token. It might be expired, or has already been used.', token: null, csrf: this.csrf});
yield this.render('forgot', {
error: 'Invalid password reset token. It might be expired, or has already been used.',
csrf: this.csrf,
token: null,
});
return;
}
return yield this.render('forgot', {token: token, csrf: this.csrf});
yield this.render('forgot', { csrf: this.csrf, token });
return;
} else if (this.request.body.email) {
this.assertCSRF(this.request.body);
try {
const email = this.request.body.email;
yield sendResetToken.call(this, email);
this.statsd.incr('auth.reset.request', 1);
return yield this.render('forgot', {message: 'We\'ve sent an email with a link to reset your password. Be sure to check your spam folder if you it doesn\'t appear within a few minutes', token: null, csrf: this.csrf});
yield this.render('forgot', {
message: `We've sent an email with a link to reset your password.
Be sure to check your spam folder if you it doesn't appear within a few minutes`,
csrf: this.csrf,
token: null,
});
return;
} catch (error) {
debug(error);
}
} else {
yield this.render('forgot', {token: null, csrf: this.csrf});
yield this.render('forgot', { csrf: this.csrf, token: null });
}
}
export function* logout() {
this.statsd.incr('auth.logout', 1);
this.cookies.set('r', {expires: new Date(1), path: '/'});
this.cookies.set('r', { expires: new Date(1), path: '/' });
this.session = null;
this.redirect('/');
}