Created
March 8, 2020 04:12
-
-
Save marantz/52b6d003179b90e35aaa41e375da18fd to your computer and use it in GitHub Desktop.
MongoDB Add User Client Source
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Remove Duplicates | |
function removeDuplicates(array) { | |
return array.sort().filter((a, b) => array.indexOf(a) === b) | |
}; | |
// Add CIDR Address on User | |
addUserClientSource = function(user,dbname,cidr) { | |
var nsAdmin = "admin." + user; | |
var res = db.system.users.aggregate([ | |
{$match:{"_id" : nsAdmin, "user" : user, "db" : dbname}}, | |
{$project:{_id:0,"authenticationRestrictions.clientSource":1}}, | |
{$addFields:{ | |
clientSource:{ | |
$reduce:{ | |
input:"$authenticationRestrictions.clientSource", | |
initialValue:[], | |
in: { $concatArrays : ["$$value", "$$this"] } | |
} | |
} | |
}}, | |
{$project:{"authenticationRestrictions":0}} | |
]) | |
if ( ! res._batch ) { | |
printStackTrace(); | |
throw "User not found: " + tojson(res); | |
} | |
var ipList = res._batch[0]; | |
if(!ipList.clientSource){ | |
ipList.clientSource=[cidr] | |
} else { | |
ipList.clientSource.push(cidr) | |
} | |
var uniqList = removeDuplicates(ipList.clientSource); | |
//Remove | |
//print( "ipList " + JSON.stringify( ipList ) ) | |
//isRemove = isRemove ? true : false; | |
//uniqList = uniqList.filter(item => item !== cidr) | |
db.updateUser( user,{authenticationRestrictions: [ {clientSource:uniqList} ]}) | |
var results = db.getSiblingDB("admin").runCommand( { usersInfo: user, showPrivileges: true, showAuthenticationRestrictions: true } ).users[0].authenticationRestrictions | |
print( user + " Add " + JSON.stringify( results ) ) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment