mirror of
https://github.com/NginxProxyManager/nginx-proxy-manager.git
synced 2025-10-06 12:50:10 +00:00
Merge 34194e65d2
into 3a01b2c84f
This commit is contained in:
@@ -313,6 +313,9 @@ const internalCertificate = {
|
||||
.where('is_deleted', 0)
|
||||
.andWhere('id', data.id)
|
||||
.allowGraph('[owner]')
|
||||
.allowGraph('[proxy_hosts]')
|
||||
.allowGraph('[redirection_hosts]')
|
||||
.allowGraph('[dead_hosts]')
|
||||
.first();
|
||||
|
||||
if (access_data.permission_visibility !== 'all') {
|
||||
@@ -464,6 +467,9 @@ const internalCertificate = {
|
||||
.where('is_deleted', 0)
|
||||
.groupBy('id')
|
||||
.allowGraph('[owner]')
|
||||
.allowGraph('[proxy_hosts]')
|
||||
.allowGraph('[redirection_hosts]')
|
||||
.allowGraph('[dead_hosts]')
|
||||
.orderBy('nice_name', 'ASC');
|
||||
|
||||
if (access_data.permission_visibility !== 'all') {
|
||||
|
76
backend/internal/mfa.js
Normal file
76
backend/internal/mfa.js
Normal file
@@ -0,0 +1,76 @@
|
||||
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);
|
||||
});
|
||||
},
|
||||
};
|
@@ -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';
|
||||
|
||||
@@ -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';
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
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);
|
||||
}
|
||||
|
||||
// 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()
|
||||
};
|
||||
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);
|
||||
|
@@ -507,7 +507,8 @@ const internalUser = {
|
||||
.then((user) => {
|
||||
return internalToken.getTokenFromUser(user);
|
||||
});
|
||||
}
|
||||
},
|
||||
|
||||
};
|
||||
|
||||
module.exports = internalUser;
|
||||
|
45
backend/migrations/20250115041439_mfa_integeration.js
Normal file
45
backend/migrations/20250115041439_mfa_integeration.js
Normal file
@@ -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');
|
||||
});
|
||||
};
|
@@ -4,7 +4,6 @@
|
||||
const db = require('../db');
|
||||
const helpers = require('../lib/helpers');
|
||||
const Model = require('objection').Model;
|
||||
const User = require('./user');
|
||||
const now = require('./now_helper');
|
||||
|
||||
Model.knex(db);
|
||||
@@ -68,6 +67,11 @@ class Certificate extends Model {
|
||||
}
|
||||
|
||||
static get relationMappings () {
|
||||
const ProxyHost = require('./proxy_host');
|
||||
const DeadHost = require('./dead_host');
|
||||
const User = require('./user');
|
||||
const RedirectionHost = require('./redirection_host');
|
||||
|
||||
return {
|
||||
owner: {
|
||||
relation: Model.HasOneRelation,
|
||||
@@ -79,6 +83,39 @@ class Certificate extends Model {
|
||||
modify: function (qb) {
|
||||
qb.where('user.is_deleted', 0);
|
||||
}
|
||||
},
|
||||
proxy_hosts: {
|
||||
relation: Model.HasManyRelation,
|
||||
modelClass: ProxyHost,
|
||||
join: {
|
||||
from: 'certificate.id',
|
||||
to: 'proxy_host.certificate_id'
|
||||
},
|
||||
modify: function (qb) {
|
||||
qb.where('proxy_host.is_deleted', 0);
|
||||
}
|
||||
},
|
||||
dead_hosts: {
|
||||
relation: Model.HasManyRelation,
|
||||
modelClass: DeadHost,
|
||||
join: {
|
||||
from: 'certificate.id',
|
||||
to: 'dead_host.certificate_id'
|
||||
},
|
||||
modify: function (qb) {
|
||||
qb.where('dead_host.is_deleted', 0);
|
||||
}
|
||||
},
|
||||
redirection_hosts: {
|
||||
relation: Model.HasManyRelation,
|
||||
modelClass: RedirectionHost,
|
||||
join: {
|
||||
from: 'certificate.id',
|
||||
to: 'redirection_host.certificate_id'
|
||||
},
|
||||
modify: function (qb) {
|
||||
qb.where('redirection_host.is_deleted', 0);
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
|
@@ -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"
|
||||
},
|
||||
|
@@ -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'));
|
||||
|
89
backend/routes/mfa.js
Normal file
89
backend/routes/mfa.js
Normal file
@@ -0,0 +1,89 @@
|
||||
const express = require('express');
|
||||
const jwtdecode = require('../lib/express/jwt-decode');
|
||||
const apiValidator = require('../lib/validator/api');
|
||||
const internalToken = require('../internal/token');
|
||||
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('/')
|
||||
.options((_, res) => {
|
||||
res.sendStatus(204);
|
||||
})
|
||||
|
||||
.get(async (req, res, next) => {
|
||||
internalToken.getFreshToken(res.locals.access, {
|
||||
expiry: (typeof req.query.expiry !== 'undefined' ? req.query.expiry : null),
|
||||
scope: (typeof req.query.scope !== 'undefined' ? req.query.scope : null)
|
||||
})
|
||||
.then((data) => {
|
||||
res.status(200)
|
||||
.send(data);
|
||||
})
|
||||
.catch(next);
|
||||
});
|
||||
|
||||
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', 'post'), req.body).then((params) => {
|
||||
internalMfa.enableMfaForUser(res.locals.access.token.getUserId(), params.token)
|
||||
.then(() => res.status(200).send({ success: true }))
|
||||
.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);
|
||||
});
|
||||
|
||||
module.exports = router;
|
41
backend/schema/paths/mfa/post.json
Normal file
41
backend/schema/paths/mfa/post.json
Normal file
@@ -0,0 +1,41 @@
|
||||
{
|
||||
"operationId": "enableMfa",
|
||||
"summary": "Enable multi-factor authentication for a user",
|
||||
"tags": ["MFA"],
|
||||
"requestBody": {
|
||||
"description": "MFA Token Payload",
|
||||
"required": true,
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"type": "object",
|
||||
"additionalProperties": false,
|
||||
"properties": {
|
||||
"token": {
|
||||
"type": "string",
|
||||
"minLength": 1
|
||||
}
|
||||
},
|
||||
"required": ["token"]
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"responses": {
|
||||
"200": {
|
||||
"description": "MFA enabled successfully",
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"success": {
|
||||
"type": "boolean"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
@@ -22,6 +22,10 @@
|
||||
"secret": {
|
||||
"minLength": 1,
|
||||
"type": "string"
|
||||
},
|
||||
"mfa_token": {
|
||||
"minLength": 1,
|
||||
"type": "string"
|
||||
}
|
||||
},
|
||||
"required": ["identity", "secret"],
|
||||
|
@@ -14,7 +14,7 @@
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"type": "object",
|
||||
"additionalProperties": false,
|
||||
"additionalProperties": true,
|
||||
"required": ["name", "nickname", "email"],
|
||||
"properties": {
|
||||
"name": {
|
||||
|
@@ -15,6 +15,11 @@
|
||||
"$ref": "./paths/get.json"
|
||||
}
|
||||
},
|
||||
"/mfa": {
|
||||
"post": {
|
||||
"$ref": "./paths/mfa/post.json"
|
||||
}
|
||||
},
|
||||
"/audit-log": {
|
||||
"get": {
|
||||
"$ref": "./paths/audit-log/get.json"
|
||||
|
2160
backend/yarn.lock
2160
backend/yarn.lock
File diff suppressed because it is too large
Load Diff
Reference in New Issue
Block a user