Get List of User with Permission - mongodb

I want to create a query which basically finds out the users with their privileges i.e if a user has a role - admin then want to see what privileges have this role and to whom this role is assigned

Use db.getUsers() command:
db.getUsers({ showCredentials: true })
Note, users are defined on a database, typically admin. So you would have to run
db.getSiblingDB("admin").getUsers({ showCredentials: true })
In case you need to scan all databases, you could use this one:
db.adminCommand({ listDatabases: 1, nameOnly: true }).databases.forEach(function (doc) {
db.getSiblingDB(doc.name).getUsers({ showCredentials: true }).forEach(function (user) {
printjson({ _id: user._id, user: user.user, db: user.db, roles: user.roles });
});
});
The privileges of a role you can get with db.getRoles(). Similar to db.getUsers() the roles could be defined in any database.
In general I don't see any reason to define users and roles in other database than admin - it makes your life much easier.

Related

In Mongoose I have User and Role schemas that have a one to many relationship. How to query if a particular User has the 'admin' role?

I have two collections in my Mongo DB: users and roles. A user can have many roles. Using Mongoose I want to find out whether a particular user (based on their id) has the admin role. How do I perform that query? In SQL one way of finding out would be to write this query:
SELECT *
FROM Users
INNER JOIN Roles ON Users.id = Roles.userID
WHERE (Users.id = <some user id> AND Roles.name='admin')
But I'm failing to see how the equivalent query is done using Mongoose. Below are my Mongoose schemas:
let RoleSchema = new Schema({
name: String,
owner: {
type: Schema.Types.ObjectId,
ref: "User"
}
})
export let Role = mongoose.model("Role", RoleSchema)
let userSchema = new Schema({
username: {
type: String,
unique: true,
required: true,
trim: true
},
roles: [
{
type: Schema.Types.ObjectId,
ref: "Role"
}
]
})
export let User = mongoose.model("User", userSchema)
Read - https://mongoosejs.com/docs/populate.html#query-conditions
User.
findById(id). // can also use find/findOne depending on your use-case
populate({
path: 'roles',
match: { name: 'admin' }
}).
exec();
This will fetch you User details and roles where name is admin.
You can check the user.roles array count to get the user is having admin role or not.

how to make mongo-express show all db?

here is my mongo-express config, when i login http://192.168.1.104:8081, it only shows the admin db, i want it to show all db. i had ran this command before
use admin
db.createUser(
{
user: "root",
pwd: "password",
roles: [ "root" ]
}
)
config file:
'use strict';
var url = require('url');
if (typeof process.env.MONGODB_PORT === 'string') {
var mongoConnection = url.parse(process.env.MONGODB_PORT);
process.env.ME_CONFIG_MONGODB_SERVER = mongoConnection.hostname;
process.env.ME_CONFIG_MONGODB_PORT = mongoConnection.port;
}
module.exports = {
mongodb: {
server: process.env.ME_CONFIG_MONGODB_SERVER || 'localhost',
port: process.env.ME_CONFIG_MONGODB_PORT || 27017,
//autoReconnect: automatically reconnect if connection is lost
autoReconnect: true,
//poolSize: size of connection pool (number of connections to use)
poolSize: 4,
//set admin to true if you want to turn on admin features
//if admin is true, the auth list below will be ignored
//if admin is true, you will need to enter an admin username/password below (if it is needed)
admin: true,
// >>>> If you are using regular accounts, fill out auth details in the section below
// >>>> If you have admin auth, leave this section empty and skip to the next section
auth: [
/*
* Add the the name, the username, and the password of the databases you want to connect to
* Add as many databases as you want!
{
database: 'test',
username: 'user',
password: 'pass'
}
*/
],
// >>>> If you are using an admin mongodb account, or no admin account exists, fill out section below
// >>>> Using an admin account allows you to view and edit all databases, and view stats
//leave username and password empty if no admin account exists
adminUsername: process.env.ME_CONFIG_MONGODB_ADMINUSERNAME || '',
adminPassword: process.env.ME_CONFIG_MONGODB_ADMINPASSWORD || '',
//whitelist: hide all databases except the ones in this list (empty list for no whitelist)
whitelist: [],
//blacklist: hide databases listed in the blacklist (empty list for no blacklist)
blacklist: []
},
site: {
host: '192.168.1.104',
port: 8081,
cookieSecret: process.env.ME_CONFIG_SITE_COOKIESECRET || 'cookiesecret',
sessionSecret: process.env.ME_CONFIG_SITE_SESSIONSECRET || 'sessionsecret',
cookieKeyName: 'mongo-express',
sslEnabled: process.env.ME_CONFIG_SITE_SSL_ENABLED || false,
sslCert: process.env.ME_CONFIG_SITE_SSL_CRT_PATH || '',
sslKey: process.env.ME_CONFIG_SITE_SSL_KEY_PATH || ''
},
//set useBasicAuth to true if you want to authehticate mongo-express loggins
//if admin is false, the basicAuthInfo list below will be ignored
//this will be true unless ME_CONFIG_BASICAUTH_USERNAME is set and is the empty string
useBasicAuth: process.env.ME_CONFIG_BASICAUTH_USERNAME !== '',
basicAuth: {
username: process.env.ME_CONFIG_BASICAUTH_USERNAME || 'root',
password: process.env.ME_CONFIG_BASICAUTH_PASSWORD || 'password'
},
options: {
//documentsPerPage: how many documents you want to see at once in collection view
documentsPerPage: 10,
//editorTheme: Name of the theme you want to use for displaying documents
//See http://codemirror.net/demo/theme.html for all examples
editorTheme: process.env.ME_CONFIG_OPTIONS_EDITORTHEME || 'rubyblue',
//The options below aren't being used yet
//cmdType: the type of command line you want mongo express to run
//values: eval, subprocess
// eval - uses db.eval. commands block, so only use this if you have to
// subprocess - spawns a mongo command line as a subprocess and pipes output to mongo express
cmdType: 'eval',
//subprocessTimeout: number of seconds of non-interaction before a subprocess is shut down
subprocessTimeout: 300,
//readOnly: if readOnly is true, components of writing are not visible.
readOnly: false
},
// Specify the default keyname that should be picked from a document to display in collections list.
// Keynames can be specified for every database and collection.
// If no keyname is specified, it defalts to '_id', which is a mandatory feild.
// For Example :
// defaultKeyNames{
// "world_db":{ //Database Name
// "continent":"cont_name", // collection:feild
// "country":"country_name",
// "city":"name"
// }
// }
defaultKeyNames: {
}
};
Remarks:
in above config,
basicAuth: {
username: process.env.ME_CONFIG_BASICAUTH_USERNAME || 'root',
password: process.env.ME_CONFIG_BASICAUTH_PASSWORD || 'password'
},
i changed the username, password to root and password repectively, when i access http://192.168.1.104:8081 , i need to enter root and password in http auth prompt so as i entering the mongo-express web panel.
This is my first answer on StackOverflow, but hopefully it's helpful.
Issue in your case seems to be database authentication defined in config.js.
You need to pass the db credentials through "auth" section and not through "basicAuth".
Also, once you correct the config.js file, start the mongo-express with -a switch, i.e. -> cd YOUR_PATH/node_modules/mongo-express/ && node app.js -a
Corrected section of config.js :
admin: true,
// >>>> If you are using regular accounts, fill out auth details in the section below
// >>>> If you have admin auth, leave this section empty and skip to the next section
auth: [
/*
* Add the the name, the username, and the password of the databases you want to connect to
* Add as many databases as you want!
{
database: 'test',
username: 'user',
password: 'pass'
}
*/
],
// >>>> If you are using an admin mongodb account, or no admin account exists, fill out section below
// >>>> Using an admin account allows you to view and edit all databases, and view stats
//leave username and password empty if no admin account exists
adminUsername: process.env.ME_CONFIG_MONGODB_ADMINUSERNAME || 'root',
adminPassword: process.env.ME_CONFIG_MONGODB_ADMINPASSWORD || 'password',

sails-permissions getting all permissions

I am trying to send all the permissions for an authenticated user via JSON from Sails.
My current code to find permissions for a single model type:
hasPermission: function hasPermission(req, res) {
var permitted = PermissionService.isAllowedToPerformAction({
method: req.param('method'),
model: sails.models[req.param('model')],
user: req.user
});
return res.json(200, { permitted: permitted });
}
This code doesn't work as isAllowedToPerformAction wants a single instance of a model. Is there a way to return a single JSON file accounting for all permissions?
Try creating roles and give them permissions.
Assign role to users
Ex.
PermissionService.createRole({
name: 'carsCategoryAdmin',
permissions: [
{ action: 'update', model: 'review', criteria: [{ where: { category: 'cars'}}]},
{ action: 'delete', model: 'review', criteria: [{ where: { category: 'cars'}}]}
],
users: ['venise']
})
You can examine the role and related permissions and users,
Role.find({name:'carsCategoryAdmin'})
.populate('users')
.populate('permissions')
.exec(console.log)
See more # sails-permissions-by-example
See how to get user permissions with code in comment given by skrichten on May 10, 2014 .

Authentication error (credentials missing in user document) in Mongo 3.0.1

I am having trouble with a basic user connection to my new Mongo setup.
The error looks like this in mongo.log:
authenticate db: a { authenticate: 1, user "u", nonce: "xxx", key: "xxx" }
Failed to authenticate u#a with mechanism MONGODB-CR:AuthenticationFailed MONGODB-CR credentials missing in user document
and here is my user setup
> use a
switched to db a
> show users
{
"_id":"a.u",
"user":"u",
"db":"a",
roles:[
{
"role":"readWrite",
"db":"a"
},
{
"role":"dbAdmin",
"db":"a"
}
]
}
Id user u has readWrite on database a, why is he being rejected? All the examples I found when googling where users that were created in the wrong db.
Thanks in advance.

How to change my mongoDB user password as non administrator?

I understand I can change a user's password by running db.changeUserPassword() as an MongoDB administrator. However, as a user with no administrator privilege, can I change my password just with my own account?
Thanks,
Although solution provided by Gergo worked. But I had to create a new role in order for it to work. I thought changeOwnPassword should be a built in privilege and not require additional admin work. Creating a dedicated role just for the purpose to be able to change user's own password is overkill in MongoDB.
If you have the necessary privileges, you can change your own password. You can verify that you have the necessary privileges by running this command:
db.runCommand(
{
usersInfo:"username",
showPrivileges:true
}
)
If it contains changeOwnPassword, then you can change the password:
db.runCommand(
{ updateUser: "username",
pwd: "password"
}
)
You can find more information in the MongoDB documentation.
In the admin database, create a new role with changeOwnPassword action.
use admin
db.createRole(
{ role: "changeOwnPasswordRole",
privileges: [
{
resource: { db: "", collection: ""},
actions: [ "changeOwnPassword" ]
}
],
roles: []
}
)
create a new user with changeOwnPasswordRole role and along with other roles
use test
db.createUser(
{
user:"user123",
pwd:"12345678",
roles:[ "readWrite", { role:"changeOwnPasswordRole", db:"admin" } ]
}
)
login the above user credentials
Use the below command to update own password
db.updateUser("user123",{pwd: "pass123"})