<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Prakhar Jain on Medium]]></title>
        <description><![CDATA[Stories by Prakhar Jain on Medium]]></description>
        <link>https://medium.com/@prakhartkg?source=rss-a8613559873e------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/2*mq_IwxFq7i2iKGRx-cA5TQ.jpeg</url>
            <title>Stories by Prakhar Jain on Medium</title>
            <link>https://medium.com/@prakhartkg?source=rss-a8613559873e------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 15 Nov 2026 21:27:30 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@prakhartkg/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[In corners cool, away from glare,
 The Peace Lily thrives on tempered care.]]></title>
            <link>https://medium.com/@prakhartkg/in-corners-cool-away-from-glare-the-peace-lily-thrives-on-tempered-care-221e6e1bd05f?source=rss-a8613559873e------2</link>
            <guid isPermaLink="false">https://medium.com/p/221e6e1bd05f</guid>
            <dc:creator><![CDATA[Prakhar Jain]]></dc:creator>
            <pubDate>Fri, 23 May 2025 02:58:41 GMT</pubDate>
            <atom:updated>2025-05-23T02:58:41.947Z</atom:updated>
            <content:encoded><![CDATA[<h3>The Peace Lily’s Counsel</h3><p>In corners cool, away from glare,<br> The Peace Lily thrives on tempered care.<br> Not blazing sun nor desert dry — <br> She favors shade where shadows lie.</p><p>A drink she takes with quiet need,<br> But not so oft as thirst to plead.<br> Too much, and sorrow lines her face — <br> With drooping leaves she marks disgrace.<br> Her roots, if drowned in love too deep,<br> Will fail to hold and cease to keep.</p><p>Yet leave her parched, and she shall bend,<br> A wilted form, as if to send<br> A gentle chide, a whispered moan:<br> “Neglect me not, though I’ve not grown<br> To ask in voice or clamor loud — <br> I speak through leaf, not cries or crowd.”</p><p>Touch soil before the water flows,<br> Let dryness tell what she well knows.<br> A weekly sip may serve her well,<br> But listen close — she’ll always tell.</p><p>In filtered light, not harsh nor bold,<br> She stands in grace, not seeking gold.<br> With leaves of green and spathe of white,<br> She cleans the air and soothes the sight.</p><p>She needs no mists, nor fuss, nor frill — <br> Just honest care and time to still.<br> A gentle cloth to dust each leaf,<br> Will bring her joy and grant relief.</p><p>So heed her form, both firm and fair,<br> And let her teach the art of care.<br> Not too much, and not too small — <br> In balance lies the root of all.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=221e6e1bd05f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Anxiety : A silent thief]]></title>
            <link>https://medium.com/@prakhartkg/anxiety-a-silent-thief-steals-my-peace-and-brings-me-grief-a-constant-shadow-always-near-74317c3a89e7?source=rss-a8613559873e------2</link>
            <guid isPermaLink="false">https://medium.com/p/74317c3a89e7</guid>
            <category><![CDATA[motivation]]></category>
            <category><![CDATA[poetry]]></category>
            <category><![CDATA[inspiration]]></category>
            <category><![CDATA[poem]]></category>
            <category><![CDATA[anxiety]]></category>
            <dc:creator><![CDATA[Prakhar Jain]]></dc:creator>
            <pubDate>Sun, 15 Jan 2023 18:36:33 GMT</pubDate>
            <atom:updated>2023-01-15T19:45:46.803Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Anxiety : A silent thief</strong></p><p>Anxiety, a silent thief,<br>Steals my peace and brings me grief,<br>A constant shadow, always near,<br>Whispering doubts and filled with fear.</p><p>It grips my chest and twists my mind,<br>A prison, from which I cannot find,<br>A way to break these chains that bind,<br>And leave me trapped and confined.</p><p>But I will not let it win,<br>I&#39;ll fight the battle deep within,<br>For though it may be hard and long,<br>I&#39;ll find my strength and carry on.</p><p>For in the end, I know it&#39;s true,<br>That I am stronger than this too,<br>And though anxiety may try,<br>I&#39;ll rise above it, reaching for the sky.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=74317c3a89e7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Implement Single Sign-On SAML strategy with Node.js & Passport.js]]></title>
            <link>https://medium.com/brightlab-techblog/implement-single-sign-on-saml-strategy-with-node-js-passport-js-e8b01ff79cc3?source=rss-a8613559873e------2</link>
            <guid isPermaLink="false">https://medium.com/p/e8b01ff79cc3</guid>
            <category><![CDATA[aml]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[sso]]></category>
            <category><![CDATA[authentication]]></category>
            <category><![CDATA[passportjs]]></category>
            <dc:creator><![CDATA[Prakhar Jain]]></dc:creator>
            <pubDate>Tue, 09 Jun 2020 09:47:32 GMT</pubDate>
            <atom:updated>2020-06-11T13:15:04.588Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/406/1*viJBPg1CeVGNuWhXrlG-gg.png" /></figure><p><strong>Single sign-on (SSO)</strong> is a property of identity and access management (IAM) that enables users to securely authenticate with multiple applications and websites by logging in only once with just one set of credentials (username and password).</p><p>Here in this article, we will Implement Single Sign-On in a Node.js App with SAML authentication strategy using Passport.js middleware if you want to read more on Single Sign-on and SAML you can read this article below.</p><p><a href="https://medium.com/@prakhartkg/single-sign-on-sso-saml-authentication-explained-1e463b9168cb">Single Sign-On(SSO) — SAML Authentication Explained</a></p><p>First, we need an <strong>Identity Provider</strong> which can be an organization’s active directory or any free identity provider like OneLogin. For testing purposes I used <strong>OneLogin identity provider</strong> it allows us to create a developer account and we can play around it <a href="https://developers.onelogin.com/">https://developers.onelogin.com/</a></p><p>We can configure our App please follow documentation for more information.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/905/1*vAXhcdm1KddFkA8JXZ1yew.png" /></figure><p>We will configure this information from the SAML-Test connector into our Passport.js middleware.</p><p>This includes certificate, endpoint ie. entry point will be the entry point for our app this will redirect our app on the authentication page.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/779/1*pPrlRzlZaXIGdFRtVCpflQ.png" /></figure><p>We need to configure our app information into the identity provider to establish trust.</p><p>Application details are all Service Provider’s configuration like issuer and consumer callback URL</p><p><strong>Consumer URL </strong>we will configure Service Provider’s Callback Url which will be called on authentication success.</p><p>Above information provided by the identity provider which will set up trust between an identity provider and service provider. Here service provider will be a backend app that will make trust between multiple identity providers like Azure IDP, OneLogin, Google OAuth, and so on.</p><pre>{<br>    entryPoint: &#39;https://ad.example.net/adfs/ls/&#39;,<br>    issuer: &#39;DEV-BrightLab&#39;,<br>    callbackUrl: &#39;https://your-app.example.net/login/callback&#39;,<br>    cert: &#39;MIICizCCAfQCCQCY8tKaMc0BMjANBgkqh ... W==&#39;<br> }</pre><p>Here we have details which we will set up in our service provider to establish a trust between the service provider and identity provider.</p><blockquote><strong>entryPoint:</strong> is the URL provided by Identity Provider which will be used to redirect users on the login page if not authenticated.</blockquote><blockquote><strong>issuer: </strong>is a string provided to the Identity Provider to uniquely identify Service Provider.</blockquote><blockquote><strong>callbackUrl: </strong>This will be the URL of the Service Provider which will consume the SAML response once authentication is done on Identity Provider. Identity Provider will call this URL.</blockquote><blockquote><strong>cert: </strong>This is the certificate provided by Identity Provider. This will be used to establish the trust between Identity Provider and Service Provider.</blockquote><p><strong><em>Now we are ready to implement our service provider using Passport.js</em></strong></p><p>Passport is authentication middleware for Node.js. extremely flexible and modular, Passport can be unobtrusively dropped into any Express-based web application. A comprehensive set of strategies support authentication using a username and password, Facebook, Twitter, and more.</p><pre>npm install passport</pre><p>Install <em>passport-saml</em>, it is a SAML 2.0 authentication provider for Passport, the Node.js authentication library. The code was originally based on Michael Bosworth’s <em>express-saml</em> library.</p><pre>npm install passport-saml</pre><p>First We will Setup our passport handler middleware with our identity provider configuration. This is for a single identity provider strategy.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c5376ffad6da7e5edcd957f7a85606e0/href">https://medium.com/media/c5376ffad6da7e5edcd957f7a85606e0/href</a></iframe><p>Now we can configure this Passport middleware into our app and initialize it.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1c5f7bc88f1e236fb3a22ec63c3daacc/href">https://medium.com/media/1c5f7bc88f1e236fb3a22ec63c3daacc/href</a></iframe><ul><li>We will set up two routes one is the <strong>GET</strong> route which will be the entry point of SSO into the application. when it will be called passport will authenticate and verify the trust in between service provider and the identity provider.</li><li>Another will be the consumer which will be called by the identity provider once it validated the credentials. Here Request body will be a SAML which is a base64 encoded body here I used the <strong>Saml2js </strong>module to parse the assertion in the <strong>SAML </strong>body which will provide the details of user who logged in.</li></ul><p>Here is the router code for the Router</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/deabeca293797ecd4505e691dec84c40/href">https://medium.com/media/deabeca293797ecd4505e691dec84c40/href</a></iframe><p>This is a user login controller which creates the session set in response cookies and redirect response to a UI Application page.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jV6hxnWV4Wh5iI7e0hkePw.png" /></figure><p>Let&#39;s put this all together and see how all this works…..</p><p>First, we call GET API <strong><em>localhost:9000/user/v1/users/login/sso</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*F6Ejf-0ytC5-PS9ox4Ycxw.png" /></figure><ul><li>This <strong>GET</strong> API call checks if the active session is there or not, In my case, there was no active session it redirects me on an identity provider login page.</li><li>Once I entered my username and then password it authenticate request on identity provider and then it called the callback URL of service provider which we configured in the identity provider.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*diPUX2j2Zsz2LYdVyBVKMg.png" /></figure><ul><li>This <strong>POST </strong>callback URL <strong><em>localhost:9000/user/v1/users/login/sso/callback </em></strong>created a session for the application by validating request and redirects to the application dashboard page.</li></ul><p>Well, We have successfully configured SAML based Single Sign-On</p><p>What if we have a SAAS based multitenant application which has different organizations and we need to configure Single Sign-On with these organization&#39;s Active Directory or their identity provider, In this case, we can use Passport’s MultiSAML strategy where we can configure SAML configuration on demand, we can identify organizations by subdomain or we can pass path params to these above URL. Let&#39;s configure MultiSamlStrategy</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/76ef7088f04e1f7ab52f0ab406cbe49e/href">https://medium.com/media/76ef7088f04e1f7ab52f0ab406cbe49e/href</a></iframe><p>Here <strong>getSamlOptions </strong>function will be invoked on <strong>passport.authenticate()</strong> middleware called here we are fetching SAML configuration from DB on the basis of request orgId and setting this config for this middleware.</p><p>Here we configure Routes with path params and also configured their value into identity provider.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*xA8qYzwBPwBpQ1ITQ-gIng.png" /></figure><p>He is how I configured my BrightLab application with my Organization’s Active Directory ie. Azure.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/594/1*4xujFwEkOEfmx9bd-3oc2g.png" /></figure><p>we provided callback URL as <strong>/login/sso/callback/orgName</strong>here <strong><em>orgName </em></strong>becomes the value for the path parm id and we fetch SAML configuration from DB by <strong>{orgId: orgName}</strong> and on calling login API it will be redirected to the meck azure login page.</p><p>On submitting id and password identity provider authenticates the request and calls the callback URL and Land on the dashboard Page. similarly, we can pass different org if we have configured it and stored it into our database and we can determine this on the basis on the subdomain as well.</p><p>If you want to implement multitenancy into the Node.js application you can read this article below.</p><p><a href="https://medium.com/brightlab-techblog/multitenant-node-js-application-with-mongoose-mongodb-f8841a285b4f">Multitenant Node.js Application with mongoose (MongoDB)</a></p><h3>References :</h3><p><a href="http://www.passportjs.org/docs/downloads/html/">Documentation</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e8b01ff79cc3" width="1" height="1" alt=""><hr><p><a href="https://medium.com/brightlab-techblog/implement-single-sign-on-saml-strategy-with-node-js-passport-js-e8b01ff79cc3">Implement Single Sign-On SAML strategy with Node.js &amp; Passport.js</a> was originally published in <a href="https://medium.com/brightlab-techblog">TechBlog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Single Sign-On(SSO) — SAML Authentication Explained]]></title>
            <link>https://medium.com/brightlab-techblog/single-sign-on-sso-saml-authentication-explained-1e463b9168cb?source=rss-a8613559873e------2</link>
            <guid isPermaLink="false">https://medium.com/p/1e463b9168cb</guid>
            <category><![CDATA[passportjs]]></category>
            <category><![CDATA[sso]]></category>
            <category><![CDATA[authorization]]></category>
            <category><![CDATA[aml]]></category>
            <category><![CDATA[authentication]]></category>
            <dc:creator><![CDATA[Prakhar Jain]]></dc:creator>
            <pubDate>Mon, 08 Jun 2020 04:53:58 GMT</pubDate>
            <atom:updated>2020-06-09T13:16:45.203Z</atom:updated>
            <content:encoded><![CDATA[<h3>Single Sign-On(SSO) -SAML Authentication Explained</h3><h3><strong>What is Single sign-on?</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/406/1*viJBPg1CeVGNuWhXrlG-gg.png" /></figure><p><strong>Single sign-on (SSO)</strong> is a property of identity and access management (IAM) that enables users to securely authenticate with multiple applications and websites by logging in only once with just one set of credentials (username and password).</p><p>This saves the user from remembering multiple usernames and passwords, while still providing strong authentication. And, once they have logged in, an end-user can access other connected web apps without logging in again, until their authenticated session expires.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/811/1*sbT1TaVFIUdoYF2cx90XoQ.png" /></figure><h3>How does SSO work?</h3><p>Authentication with SSO relies on a trust relationship between domains (websites). With single sign-on, this is what happens when you try to log in to an app or website:</p><ol><li>The website first checks to see whether you’ve already been authenticated by the SSO solution, in which case it gives you access to the site.</li><li>If you haven’t, it sends you to the SSO solution to log in.</li><li>You enter the single username/password that you use for corporate access.</li><li>The SSO solution requests authentication from the identity provider or authentication system that your company uses. It verifies your identity and notifies the SSO solution.</li><li>The SSO solution passes authentication data to the website and returns you to that site.</li><li>After login, the site passes authentication verification data with you as you move through the site to verify that you are authenticated each time you go to a new page.</li></ol><p>In SSO, authentication verification data takes the form of tokens.</p><h3><strong>SSO Strategy</strong></h3><p><strong>SAML</strong> is an XML-based open-standard data format for exchanging <strong>authentication </strong>and <strong>authorization </strong>data between parties, in particular, between an identity provider and a service provider.</p><p><strong>OAuth </strong>is an open protocol to allow <strong>secure authorization </strong>in a simple and standard method from web, mobile, and desktop applications.</p><h3><strong>What is SAML?</strong></h3><p>Security Assertion Markup Language (SAML) is a very powerful and flexible standard for logging users into applications based on their sessions in another context. This single sign-on (SSO) login standard has significant advantages over logging in using a username/password:</p><ul><li>No need to type in credentials</li><li>No need to remember and renew passwords</li><li>No weak passwords</li></ul><p>Most organizations already know the identity of users because they are logged in to their Active Directory domain or intranet. It makes sense to use this information to log users into other applications, such as web-based applications, and one of the more elegant ways of doing this is by using SAML.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*fULvjuF0MUJxXho7.png" /><figcaption>SAML Response</figcaption></figure><h3>WHY USE SAML?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/602/1*F9ikVUZ2aw4UV6WQ27QANQ.png" /></figure><p><strong>SAML </strong>is the gold standard for single sign-on for cloud apps. It eliminates all passwords and instead uses digital signatures to establish trust between the identity provider and the cloud app. Using <strong>SAML</strong>, users can seamlessly access multiple applications, allowing them to conduct business faster and more efficiently.</p><blockquote><strong>SSO </strong>also helps organizations to login employes to all the organization related applications with just a single username and password which can we associated with their system and the Active directory they are already managing and with SAML we can do Authorization and Authentication both.</blockquote><blockquote>For Example, we Integrated our BrightLab app with Organization’s Azure AD to login to the application with the same company’s email and they don’t have to log in if already logged in to any of the application associated with same AD ie. their <strong>Outlook any other App</strong>.</blockquote><h3>User requests access Flow</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/650/0*V1auWxXEGtiGKxT_.jpg" /></figure><p>The website redirects the user to the SSO website to log in. The user logs in with a single username and password.</p><p>The SSO website verifies the user’s identity with an identity provider, such as Active Directory.</p><p><strong>User is granted access and then requests access to a new site</strong></p><p>When the user tries to access a different website, the new website checks with the SSO solution. Since the user has been authenticated, it verifies the user’s identity to the new website without requiring an additional login.</p><p><strong>A Service Provider (SP)</strong> is the entity providing the service, typically in the form of an application.</p><p><strong>An Identity Provider (IdP)</strong> is the entity providing the identities, including the ability to authenticate a user. The Identity Provider typically also contains the user profile: additional information about the user such as first name, last name, job code, phone number, address, and so on. Depending on the application, some service providers may require a very simple profile (username, email), while others may require a richer set of user data (job code, department, address, location, manager, and so on).</p><p><strong>A SAML Request</strong>, also known as an authentication request, is generated by the Service Provider to “request” an authentication.</p><p><strong>A SAML Response</strong> is generated by the Identity Provider. It contains the actual assertion of the authenticated user. In addition, a SAML Response may contain additional information, such as user profile information and group/role information, depending on what the Service Provider can support.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/571/0*6mTW2bm3KyGZeWlS.png" /></figure><p><strong>A Service Provider Initiated (SP-initiated)</strong> sign-in describes the SAML sign-in flow when initiated by the Service Provider. This is typically triggered when the end-user tries to access a resource or sign in directly on the Service Provider side, such as when the browser tries to access a protected resource on the Service Provider side.</p><p><strong>An Identity Provider Initiated (IdP-initiated)</strong> sign-in describes the SAML sign-in flow initiated by the Identity Provider. Instead of the SAML flow being triggered by redirection from the Service Provider, in this flow, the Identity Provider initiates a SAML Response that is redirected to the Service Provider to assert the user’s identity.</p><h3>SAML SSO Flow</h3><p>The diagram below illustrates the single sign-on flow for service provider-initiated SSO, i.e. when an application triggers SSO.</p><p>Identity provider-initiated SSO is similar and consists of only the bottom half of the flow.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/897/1*S5VbyNSva1c-A3JbMGnWPw.png" /></figure><h3><strong>How SAML Works</strong></h3><p>SAML SSO works by transferring the user’s identity from one place (the identity provider) to another (the service provider). This is done through an exchange of digitally signed XML documents.</p><p>Consider the following scenario: A user is logged into a system that acts as an identity provider. The user wants to log in to a remote application, such as a support or accounting application (the service provider). The following happens:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/598/1*ivdXb1Ec-V_srnmv3zXOBA.png" /></figure><ol><li>The user accesses the remote application using a link on an intranet, a bookmark, or similar and the application loads.</li><li>The application identifies the user’s origin (by application subdomain, user IP address, or similar) and redirects the user back to the identity provider, asking for authentication. This is the authentication request.</li><li>The user either has an existing active browser session with the identity provider or establishes one by logging into the identity provider.</li><li>The identity provider builds the authentication response in the form of an XML-document containing the user’s username or email address, signs it using an X.509 certificate, and posts this information to the service provider.</li><li>The service provider, which already knows the identity provider and has a certificate fingerprint, retrieves the authentication response and validates it using the certificate fingerprint.</li><li>The identity of the user is established, and the user is provided with app access.</li></ol><h3><strong>Implement SSO with Node.js</strong></h3><p>Implementation of SSO with SAML in Node.js using Passport.js middleware.</p><p><a href="https://medium.com/@prakhartkg/implement-single-sign-on-saml-strategy-with-node-js-passport-js-e8b01ff79cc3">Implement Single Sign-On SAML strategy with Node.js &amp; Passport.js</a></p><h3><strong>References :</strong></h3><p><a href="https://www.onelogin.com/learn/how-single-sign-on-works">How Does Single Sign-On (SSO) Work? | OneLogin</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1e463b9168cb" width="1" height="1" alt=""><hr><p><a href="https://medium.com/brightlab-techblog/single-sign-on-sso-saml-authentication-explained-1e463b9168cb">Single Sign-On(SSO) — SAML Authentication Explained</a> was originally published in <a href="https://medium.com/brightlab-techblog">TechBlog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Multitenant Node.js Application with mongoose (MongoDB)]]></title>
            <link>https://medium.com/brightlab-techblog/multitenant-node-js-application-with-mongoose-mongodb-f8841a285b4f?source=rss-a8613559873e------2</link>
            <guid isPermaLink="false">https://medium.com/p/f8841a285b4f</guid>
            <category><![CDATA[mongodb]]></category>
            <category><![CDATA[multitenancy]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[mongoose]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Prakhar Jain]]></dc:creator>
            <pubDate>Mon, 27 Apr 2020 11:56:23 GMT</pubDate>
            <atom:updated>2020-06-15T05:15:54.499Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Multitenancy</strong> is a reference to the mode of operation of software where multiple independent instances of one or multiple applications operate in a shared environment. The instances (tenants) are logically isolated, but physically integrated.</p><blockquote><em>The term “</em><strong><em>software multi-tenancy</em></strong><em>” refers to a software architecture in which a single instance of software runs on a server and serves multiple tenants.</em></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hxoH4oBiDxssx5HpOdS14w.jpeg" /></figure><blockquote>Architecting a multi-tenant system is <strong>more complicated</strong> than architecting a multi-user system. There are two models of architecting a multi-tenant system: <strong>Instance replication</strong> and <strong>Data-Segregation</strong>.</blockquote><p>In the <strong>instance replication model</strong>, the system spins a new instance for every tenant. This is easier to start, but hard to scale. It becomes a nightmare when 100s of tenants signup.</p><p>In the <strong>data-segregation model</strong>, the application is shared between tenants but data of each tenant is stored in separate data stores. Separate data stores could be<strong> separate databases</strong> or <strong>separate schema</strong> within the same database.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/473/1*5CVveduLQdoIFAdQp5F0tA.png" /></figure><p><strong>Data Segregation</strong> is of two types</p><ul><li>One DB with different schemas for a different tenant.</li><li>One DB per tenant.</li></ul><p>separate schema ie. different tables within one DB for each tenant.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/715/1*WkEE_fKOgFRE0b1U-LI7Dg.png" /></figure><p>In this blog, we will discuss multitenancy with Data-Segregation Model with a single DB per tenant.</p><p>Create a Node app initialize one MongoDB connection along with the app and export this connection object. create this connection using mongoose createConnection as the createConnection method does not create default connection but return a DB connection object.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a1f1202ef5ee71982e4bcfef90715eaf/href">https://medium.com/media/a1f1202ef5ee71982e4bcfef90715eaf/href</a></iframe><p>Here we are creating a MongoDB connection with mongoose and exporting it from here and it will be imported in config index.js file which will be initialized only once in the app and we can import this MongoDB object anywhere or we can also create and store it in global and can use it anywhere.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6b2c3bd1a7fc0e07aa12cce60af14509/href">https://medium.com/media/6b2c3bd1a7fc0e07aa12cce60af14509/href</a></iframe><p>importing this MongoDB object and we can create a new MongoDB connection as per our tenant.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a75444c5b9ad5a23fc8ae30797022bd4/href">https://medium.com/media/a75444c5b9ad5a23fc8ae30797022bd4/href</a></iframe><p>Mongoose provides <strong>useDb </strong>function which is used to create a new connection object it takes two params first one is DB name and another is options</p><pre><strong>Connection.prototype.useDb()</strong></pre><pre><strong>Parameters</strong>:<br>name      «String» The database name<br>{options} «Object» Configs</pre><pre>options = {useCache: false} «Boolean»  False by default</pre><pre>If set true, cache results so calling useDb() multiple times with the same name only creates 1 connection object.</pre><pre><strong>Returns:</strong><br>«Connection» New Connection Object</pre><p>we are it switches to a different database using the same connection pool and Returns a new connection object, with the new DB, and using option {useCache: true} will create a single connection object for the same tenant if called multiple times.</p><p>To get the model from tenant DB, we need to create a schema of our model and pass it along with the tenant to this function, which will return a model. Now we can use this model to perform all of our crud operations.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ee9a3c823fd4dbc06a2c7c6e29779b35/href">https://medium.com/media/ee9a3c823fd4dbc06a2c7c6e29779b35/href</a></iframe><p>In the Data access layer, we will first get the model as per our tenant DB connection and then perform crud operations. In each request, we have to pass tenantId and this tenantId will be used to switch with that tenant DB.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/45ef141828cf3a669d872e52c0c2bb7a/href">https://medium.com/media/45ef141828cf3a669d872e52c0c2bb7a/href</a></iframe><p>In this approach, we are using the same connection pool which we created at the time of app initialization. Multiple requests with different tenants will create different connection objects which will be timed out after 30 seconds if there is not new request with the same tenant.</p><p>There is another approach as well we can implement this will be helpful with limited no of tenants. In this, we can create a global object where the key will be tenantId/tenantName, and value will be the connection object. before every request we will check if the connection is there in this global object otherwise we will create a connection and store it there so in next request from that tenant will be reused.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f426fd7fd405a2713ccfc4c113f03bf0/href">https://medium.com/media/f426fd7fd405a2713ccfc4c113f03bf0/href</a></iframe><p>In this above implementation, there can be a CPU usage issue if the number of the tenants will increase as the app will always have lots of open connection will degrade performance but it can be used in case you have fewer tenants and which will never grow dynamically.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f8841a285b4f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/brightlab-techblog/multitenant-node-js-application-with-mongoose-mongodb-f8841a285b4f">Multitenant Node.js Application with mongoose (MongoDB)</a> was originally published in <a href="https://medium.com/brightlab-techblog">TechBlog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>