Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Validation #397

Open
wants to merge 7 commits into
base: master
Choose a base branch
from
Open
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
2 changes: 1 addition & 1 deletion config/passport.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
/** UNFINISHED **/
/* UNFINISHED */
/* eslint-disable no-unused-vars */

const passport = require('passport');
Expand Down
77 changes: 58 additions & 19 deletions controllers/backend/account.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
/** UNFINISHED **/
/* UNFINISHED */
/* eslint-disable no-unused-vars */

const express = require("express"); // JSDoc types only
const bluebird = require('bluebird');
const Promise = require('bluebird');
const crypto = bluebird.promisifyAll(require('crypto'));
Expand All @@ -15,6 +16,7 @@ const mv = require('mv');
const fs = require('fs-extra');
const mkdirp = Promise.promisifyAll(require('mkdirp'));
const randomstring = require('randomstring');

const mailJet = require('../../lib/emails/mailjet');
const sendgrid = require('../../lib/emails/sendgrid');

Expand Down Expand Up @@ -49,8 +51,8 @@ const recaptcha = new reCAPTCHA({
secretKey : process.env.RECAPTCHA_SECRETKEY
});

const { b2 } = require('../../lib/uploading/backblaze');
const pagination = require('../../lib/helpers/pagination');
// const { b2 } = require('../../lib/uploading/backblaze');
// const pagination = require('../../lib/helpers/pagination');

// where to send users to after login
const redirectUrl = '/account';
Expand Down Expand Up @@ -110,28 +112,41 @@ exports.postLogin = async(req, res, next) => {
};

/**
* POST /signup
* `POST` `/signup`
*
* Create a new local account.
*
* TODO: write tests for it.
* @param {express.Request} req
* @param {express.Response} res
* @param {express.NextFunction} next
*/
exports.postSignup = async(req, res, next) => {
exports.postSignup = async (req, res, next) => {

// CAPTCHA VALIDATION
if(process.env.NODE_ENV == 'production' && process.env.RECAPTCHA_ON == 'true'){
if (process.env.NODE_ENV == 'production' && process.env.RECAPTCHA_ON == 'true') {

try {
const response = await recaptcha.validate(req.body['g-recaptcha-response']);
} catch(err){
req.flash('errors', { msg: 'Captcha failed, please try again' });
return res.redirect('/signup');
}

}

/** assertion testing the data **/
/* assertion testing the data */
// req.assert('email', 'Email is not valid').isEmail();
req.assert('password', 'Password must be at least 4 characters long').len(4);
req.assert('password', 'Password must be at least 4 characters long').len({min: 4});
req.assert('confirmPassword', 'Passwords do not match').equals(req.body.password);
// req.assert('channelName', 'Channel name must be entered').notEmpty();
req.assert('channelUrl', 'Channel username must be entered').notEmpty();
req.assert('channelUrl', 'Channel username must be between 3 and 25 characters.').len(3,25);
req.assert('channelUrl', 'Channel username must be entered')
.notEmpty()
.len({ min: 3, max: 25 }).withMessage("Channel username must be between 3 and 25 characters.")

/* Data sanitization */
req.sanitize("channelUrl").trim();
req.sanitize("channelUrl").escape();

console.log(req.body.channelUrl + ' <--- inputted channelUrl for' + req.body.email);
// console.log(req.body.grecaptcha.getResponse('captcha'));
Expand All @@ -158,9 +173,9 @@ exports.postSignup = async(req, res, next) => {
});

// make sure first user is admin, can refactor later
const numberOfUsers = await User.countDocuments();
const randomUser = await User.findOne();

if(numberOfUsers == 0){
if(!randomUser){
user.role = 'admin';
user.plan = 'plus';
user.privs.unlistedUpload = true;
Expand Down Expand Up @@ -200,13 +215,17 @@ exports.postSignup = async(req, res, next) => {
};

/**
* POST /account/profile
* `POST` `/account/profile`
*
* Update profile information.
*
* @param {express.Request} req
* @param {express.Response} res
* @param {express.NextFunction} next
*/

exports.postUpdateProfile = async(req, res, next) => {

if(!req.user && req.body.uploadToken){
if (!req.user && req.body.uploadToken) {
req.user = await User.findOne({ uploadToken : req.body.uploadToken });
}

Expand All @@ -215,7 +234,16 @@ exports.postUpdateProfile = async(req, res, next) => {

console.log(`UPDATING PROFILE FOR ${req.user && req.user.channelUrl}`);

/* Data validation */
req.assert("channelName", "Channel name must be between 3 to 25 characters long").len({ min: 3, max: 25 });
req.assert("description", "Description can be 500 characters long at best").len({ max: 500 });

/* Data sanitization */
req.sanitize('email').normalizeEmail({ gmail_remove_dots: false });
req.sanitize("channelName").trim();
req.sanitize("channelName").escape();
req.sanitize("description").trim();
req.sanitize("description").escape();

const errors = req.validationErrors();

Expand Down Expand Up @@ -253,6 +281,7 @@ exports.postUpdateProfile = async(req, res, next) => {
const channelUrlFolder = `${saveAndServeFilesDirectory}/${req.user.channelUrl}`;

// make the directory if it doesnt exist
// @ts-expect-error
await mkdirp.mkdirpAsync(channelUrlFolder);

// save the file
Expand All @@ -267,7 +296,9 @@ exports.postUpdateProfile = async(req, res, next) => {
req.user.customThumbnail = `user-thumbnail${fileExtension}`;

// if no channel name is given, save it as the channel url
req.user.channelName = req.body.channelName ? req.body.channelName : req.user.channelUrl;
req.user.channelName = req.body.channelName
? req.body.channelName
: req.user.channelUrl;

req.user.channelDescription = req.body.description;

Expand Down Expand Up @@ -380,8 +411,12 @@ exports.postReset = async(req, res, next) => {
};

/**
* POST /forgot
* `POST` `/forgot`
*
* Create a random token, then the send user an email with a reset link.
* @param {express.Request} req
* @param {express.Response} res
* @param {express.NextFunction} next
*/
exports.postForgot = async(req, res, next) => {

Expand Down Expand Up @@ -444,8 +479,12 @@ exports.postForgot = async(req, res, next) => {
};

/**
* POST /account/email
* `POST` `/account/email`
*
* Create a random token, then the send user an email with a confirmation link
* @param {express.Request} req
* @param {express.Response} res
* @param {express.NextFunction} next
*/
exports.postConfirmEmail = async(req, res, next) => {

Expand Down Expand Up @@ -541,4 +580,4 @@ exports.postImporter = async(req, res) => {
uniqueTag,
channelUrl
});
};
};
53 changes: 35 additions & 18 deletions controllers/backend/internalApi.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
/** UNFINISHED **/
/* UNFINISHED */
/* eslint-disable no-unused-vars */

const express = require("express"); // JSDoc types only
const bluebird = require('bluebird');
const Promise = require('bluebird');
const request = bluebird.promisifyAll(require('request'), { multiArgs: true });
Expand Down Expand Up @@ -51,18 +52,20 @@ const frontendServer = process.env.FRONTEND_SERVER || '';
const createNotification = require('../../lib/helpers/notifications');

// models
const Upload = require('../../models/index').Upload;
const User = require('../../models/index').User;
const Comment = require('../../models/index').Comment;
const React = require('../../models/index').React;
const Subscription = require('../../models/index').Subscription;
const Notification = require('../../models/index').Notification;
const CreditAction = require('../../models/index').CreditAction;
const Report = require('../../models/index').Report;
const LastWatchedTime = require('../../models/index').LastWatchedTime;
const PushEndpoint = require('../../models/index').PushEndpoint;
const PushSubscription = require('../../models/index').PushSubscription;
const EmailSubscription = require('../../models/index').EmailSubscription;
const {
Upload,
User,
Comment,
React,
Subscription,
Notification,
CreditAction,
Report,
LastWatchedTime,
PushEndpoint,
PushSubscription,
EmailSubscription,
} = require('../../models/index');

const getMediaType = require('../../lib/uploading/media');
const pushNotificationLibrary = require('../../lib/mediaPlayer/pushNotification');
Expand Down Expand Up @@ -95,7 +98,7 @@ if(process.env.NODE_ENV !== 'production' && !process.env.UPLOAD_SERVER){
async function updateUsersUnreadSubscriptions(user){
const subscriptions = await Subscription.find({ subscribedToUser: user._id, active: true });

for(const subscription of subscriptions){
for (const subscription of subscriptions) {
let subscribingUser = await User.findOne({ _id: subscription.subscribingUser });

subscribingUser.unseenSubscriptionUploads = subscribingUser.unseenSubscriptionUploads + 1;
Expand Down Expand Up @@ -779,8 +782,11 @@ exports.deleteComment = async(req, res) => {
};

/**
* POST /api/comment
* `POST` `/api/comment`
*
* List of API examples.
* @param {express.Request} req
* @param {express.Response} res
*/
exports.postComment = async(req, res) => {

Expand All @@ -793,6 +799,19 @@ exports.postComment = async(req, res) => {
return res.send('failed to post comment');
}

/* Data validation */
req.assert("comment", "The comment shoould have between 2 to 250 characters").len({ min: 2, max: 250 });

/* Data sanitization */
req.sanitize("comment").trim();
req.sanitize("comment").escape();

const errors = req.validationErrors();

if(errors){
return res.status(422).json(errors);
}

try {

// note: this functionality is kind of crappy so turning it off
Expand Down Expand Up @@ -891,14 +910,12 @@ exports.postComment = async(req, res) => {
res.json(responseObject);

// res.send('success')
}
catch(err){
} catch(err) {

console.log(err);

res.status(500);
res.send('failed to post comment');

}

};
Expand Down
Loading