Proper way to cleanup a mongo db() reference? - mongodb

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.

Related

setting per-user session variable in pg-promise

I'm trying to set session level variable on a connection in pg-promise, the variable value will be read by trigger in the database level with current_setting('var_name'). This session variable will be different for each user, while I'm also sharing the same database connection for all users.
I found this somewhat related question utilizing the connect event, but I have concern that since I'm sharing the same connection for all users that the session var will not be set correctly when different users call the query method.
Is there another way to safely set this session var and make sure that it's isolated for each user while still sharing the same database object?
const pgPromise = pgp({
promiseLib: Promise, // overriding the default (ES6 Promise)
async connect(client, dc, useCount) {
// const cp = client.connectionParameters;
// console.log('Connected to database:', cp.database, dc);
if (dc && dc.email) {
console.log(useCount);
const email = encodeURI(dc.email);
await client.query(`SET SESSION "app.user" = '${email}'`);
}
}
});
get tenantDb() {
const state = this.request.sessionState();
const config = { host, database, port };
// pass state as database context,
// we'll get warning of duplicate database object for the same connection
const connection = pgPromise(config, state);
return connection;
}
Update
It turns out that I need to upgrade pg-promise version to the latest version, I was using v7 which doesn't differentiate the connection object based on the context, once I upgrade pg-promise to v10 the warning disappear, a more optimized solution would be if we can somehow set the session settings along with the schema callback in the initOptions parameter when we initiate the database, that way we only need one extra query execution together with the schema.

GetStream add activity fails due 403

Trying out GetStream for Swift, I am not able to add an activity.
class MyActivity : Activity {}
...
let client = Client(apiKey: <MyApiKey>, appId: <MyApiKey>, token: <Token>)
let ericFeed = client.flatFeed(feedSlug: "user", userId: "eric")
let activity = MyActivity(actor: "eric", verb: "waves", object: "picture:10", foreignId: "picture:10")
ericFeed.add(activity) { result in
print("!result!")
print(result)
}
The token is generated server-side, is in form eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiZXJpYyJ9.AAAAAAAAAAAAAAAAA-AAAAAAAAAAAAAAAA-AAAAAAAA and:
client.currentUserId returns eric (So, the token is correct?)
The Callback of ericFeed.add(activity) is not called
On my app's dashboard log, I see the attempt of adding the activity as failed, with error 403
I tried different ids (with different tokens), both actor: "eric" and actor: "user:eric". What could have gone wrong?
The code to generate the token (php server) is:
$userId = "eric";
$client = new GetStream\Stream\Client(<MyApiKey>, <MyAppSecret>);
$userToken = $client->createUserSessionToken($userId);
And I receive to logs on my dashboard:
There is a couple things that needs to keep in mind.
First of all, probably your client was deallocated when the request was ended and that's why the callback wasn't called, but logs could show you that the request was done. I suggest you to use a shared Client instance and it would be easy to use. To setup a shared Client you need to write this:
Client.config = .init(apiKey: "<MyApiKey>", appId: "<MyApiKey>", token: "<Token>")
More about the Client setup in wiki page.
The second important thing, that you have to create/update your Stream user. From the server side you are getting your Token with the Stream userId and can request the Stream user. The easiest way is to call Client.shared.create(user:) where user would be created/updated. So, it's still a part of the Stream Client setup:
Client.shared.create(user: GetStream.User(id: Client.shared.currentUserId!)) { result in
// Update the client with the current user.
Client.shared.currentUser = try? result.get()
// Do all your requests from here. Reload feeds and etc.
}
More info in docs.
I suggest you to create feeds with only feedSlug parameter and the Stream userId would be taken from the Token. But it would be Optional, because the currentUserId is optional. For example:
let ericFeed = Client.shared.flatFeed(feedSlug: "user")
ericFeed?.add(activity)
And for your activities, Stream clients should always use the current Stream user as an actor. So, we need to update the definition of your MyActivity.
Finally, here is your code that should works:
// Define your activity.
class MyActivity: EnrichedActivity<GetStream.User, String, DefaultReaction> {
// ...
}
// Setup Stream Client.
Client.config = .init(apiKey: <MyApiKey>, appId: <MyApiKey>, token: <Token>)
// Setup the current user.
Client.shared.getCurrentUser {
let ericFeed = Client.shared.flatFeed(feedSlug: "user")
let activity = MyActivity(actor: Client.shared.currentUser!, verb: "waves", object: "picture:10", foreignId: "picture:10")
ericFeed?.add(activity) { result in
print("!result!")
print(result)
}
}

MongoDB Stitch REST API - Payload Signature Verification

I am working on a SANDBOX Cluster & a new app created by me in MongoDB Stitch.
I need to understand "Payload Signature Verification" in MongoDB Stitch App. Lets say, I need to make a REST GET API, which will fetch me a list of products, but this API call must be authenticated ie. only registered/authenticated users will be able to make this call. MongoDB Stitch suggests below to do that:
https://docs.mongodb.com/stitch/services/webhook-requests-and-responses/#webhook-verify-payload-signature
But, i need to understand:
(1) Where to add this BODY & SECRET ? As per my knowledge, it must be kept in the stitch app, as you must not expose any of your secret keys in client side javascript.
(2) { "message":"MESSAGE" } is this configurable? if yes, what value should we add here?
This function must be coded in MongoDB Stitch App. That is clear. This function returns "hash" based on the "body" & "secret" you pass in earlier step.
And now, you must pass this hash in your API Request:
Now, the question is:
You can easily see any request which is being passed to server in developer tools, anybody can easily copy it & pass it same through POSTMAN. So:
-> How do i secure my requests? (FYI: I have also added "RULES", saying this request must execute only if the domain name contains lets say, www.mysite.com. But i am able to execute the request successfully from localhost.)
-> If, anybody can copy & paste my request in POSTMAN & run it. SO, what is the use of generating that HASH ?
-> How do i keep my request(s) tokens alive/valid for limited period of time, lets say request is valid only for next 5 minutes ? (i mean how do i do this in Stitch APP ? Where is that Option ?)
-> How do i get the refresh token ? & even if i get it somehow, how do i re-pass it to the request ?
All such queries are UN_ANSWERED in MongoDB Stich Documentation : https://docs.mongodb.com/stitch/
Basically i want to understand the full life-cycle of any GET/POST/PUT/PATCH/DELETE request of MongoDB Stitch App / Stitch REST APIs.
If anybody have used MongoDB Stich, please explain me.
I don't know your specific use-case, though I also had issues with creating an Authenticated HTTP REST API. My idea was: I already have all security rules and schemas defined in Stitch, now I want to access the data over HTTP still using the logic defined in Stitch and not rewriting everything.
I wasn't able to create such API with Stitch functions and Webhooks, though I created an API server in (literally) 1 hour with NodeJS Koa (express or any other framework would do) and Stitch server SDK:
// app.js
const Koa = require('koa')
const app = module.exports = new Koa()
const auth = require('./auth')
const router = require('./router')
app.use(auth())
app.use(router.routes())
app.use(router.allowedMethods())
// listen
if (!module.parent) {
app.listen(3000)
}
// auth.js
const { loginWithApiKey } = require('./stitch')
function auth () {
return async function auth (ctx, next) {
const apiKey = ctx.query.api_key
try {
await loginWithApiKey(apiKey)
} catch (e) {
ctx.throw(401, 'Not Authorized')
}
await next()
}
}
module.exports = auth
// router.js
const router = require('koa-router')()
const { BSON } = require('mongodb-stitch-server-sdk')
const { db } = require('./stitch')
router.get('/', async (ctx) => {
ctx.body = { message: 'Nothing to see, but you\'re good!' }
})
const COLLECTIONS_WHITELIST = [
'activities',
'expenses',
'projects',
'resources'
]
// List
router.get('/:collection', async (ctx) => {
const collection = ctx.params.collection
isValidCollection(ctx, collection)
ctx.body = await db
.collection(collection)
.find()
.toArray()
})
function isValidCollection (ctx, collection) {
// check if the collection is allowed in the API
if (!COLLECTIONS_WHITELIST.includes(collection)) {
ctx.throw(404, `Unknown API entity ${collection}`)
}
}
module.exports = router
I hope it helps

Why am I getting this 'undefined' error?

I'm working on a Meteor project, and for some reason this profile template refuses to work.
I'm using the following code, as well as the accounts-password and accounts-entry packages for user management:
this.route('profile', {
path: '/profile/:username',
data: function() {
var userDoc = Meteor.users.findOne({"username": this.params.username});
var bookCursor = Books.find({owner: userDoc._id});
return {
theUser: userDoc,
theBooks: bookCursor
};
}
});
When I try to go to the profile URL for my test accounts ('misutowolf', and 'test2', respectively), I am given the following error in Chrome's dev console: Exception from Deps recompute function: TypeError: Cannot read property '_id' of undefined, pointing to the use of userDoc._id in the call to Books.find().
This makes no sense whatsoever, as I was able to find a user document with the names in question using meteor mongo with both usernames, in the form db.users.find({username: "misutowolf"}) and db.users.find({username: "test2"}).
I am very confused, not sure what is causing this issue at all.
By default Meteor only publish the currently logged in user info via an automatically setup publication.
What you need to do is push to the client the user info (username) you're trying to use, because if you don't do that, the user you're accessing is not published to the client and you get an undefined error when accessing its _id.
First, setup a dedicated publication (on the server) :
Meteor.publish("userByUsername",function(username){
return Meteor.users.find({
username:username
});
});
Then waitOn this publication in your route :
waitOn:function(){
return this.subscribe("userByUsername",this.params.username);
}
Finally, guard against accessing the user document until it is pushed to the client because even if you are waiting on the subscription, the data method might actually get called even if the subscription is not ready yet.
data: function() {
var userDoc = Meteor.users.findOne({"username": this.params.username});
if(!userDoc){
return;
}
// ...
}

Updating MongoDB in Meteor Router Filter Methods

I am currently trying to log user page views in meteor app by storing the userId, Meteor.Router.page() and timestamp when a user clicks on other pages.
//userlog.js
Meteor.methods({
createLog: function(page){
var timeStamp = Meteor.user().lastActionTimestamp;
//Set variable to store validation if user is logging in
var hasLoggedIn = false;
//Checks if lastActionTimestamp of user is more than an hour ago
if(moment(new Date().getTime()).diff(moment(timeStamp), 'hours') >= 1){
hasLoggedIn = true;
}
console.log("this ran");
var log = {
submitted: new Date().getTime(),
userId: Meteor.userId(),
page: page,
login: hasLoggedIn
}
var logId = Userlogs.insert(log);
Meteor.users.update(Meteor.userId(), {$set: {lastActionTimestamp: log.submitted}});
return logId;
}
});
//router.js This method runs on a filter on every page
'checkLoginStatus': function(page) {
if(Meteor.userId()){
//Logs the page that the user has switched to
Meteor.call('createLog', page);
return page;
}else if(Meteor.loggingIn()) {
return 'loading';
}else {
return 'loginPage';
}
}
However this does not work and it ends up with a recursive creation of userlogs. I believe that this is due to the fact that i did a Collection.find in a router filter method. Does anyone have a work around for this issue?
When you're updating Meteor.users and setting lastActionTimestamp, Meteor.user will be updated and send the invalidation signal to all reactive contexts which depend on it. If Meteor.user is used in a filter, then that filter and all consecutive ones, including checkLoginStatus will rerun, causing a loop.
Best practices that I've found:
Avoid using reactive data sources as much as possible within filters.
Use Meteor.userId() where possible instead of Meteor.user()._id because the former will not trigger an invalidation when an attribute of the user object changes.
Order your filters so that they run with the most frequently updated reactive data source first. For example, if you have a trackPage filter that requires a user, let it run after another filter called requireUser so that you are certain you have a user before you track. Otherwise if you'd track first, check user second then when Meteor.logginIn changes from false to true, you'd track the page again.
This is the main reason we switched to meteor-mini-pages instead of Meteor-Router because it handles reactive data sources much easier. A filter can redirect, and it can stop() the router from running, etc.
Lastly, cmather and others are working on a new router which is a merger of mini-pages and Meteor.Router. It will be called Iron Router and I recommend using it once it's out!