Fixed bug that prevented migrations from succeeding

Added scaffolding required for jwt authentication for certain routes

Added logger to auth_api

Added necessary routing rules for multi-user mode

Registration is now possible
This commit is contained in:
Isaac Grynsztein
2020-04-24 21:03:00 -04:00
parent c3cc28540f
commit 98f1d003c3
5 changed files with 245 additions and 50 deletions

View File

@@ -1,7 +1,7 @@
var async = require('async');
const { uuid } = require('uuidv4');
var fs = require('fs-extra');
var auth = require('./authentication/auth');
var auth_api = require('./authentication/auth');
var winston = require('winston');
var path = require('path');
var youtubedl = require('youtube-dl');
@@ -63,6 +63,7 @@ const logger = winston.createLogger({
config_api.setLogger(logger);
subscriptions_api.setLogger(logger);
auth_api.setLogger(logger);
// var GithubContent = require('github-content');
@@ -154,7 +155,7 @@ app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
// use passport
app.use(auth.passport.initialize());
app.use(auth_api.passport.initialize());
// objects
@@ -218,6 +219,7 @@ async function runFilesToDBMigration() {
db.set('files_to_db_migration_complete', true).write();
resolve(true);
} catch(err) {
logger.error(err);
resolve(false);
}
});
@@ -635,7 +637,7 @@ function getMp3s() {
var url = jsonobj.webpage_url;
var uploader = jsonobj.uploader;
var upload_date = jsonobj.upload_date;
upload_date = `${upload_date.substring(0, 4)}-${upload_date.substring(4, 6)}-${upload_date.substring(6, 8)}`;
upload_date = upload_date ? `${upload_date.substring(0, 4)}-${upload_date.substring(4, 6)}-${upload_date.substring(6, 8)}` : null;
var size = stats.size;
@@ -664,7 +666,7 @@ function getMp4s(relative_path = true) {
var url = jsonobj.webpage_url;
var uploader = jsonobj.uploader;
var upload_date = jsonobj.upload_date;
upload_date = `${upload_date.substring(0, 4)}-${upload_date.substring(4, 6)}-${upload_date.substring(6, 8)}`;
upload_date = upload_date ? `${upload_date.substring(0, 4)}-${upload_date.substring(4, 6)}-${upload_date.substring(6, 8)}` : null;
var thumbnail = jsonobj.thumbnail;
var duration = jsonobj.duration;
@@ -1659,6 +1661,14 @@ app.use(function(req, res, next) {
app.use(compression());
const optionalJwt = function (req, res, next) {
const multiUserMode = config_api.getConfigItem('ytdl_multi_user_mode');
if (multiUserMode && req.query.jwt) {
return auth_api.passport.authenticate('jwt', { session: false })(req, res, next);
}
return next();
};
app.get('/api/config', function(req, res) {
let config_file = config_api.getConfigFile();
res.send({
@@ -1781,19 +1791,21 @@ app.post('/api/fileStatusMp4', function(req, res) {
});
// gets all download mp3s
app.get('/api/getMp3s', function(req, res) {
const multiUserMode = config_api.getConfigItem('ytdl_multi_user_mode');
app.get('/api/getMp3s', optionalJwt, function(req, res) {
var mp3s = db.get('files.audio').value(); // getMp3s();
var playlists = db.get('playlists.audio').value();
if (req.query.jwt && multiUserMode) {
const is_authenticated = req.isAuthenticated();
if (is_authenticated) {
// mp3s = db.get
auth_api.passport.authenticate('jwt')
mp3s = auth_api.getUserVideos()
} else {
res.send({
mp3s: mp3s,
playlists: playlists
});
}
res.send({
mp3s: mp3s,
playlists: playlists
});
res.end("yes");
});
@@ -2537,11 +2549,18 @@ app.get('/api/audio/:id', function(req , res){
// user authentication
app.post('/api/auth/register'
, auth.registerUser);
, auth_api.registerUser);
app.post('/api/auth/login'
, auth.passport.authenticate('local', {})
, auth.generateJWT
, auth.returnAuthResponse
, auth_api.passport.authenticate('local', {})
, auth_api.passport.authorize('local')
, auth_api.generateJWT
, auth_api.returnAuthResponse
);
app.post('/api/auth/jwtAuth'
, auth_api.passport.authenticate('jwt', { session: false })
, auth_api.passport.authorize('jwt')
, auth_api.generateJWT
, auth_api.returnAuthResponse
);
app.use(function(req, res, next) {

View File

@@ -11,11 +11,13 @@ db.defaults(
var LocalStrategy = require('passport-local').Strategy;
var JwtStrategy = require('passport-jwt').Strategy,
ExtractJwt = require('passport-jwt').ExtractJwt;
var opts = {}
opts.jwtFromRequest = ExtractJwt.fromUrlQueryParameter('jwt');
opts.secretOrKey = 'secret';
opts.issuer = 'example.com';
opts.audience = 'example.com';
// other required vars
let logger = null;
exports.setLogger = function(input_logger) {
logger = input_logger;
}
/*************************
* Authentication module
@@ -27,7 +29,19 @@ var jwt = require('jsonwebtoken');
const JWT_EXPIRATION = (60 * 60); // one hour
const { uuid } = require('uuidv4');
const SERVER_SECRET = uuid();
let SERVER_SECRET = null;
if (db.get('jwt_secret').value()) {
SERVER_SECRET = db.get('jwt_secret').value();
} else {
SERVER_SECRET = uuid();
db.set('jwt_secret', SERVER_SECRET).write();
}
var opts = {}
opts.jwtFromRequest = ExtractJwt.fromUrlQueryParameter('jwt');
opts.secretOrKey = SERVER_SECRET;
/*opts.issuer = 'example.com';
opts.audience = 'example.com';*/
exports.passport = require('passport');
var BasicStrategy = require('passport-http').BasicStrategy;
@@ -50,33 +64,42 @@ exports.registerUser = function(req, res) {
bcrypt.hash(plaintextPassword, saltRounds)
.then(function(hash) {
let new_user = {
name: username,
uid: userid,
passhash: hash,
files: {
audio: [],
video: []
}
};
// check if user exists
if (db.get('users').find({uid: userid}).value()) {
// user id is taken!
logger.error('Registration failed: UID is already taken!');
res.status(409).send('UID is already taken!');
} else if (db.get('users').find({name: username}).value()) {
// user name is taken!
logger.error('Registration failed: User name is already taken!');
res.status(409).send('User name is already taken!');
} else {
// add to db
db.get('users').push({
name: username,
uid: userid,
passhash: hash
}).write();
db.get('users').push(new_user).write();
logger.verbose(`New user created: ${new_user.name}`);
res.send({
user: new_user
});
}
})
.then(function(result) {
res.send('registered');
})
.catch(function(err) {
logger.error(err);
if( err.code == 'ER_DUP_ENTRY' ) {
res.status(409).send('UserId already taken');
} else {
console.log('failed TO register User');
// res.writeHead(500, {'Content-Type':'text/plain'});
res.end(err);
res.sendStatus(409);
}
});
}
@@ -93,7 +116,7 @@ exports.registerUser = function(req, res) {
* If so, passes the user info to the next middleware.
************************************************/
exports.passport.use(new JwtStrategy(opts, function(jwt_payload, done) {
const user = db.get('users').find({uid: jwt_payload.sub}).value();
const user = db.get('users').find({uid: jwt_payload.user.uid}).value();
if (user) {
return done(null, user);
} else {
@@ -107,7 +130,7 @@ exports.passport.use(new LocalStrategy({
passwordField: 'password'},
function(username, password, done) {
const user = db.get('users').find({name: username}).value();
if (!user) { return done(null, false); }
if (!user) { console.log('user not found'); return done(null, false); }
if (user) {
return done(null, bcrypt.compareSync(password, user.passhash) ? user : false);
}
@@ -200,8 +223,9 @@ exports.ensureAuthenticatedElseError = function(req, res, next) {
// video stuff
exports.getUserVideos(type) {
exports.getUserVideos = function(uid, type) {
const user = db.get('users').find({uid: uid}).value();
return user['files'][type];
}
function getToken(queryParams) {