Mongodb authentication using MongoCredential - mongodb

I have a grails application in which Im using db.authenticate for a login page but I understand this method has been deprecated and therefore I would like to upgrade my application to using the MongoCredential object for authentication. However, unlike the db.authenticate which nicely returns a boolean to get authentication done, the MongoCredential doesn't return a boolean so how can I go about accomplishing the code replacement with minimal headache. Ideally, I'd like to derive some kind of a boolean to tell me if authentication was achieved. Thanks for your patience. Im a newbie with Mongodb.
This is part of the code I need to replace which currently makes use of the deprecated method "authenticate":
MongoClient mongoClient = new MongoClient("localhost", 27017)
DB db = mongoClient.getDB("twcdb");
def userName = params.username
def passWord = params.password
//deprecated method being used in the line below.
boolean auth = db.authenticate(userName, passWord.toCharArray())
if (auth) {
userloggedin = params.username
render(contentType: 'text/json') {
[success: true, url: createLink(controller: 'admin', action: 'loggedin')]
}
}
else {
render(contentType: 'text/json') {
["success": false, "message": 'Login or Password is incorrect.']
}
Edit: I know that the answer must lie in testing a property of the MongoClient object somehow to see if it contains a valid authenticated connection but I am still stuck on how to do this. Given I knowingly feed the MongoClient constructor with a bogus MongoCredential, it still creates an object that isn't null. I was betting on the null test but no joy. So, how do I replace the deprecated db.authenticate?

Related

Proper way to cleanup a mongo db() reference?

I'm making a multi tenant app using mongo db and would like to know what the proper procedure between switching between databases is. I know I can get a new reference to a database using the db() command:
const client = await MongoClient.connect(url);
client.mainDb = client.db('main');
app.set('mongoClient', client);
On bootup I get and store a reference to my main for all my global app data. Then each request also passes in a tenant id. I'm using Feathersjs which provides me with a hook for every request before and after.
In my before hook, I get a reference to the clients data and store it to be used during that singular request:
app.hooks({
before: {
all: [(context) => {
// Run before all API requests
const tenant = context.params?.query?.$tenant;
const tenantDbName = ... // some logic to query the tenant db name
const client = context.app.get('mongoClient');
context.params.tenantDb = client.db(tenantDbName);
}]
}
}
After the request, I'm unclear on if I should do anything to cleanup the connection. Do I just let the garbage collector clean it up since its request that was made which has ended? Or is there a function in Mongo to clean it up?
app.hooks({
after: {
all: [(context) => {
// Cleanup DB or reset connection?
context.params.tenantDb = null;
}]
}
}
I just need to ensure that the next request doesn't use a previous requests database as this could serve them other users data.

Having Trouble Initializing Postgresql Database Through PG-Promise

I'm completely new to Express/Postgresql and I'm trying to learn them to create a web application. After some poking around, I decided that I wanted to develop my back-end with TypeScript. I successfully converted all my other files from JavaScript to TypeScript, but I still can't figure out how to initialize the pg-promise connection in TypeScript!
I've been trying to follow the TypeScript guidelines in this link here. https://github.com/vitaly-t/pg-promise/tree/master/typescript
// Initialize the PostGres database conneciton for use throughout
the entire application
import {IMain, IDatabase} from 'pg-promise';
import * as pgPromise from 'pg-promise';
const pgp: IMain = pgPromise({
query(e: any) {
console.log('QUERY RESULT:', e.query);
},
receive(data: any, result: any, e: any) {
console.log(`DATA FROM QUERY ${e.query} WAS RECEIVED.`);
}
});
const connection: any = {
host: 'localhost',
port: 5432,
database: 'RushHub',
user: 'RyanArifin',
password: null
}
const db: IDatabase<any> = pgp(connection);
export {
db
};
I currently am getting the error "TS2349: Cannot invoke an expression whose type lacks a call signature. Type 'typeof pgPromise' has no compatible call signatures." This error is coming from when I try to set my initialization options. Any help would be appreciated, thanks!
This is standard TypeScript configuration flag - esModuleInterop. When set to true, the import syntax is import pgPromise from 'pg-promise';, and when false, which is the default, the syntax is import * as pgPromise from 'pg-promise';.
The library gives you example for the default TypeScript configuration.

"Not authorized on ___ to execute command" with mLab + MongoDB ^3.0

Connects without a hitch, but on insert() throws me this error.
var MongoClient = require('mongodb').MongoClient;
const assert = require('assert');
var url = 'mongodb://____:____#ds125565.mlab.com:25565/heroku_w268n9pj';
MongoClient.connect(url, function(err, client) {
assert.equal(null, err);
db = client.db('temp');
console.log("connected!");
const collection = db.collection('temp');
collection.insert([{
something: please
}
});
I saw some other answers regarding mLab accounts and credentials, but I just created a new admin account for this. Frustrating because it was working previously with v2.3.
When attempting to connect to an mlab database, you have to correctly specify the client. It's located at the end of your connection string, just after the final forward slash.
mlab_url = "mongodb://db_user_name:db_password#ds139725.mlab.com:39725/heroku_sd1fp182?retryWrites=false"
client = MongoClient(url)
db = client["heroku_sd1fp182"]
collection = db["coinHack"]
You may also get the error:
This MongoDB deployment does not support retryable writes. Please add retryWrites=false to your connection string.
Just add "?retryWrites=false" to your connection string, as shown above.

How to generate password policy based password in OIM 11gr2ps2

I am creating a event handler to modify user password using OIM UserManager API. But now I need to consider password policy and then generate new password that is compatible with the password policy defined in OIM.
Can you please point to some APIs and Methods which can help here?
import oracle.idm.common.ipf.api.password.RandomPasswordGenerator;
import oracle.idm.common.ipf.api.password.RandomPasswordGeneratorImpl;
The classes above actually gives handle on the randomly generated password that I was looking for. The code below shows the implementation for the same.
PasswordPolicyInfo passwordPolicyInfo = ((PasswordMgmtService)Platform.getService(PasswordMgmtService.class)).getApplicablePasswordPolicy(entityId, Boolean.valueOf(false));
RandomPasswordGenerator randomPasswordGenerator = new RandomPasswordGeneratorImpl();
OimPasswordPolicy policy = new OimPasswordPolicy(Utils.getIpfPasswordPolicyInfoVO(passwordPolicyInfo));
policy.setId(passwordPolicyInfo.getId());
policy.setName(passwordPolicyInfo.getName());
char[] generatedPassword = randomPasswordGenerator.generatePassword(policy, null);
Alternatively by using below OIM API's,you can generate password and also validate it against any policy in OIM:
import oracle.iam.passwordmgmt.api.PasswordMgmtService;
import oracle.iam.passwordmgmt.domain.generator.RandomPasswordGeneratorImpl;
Here is the snippet:
RandomPasswordGeneratorImpl randomPasswordGenerator = new RandomPasswordGeneratorImpl();
UserRepository userRepository = new DBUserRepository();
UserInfo usrInfo = userRepository.getUserAndManagerInfo(usrLogin);
String generatedPassword = new String(randomPasswordGenerator.generatePassword(Utils.getUser(usrInfo)));
PasswordMgmtService passMgmt = Platform.getService(PasswordMgmtService.class);
ValidationResult result = passMgmt.validatePasswordAgainstPolicy(generatedPassword.toCharArray(), Utils.getUser(usrInfo), Locale.getDefault());
You can use PasswordMgmtService api provided by OIM.
You can use below method in you password generation logic in your event handler code.
PasswordPolicyDescription getApplicablePasswordPolicyDescription(java.lang.String userID)
In the PasswordPolicyDescription object you have all properties which were configured while creating Password Policy.

How to correctly authorize into Mongo server using Scala?

I have added authorization to my Mongo database and now I can't perform any queries whats so ever.
Every time I try I get:
reactivemongo.core.commands.DefaultCommandError: BSONCommandError['command failed because the 'ok' field is missing or equals 0'] with original doc {
ok: BSONDouble(0.0),
errmsg: BSONString(unauthorized)
}
And my Authorization bit seams to be alright but it is just not doing the job:
private val driver = new MongoDriver(actorSystem)
private val dbName = "myDatabase"
private val userName = "root"
private val password = "pass"
private val credentials = Seq(Authenticate(dbName, userName, password))
private val connection = driver.connection(List("111.111.111.11"), credentials)
//connection.authenticate(dbName, userName, password)
private val db = connection(dbName)
The user credentials were created
Any ideas on what is wrong here?
Apparently unauthorized means not that I has not logged in it means that the user does not have sufficient permissions or Roles as they are grouped in Mongo.
Some tutorials about adding authorization have skipped that part er go I get to relearn the lesson of reading an official documentation of any resource again...
http://docs.mongodb.org/manual/reference/method/db.addUser/