Skip to content

Feature: Add multi factor authentication #4345

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

Open
wants to merge 19 commits into
base: develop
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
97 changes: 97 additions & 0 deletions backend/internal/mfa.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,97 @@
const authModel = require('../models/auth');
const error = require('../lib/error');
const speakeasy = require('speakeasy');

module.exports = {
validateMfaTokenForUser: (userId, token) => {
return authModel
.query()
.where('user_id', userId)
.first()
.then((auth) => {
if (!auth || !auth.mfa_enabled) {
throw new error.AuthError('MFA is not enabled for this user.');
}
const verified = speakeasy.totp.verify({
secret: auth.mfa_secret,
encoding: 'base32',
token: token,
window: 2
});
if (!verified) {
throw new error.AuthError('Invalid MFA token.');
}
return true;
});
},
isMfaEnabledForUser: (userId) => {
return authModel
.query()
.where('user_id', userId)
.first()
.then((auth) => {
console.log(auth);
if (!auth) {
throw new error.AuthError('User not found.');
}
return auth.mfa_enabled === true;
});
},
createMfaSecretForUser: (userId) => {
const secret = speakeasy.generateSecret({ length: 20 });
console.log(secret);
return authModel
.query()
.where('user_id', userId)
.update({
mfa_secret: secret.base32
})
.then(() => secret);
},
enableMfaForUser: (userId, token) => {
return authModel
.query()
.where('user_id', userId)
.first()
.then((auth) => {
if (!auth || !auth.mfa_secret) {
throw new error.AuthError('MFA is not set up for this user.');
}
const verified = speakeasy.totp.verify({
secret: auth.mfa_secret,
encoding: 'base32',
token: token,
window: 2
});
if (!verified) {
throw new error.AuthError('Invalid MFA token.');
}
return authModel
.query()
.where('user_id', userId)
.update({ mfa_enabled: true })
.then(() => true);
});
},
disableMfaForUser: (data, userId) => {
return authModel
.query()
.where('user_id', userId)
.first()
.then((auth) => {
if (!auth) {
throw new error.AuthError('User not found.');
}
return auth.verifyPassword(data.secret)
.then((valid) => {
if (!valid) {
throw new error.AuthError('Invalid password.');
}
return authModel
.query()
.where('user_id', userId)
.update({ mfa_enabled: false, mfa_secret: null });
});
});
},
};
83 changes: 59 additions & 24 deletions backend/internal/token.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ const userModel = require('../models/user');
const authModel = require('../models/auth');
const helpers = require('../lib/helpers');
const TokenModel = require('../models/token');
const mfa = require('../internal/mfa'); // <-- added MFA import

const ERROR_MESSAGE_INVALID_AUTH = 'Invalid email or password';

Expand All @@ -21,6 +22,8 @@ module.exports = {
getTokenFromEmail: (data, issuer) => {
let Token = new TokenModel();

console.log(data);

data.scope = data.scope || 'user';
data.expiry = data.expiry || '1d';

Expand All @@ -41,34 +44,66 @@ module.exports = {
.then((auth) => {
if (auth) {
return auth.verifyPassword(data.secret)
.then((valid) => {
.then(async (valid) => {
if (valid) {

if (data.scope !== 'user' && _.indexOf(user.roles, data.scope) === -1) {
// The scope requested doesn't exist as a role against the user,
// you shall not pass.
throw new error.AuthError('Invalid scope: ' + data.scope);
}

// Create a moment of the expiry expression
let expiry = helpers.parseDatePeriod(data.expiry);
if (expiry === null) {
throw new error.AuthError('Invalid expiry time: ' + data.expiry);
}

return Token.create({
iss: issuer || 'api',
attrs: {
id: user.id
},
scope: [data.scope],
expiresIn: data.expiry
})
.then((signed) => {
return {
token: signed.token,
expires: expiry.toISOString()
};
return await mfa.isMfaEnabledForUser(user.id)
.then((mfaEnabled) => {
if (mfaEnabled) {
if (!data.mfa_token) {
throw new error.AuthError('MFA token required');
}
console.log(data.mfa_token);
return mfa.validateMfaTokenForUser(user.id, data.mfa_token)
.then((mfaValid) => {
if (!mfaValid) {
throw new error.AuthError('Invalid MFA token');
}
// Create a moment of the expiry expression
let expiry = helpers.parseDatePeriod(data.expiry);
if (expiry === null) {
throw new error.AuthError('Invalid expiry time: ' + data.expiry);
}

return Token.create({
iss: issuer || 'api',
attrs: {
id: user.id
},
scope: [data.scope],
expiresIn: data.expiry
})
.then((signed) => {
return {
token: signed.token,
expires: expiry.toISOString()
};
});
});
} else {
// Create a moment of the expiry expression
let expiry = helpers.parseDatePeriod(data.expiry);
if (expiry === null) {
throw new error.AuthError('Invalid expiry time: ' + data.expiry);
}

return Token.create({
iss: issuer || 'api',
attrs: {
id: user.id
},
scope: [data.scope],
expiresIn: data.expiry
})
.then((signed) => {
return {
token: signed.token,
expires: expiry.toISOString()
};
});
}
});
} else {
throw new error.AuthError(ERROR_MESSAGE_INVALID_AUTH);
Expand Down
3 changes: 2 additions & 1 deletion backend/internal/user.js
Original file line number Diff line number Diff line change
Expand Up @@ -507,7 +507,8 @@ const internalUser = {
.then((user) => {
return internalToken.getTokenFromUser(user);
});
}
},

};

module.exports = internalUser;
45 changes: 45 additions & 0 deletions backend/migrations/20250115041439_mfa_integeration.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
const migrate_name = 'identifier_for_migrate';
const logger = require('../logger').migrate;

/**
* Migrate
*
* @see http://knexjs.org/#Schema
*
* @param {Object} knex
* @param {Promise} Promise
* @returns {Promise}
*/
exports.up = function (knex/*, Promise*/) {

logger.info('[' + migrate_name + '] Migrating Up...');

return knex.schema.alterTable('auth', (table) => {
table.string('mfa_secret');
table.boolean('mfa_enabled').defaultTo(false);
})
.then(() => {
logger.info('[' + migrate_name + '] User Table altered');
logger.info('[' + migrate_name + '] Migrating Up Complete');
});
};

/**
* Undo Migrate
*
* @param {Object} knex
* @param {Promise} Promise
* @returns {Promise}
*/
exports.down = function (knex/*, Promise*/) {
logger.info('[' + migrate_name + '] Migrating Down...');

return knex.schema.alterTable('auth', (table) => {
table.dropColumn('mfa_key');
table.dropColumn('mfa_enabled');
})
.then(() => {
logger.info('[' + migrate_name + '] User Table altered');
logger.info('[' + migrate_name + '] Migrating Down Complete');
});
};
2 changes: 2 additions & 0 deletions backend/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -23,8 +23,10 @@
"node-rsa": "^1.0.8",
"objection": "3.0.1",
"path": "^0.12.7",
"qrcode": "^1.5.4",
"pg": "^8.13.1",
"signale": "1.4.0",
"speakeasy": "^2.0.0",
"sqlite3": "5.1.6",
"temp-write": "^4.0.0"
},
Expand Down
1 change: 1 addition & 0 deletions backend/routes/main.js
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ router.get('/', (req, res/*, next*/) => {

router.use('/schema', require('./schema'));
router.use('/tokens', require('./tokens'));
router.use('/mfa', require('./mfa'));
router.use('/users', require('./users'));
router.use('/audit-log', require('./audit-log'));
router.use('/reports', require('./reports'));
Expand Down
81 changes: 81 additions & 0 deletions backend/routes/mfa.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
const express = require('express');
const jwtdecode = require('../lib/express/jwt-decode');
const apiValidator = require('../lib/validator/api');
const schema = require('../schema');
const internalMfa = require('../internal/mfa');
const qrcode = require('qrcode');
const speakeasy = require('speakeasy');
const userModel = require('../models/user');

let router = express.Router({
caseSensitive: true,
strict: true,
mergeParams: true
});

router
.route('/create')
.post(jwtdecode(), (req, res, next) => {
if (!res.locals.access) {
return next(new Error('Invalid token'));
}
const userId = res.locals.access.token.getUserId();
internalMfa.createMfaSecretForUser(userId)
.then((secret) => {
return userModel.query()
.where('id', '=', userId)
.first()
.then((user) => {
if (!user) {
return next(new Error('User not found'));
}
return { secret, user };
});
})
.then(({ secret, user }) => {
const otpAuthUrl = speakeasy.otpauthURL({
secret: secret.ascii,
label: user.email,
issuer: 'Nginx Proxy Manager'
});
qrcode.toDataURL(otpAuthUrl, (err, dataUrl) => {
if (err) {
console.error('Error generating QR code:', err);
return next(err);
}
res.status(200).send({ qrCode: dataUrl });
});
})
.catch(next);
});

router
.route('/enable')
.post(jwtdecode(), (req, res, next) => {
apiValidator(schema.getValidationSchema('/mfa/enable', 'post'), req.body).then((params) => {
internalMfa.enableMfaForUser(res.locals.access.token.getUserId(), params.token)
.then(() => res.status(200).send({ success: true }))
.catch(next);
}
).catch(next);
});

router
.route('/check')
.get(jwtdecode(), (req, res, next) => {
internalMfa.isMfaEnabledForUser(res.locals.access.token.getUserId())
.then((active) => res.status(200).send({ active }))
.catch(next);
});

router
.route('/delete')
.delete(jwtdecode(), (req, res, next) => {
apiValidator(schema.getValidationSchema('/mfa/delete', 'delete'), req.body).then((params) => {
internalMfa.disableMfaForUser(params, res.locals.access.token.getUserId())
.then(() => res.status(200).send({ success: true }))
.catch(next);
}).catch(next);
});

module.exports = router;
Loading