<?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 Neetesh kumar on Medium]]></title>
        <description><![CDATA[Stories by Neetesh kumar on Medium]]></description>
        <link>https://medium.com/@kumarneetesh?source=rss-e69543d835d4------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*iAPM51VAN40V8o0cJoeFtg.jpeg</url>
            <title>Stories by Neetesh kumar on Medium</title>
            <link>https://medium.com/@kumarneetesh?source=rss-e69543d835d4------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 16:38:30 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@kumarneetesh/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[How libuv help in promise.all or parallel execution In Node JS]]></title>
            <link>https://kumarneetesh.medium.com/how-libuv-help-in-promise-all-or-parallel-execution-in-node-js-fb49f6b695fb?source=rss-e69543d835d4------2</link>
            <guid isPermaLink="false">https://medium.com/p/fb49f6b695fb</guid>
            <dc:creator><![CDATA[Neetesh kumar]]></dc:creator>
            <pubDate>Sat, 26 Oct 2024 05:42:58 GMT</pubDate>
            <atom:updated>2024-10-26T05:42:58.249Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*n1HTO15RfxisIlTdx4L6BQ.jpeg" /></figure><p>Libuv is a crucial component in Node.js, providing the underlying architecture to handle asynchronous, non-blocking I/O. When `Promise.all` is used to manage multiple asynchronous operations, libuv plays a key role in concurrently managing and executing these tasks.</p><p>Here’s how libuv contributes to `Promise.all` or parallel execution of asynchronous tasks in Node.js:</p><p>1. <strong>Background Thread Pool for Non-blocking I/O Operations</strong><br> — Node.js is single-threaded for JavaScript execution, but libuv provides a thread pool to handle non-blocking operations in parallel, which is critical when using `Promise.all`.<br> — When `Promise.all` is used, each promise (representing an asynchronous operation) runs independently. For I/O-bound tasks like reading files, network requests, or database queries, libuv offloads these tasks to its thread pool instead of executing them on the main JavaScript thread.<br> — Thread pool tasks include operations like file system operations, DNS lookups, and certain types of compression and cryptography. The default thread pool size is 4, but this can be configured (via `UV_THREADPOOL_SIZE`), which allows Node.js to run multiple I/O tasks in parallel.</p><blockquote>Example:<br> ```javascript<br> const fs = require(‘fs’).promises;<br> <br> const readFile1 = fs.readFile(‘file1.txt’);<br> const readFile2 = fs.readFile(‘file2.txt’);<br> const readFile3 = fs.readFile(‘file3.txt’);<br> <br> Promise.all([readFile1, readFile2, readFile3]).then(results =&gt; {<br> console.log(‘All files read:’, results);<br> });<br> ```</blockquote><p>In this example, `fs.readFile` operations are delegated to libuv’s thread pool, which allows them to run concurrently in background threads, enabling parallel execution.</p><p>2. <strong>Event Loop Management and Task Queuing</strong><br> — Libuv manages the event loop, which orchestrates the flow of asynchronous events in Node.js. When tasks (like network requests) are offloaded, the event loop can continue processing other JavaScript code while waiting for those tasks to complete.<br> — Once an async task completes in the background, libuv queues a callback (or promise resolution) to notify Node.js that the task has finished. These callbacks are then moved back to the microtask queue (for promises) or task queue and executed in the next available cycle of the event loop.<br> — The event loop’s phases (like timers, I/O callbacks, and polling) allow Node.js to effectively handle multiple tasks at once, even when many promises are resolving simultaneously.</p><p>3. <strong>Handling Network and Timer Operations</strong><br> — Certain async operations, such as network requests, are handled directly by the OS kernel instead of the libuv thread pool. Node.js uses OS APIs to handle network requests, so libuv’s role here is to manage the event loop’s `poll` phase and watch for completion events.<br> — For `setTimeout` or `setInterval`, libuv’s timers phase checks for any expired timers in each event loop cycle and triggers their callbacks at the right time.</p><p>4. <strong>Scaling with Concurrency Control</strong><br> — By default, libuv’s thread pool has 4 threads, which means it can handle up to 4 concurrent I/O tasks without blocking. However, when using `Promise.all`, many more promises might be executed than there are available threads.<br> — If you’re handling large numbers of async tasks, you may need to increase `UV_THREADPOOL_SIZE` to enable more concurrent operations in the libuv thread pool, allowing `Promise.all` to handle more I/O tasks in parallel without excessive queuing.</p><p><strong>How `Promise.all` Works with Libuv in Practice</strong><br>When you use `Promise.all` for a set of async tasks:<br>1. Each async task starts and is either handled by a libuv thread (for I/O) or an OS-specific mechanism (e.g., networking).<br>2. Libuv and the event loop monitor each task. When a task finishes, libuv places a notification in the appropriate queue.<br>3. The event loop picks up these notifications and executes the promise resolution callbacks in the correct order.<br>4. Once all promises resolve, `Promise.all` completes, returning the results.</p><p><strong>Summary</strong><br>Libuv enables Node.js to handle multiple async operations concurrently by:<br>- Using a background thread pool to execute non-blocking I/O tasks,<br>- Managing the event loop to handle network requests and timers,<br>- Allowing `Promise.all` to process multiple tasks in parallel while keeping the main thread non-blocking.</p><p>In this way, libuv makes `Promise.all` efficient by managing the heavy lifting of concurrent I/O tasks, allowing Node.js to scale even on a single-threaded runtime.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fb49f6b695fb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Passwordless Phone or Email Authentication with Amazon Cognito In Nodejs]]></title>
            <link>https://kumarneetesh.medium.com/passwordless-phone-or-email-authentication-with-amazon-cognito-in-nodejs-e620bc30b4c2?source=rss-e69543d835d4------2</link>
            <guid isPermaLink="false">https://medium.com/p/e620bc30b4c2</guid>
            <category><![CDATA[passwordless]]></category>
            <category><![CDATA[awsserverless]]></category>
            <category><![CDATA[aws-amplify]]></category>
            <category><![CDATA[post]]></category>
            <category><![CDATA[cognito]]></category>
            <dc:creator><![CDATA[Neetesh kumar]]></dc:creator>
            <pubDate>Sat, 29 May 2021 03:54:25 GMT</pubDate>
            <atom:updated>2021-05-29T03:54:25.295Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZyPlL4KAHZinU_b1EbmZWg.jpeg" /><figcaption>image source: Google</figcaption></figure><h3>Why Passwordless</h3><ol><li>Having to remember passwords can be a pain, especially for passwords that you don’t use often. Like most people, you too are probably familiar with having to click the “forgot password” link or button on websites and apps</li><li>It is also inconvenient for a user to recover their account in case they forget their password. To solve these problems many services have started to opt for Passwordless authentication using Phone numbers and E-mail.</li></ol><h3>Using Phone Number or Email Id</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/792/1*QqKvKEM87iupvJeoWHgimA.png" /><figcaption>image source: Google images</figcaption></figure><ol><li>In passwordless authentication, a user needs to remember only their username which is usually a phone number or email id, so it&#39;s easy to remember.</li><li>When a user enters their phone number or email id, they will receive a one-time password (OTP) to their phone or email then they have to enter it on the next screen.</li></ol><p>In this article, we will implement passwordless phone number or email id authentication in a serverless application using AWS Cognito &amp; AWS Amplify. Let’s get started!</p><h3>Overview of the solution</h3><p>The passwordless email or phone authentication solution uses an Amazon Cognito user pool and a couple of Lambda functions. You use these together to implement the custom authentication flow.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qkGYiUuxhNXaiHUPSxrMgw.png" /><figcaption>Image source: AWS</figcaption></figure><ol><li>The user enters their email id or phone number on the custom sign-in page, which sends it to the Amazon Cognito user pool.</li><li>The user pool calls the “Define Auth Challenge” Lambda function. This Lambda function determines which custom challenge needs to be created.</li><li>The user pool calls the “Create Auth Challenge” Lambda function. This Lambda function generates a secret login code and mails it to the user by using Amazon SES(In the case of phone number use Amazon SNS).</li><li>The user retrieves the secret login code from their mailbox or phone and enters it on the custom sign-in page, which sends it to the user pool.</li><li>The user pool calls the “Verify Auth Challenge Response” Lambda function. This Lambda function verifies the code that the user entered.</li><li>The user pool calls the “Define Auth Challenge” Lambda function. This Lambda function verifies that the challenge has been successfully answered and that no further challenge is needed. It includes “issueTokens: true” in its response to the user pool. The user pool now considers the user to be authenticated, and sends the user valid JSON Web Tokens (JWTs) (in the response to 4).</li></ol><h3>Creating Cognito User Pool</h3><h4>Attrib<strong>u</strong>tes</h4><ol><li>We want our users to use their phone number or email id as the username. Hence in the attributes section, choose “<strong>Email address or Phone number” </strong>and under that choose “<strong>Allow Phone numbers” or “Allow email addresses”</strong></li></ol><h4>Policies</h4><ol><li>The only thing that matters in this section is to “<strong>Allow users to sign themselves up</strong>“.</li></ol><h4>MFA and Verifications</h4><ol><li>We don’t have MFA for passwordless authentication, hence make sure “<strong>Off</strong>” is selected.</li><li>We don’t need verification as well, because the phone number is implicitly verified every time user signs in using the OTP. Select “<strong>No Verification</strong>“</li></ol><h4>App Clients</h4><ol><li>Click “<strong>Add an App Client”</strong>. Provide a name for the App Client and make sure you uncheck “<strong>Generate Client Secret</strong>“.</li></ol><h4>Triggers</h4><ol><li>AWS Cognito doesn’t support passwordless authentication out of the box. So, we will select “<strong>Enable lambda trigger-based custom authentication</strong>” and uncheck other configurations.</li><li>So first we need to create these lambda functions then triggers them through Cognito.</li></ol><h4>Define Auth Challenge</h4><p>This trigger is invoked to initiate the custom authentication flow.</p><ol><li>It will receive an session array that will have the details of all the challenges and its result.</li></ol><p>2. If the session the array is empty, which means the authentication flow has just begun. Then we will present the “<strong>CUSTOM_CHALLENGE</strong>“.</p><p>3. If the session the array is not empty, it means the user has answered the challenge and their answer is validated to be right or wrong. The validation result will be present in challengeResult the field.</p><p>4. If the answer is wrong, we will provide the same challenge once again. This way we will give the user 3 chances to enter the correct OTP. If the wrong OTP is entered in all 3 attempts we will close the session and return an error.</p><p>6. If the OTP is correct, we will log in to the user and issue the authentication tokens.</p><p>Additionally, we will also check if the user is already registered or not. If the user is not registered we will throw an error.</p><pre>const defineAuthChallenge = async (event) =&gt; {<br>try {<br>// If user is not registered<br>if (event.request.userNotFound) {<br>event.response.failAuthentication = true<br>event.response.issueTokens = false</pre><pre>throw new Error(&#39;User does not exist&#39;)<br>}</pre><pre>// Wrong otp even after 3 session<br>if (event.request.session &amp;&amp;<br>event.request.session.length &gt;= 3 &amp;&amp;<br>event.request.session.slice(-1)[0].challengeResult === false) <br>{<br>event.response.failAuthentication = true<br>event.response.issueTokens = false</pre><pre>throw new Error(&#39;Invalid OTP&#39;)<br>} else if (<br>event.request.session &amp;&amp;<br>event.request.session.length &gt; 0 &amp;&amp;<br>event.request.session.slice(-1)[0].challengeResult === true) <br>{<br>event.response.failAuthentication = false<br>event.response.issueTokens = true</pre><pre>// The user provided the right answer; succeed auth<br>console.log(&#39;Correct OTP!&#39;)</pre><pre>} else {<br>event.response.challengeName = &#39;CUSTOM_CHALLENGE&#39;<br>event.response.failAuthentication = false<br>event.response.issueTokens = false</pre><pre>// The user did not provide a correct answer yet; present challenge<br>console.log(&#39;not yet received correct OTP&#39;)<br>}</pre><pre>} catch (error) {</pre><pre>return error</pre><pre>}</pre><pre>return event</pre><pre>}</pre><h4>Create Auth Challenge</h4><p>This trigger is invoked after ‘Define Auth Challenge’ if a custom challenge has been specified as part of the ‘Define Auth Challenge’ trigger.</p><p>Once the OTP is generated, we can send the OTP using AWS SNS or AWS SES. We will also store the generated OTP in two fields:</p><ul><li>privateChallengeParamater this field will be read by Verify Auth Challenge lambda to compare it against the answer.</li><li>challengeMetaData this field will be persisted across multiple calls to Create Auth Challenge. So that we don’t have to generate a new OTP and send SMS for the 2nd and 3rd attempts, instead we can re-use the OTP generated on the 1st attempt.</li></ul><pre>const createAuthChallenge = async (event) =&gt; {</pre><pre>let secretLoginCode</pre><pre>if (!event.request.session || !event.request.session.length) {</pre><pre>const phone = event.request.userAttributes.phone_number<br>// or you can use email also<br>const email= event.request.userAttributes.email</pre><pre>secretLoginCode = Math.floor(100000 + Math.random() * 900000)</pre><pre>// This is a new auth session         <br>// Generate a new secret login code and SMS or mail it to the user<br>await SNS.sendSMS(phone, secretLoginCode)<br>await SNS.sendEmail(email, secretLoginCode) // in case of email</pre><pre>} else {</pre><pre>// re-use code generated in previous challenge<br>const previousChallenge = event.request.session.slice(-1)[0]secretLoginCode = previousChallenge.challengeMetadata.match(/CODE-(\d*)/)[1]<br>}</pre><pre>event.response.publicChallengeParameters = { phone: event.request.userAttributes.phone_number}</pre><pre>// or  in case of email<br>event.response.publicChallengeParameters = { email: event.request.userAttributes.email}</pre><pre>// Add the secret login code to the private challenge parameters<br>// so it can be verified by the &quot;Verify Auth Challenge Response&quot; <br>event.response.privateChallengeParameters = {answer: <br>secretLoginCode}</pre><pre>// Add the secret login code to the session so it is available<br>event.response.challengeMetadata = `CODE-${secretLoginCode}`</pre><pre>return event</pre><pre>}</pre><h4>Verify Auth Challenge</h4><p>This trigger is invoked to verify if the response from the end user for a custom authentication challenge is valid or not.</p><ol><li>This lambda function is responsible to check if the OTP entered by the user is correct or not.</li><li>When a user enters the OTP, it will be available in the challengeAnswer field of the event request object. We can also read the actual generated OTP from the privateChallengeParameter field and compare it to check if the user entered OTP is correct or not.</li></ol><pre>const verifyAuthChallenge = async (event) =&gt; {</pre><pre>const expectedAnswer = event.request.privateChallengeParameters.answer<br>try {<br>if (event.request.challengeAnswer === expectedAnswer) {event.response.answerCorrect = true</pre><pre>console.log(&#39;valid&#39;, expectedAnswer)<br>} else {<br>event.response.answerCorrect = false</pre><pre>// throw new Error(&#39;Invalid OTP&#39;)</pre><pre>console.log(&#39;Invalid&#39;, expectedAnswer)</pre><pre>}<br>} catch (error) {</pre><pre>return error</pre><pre>}</pre><pre>return event</pre><pre>}</pre><h4>Pre Sign Up</h4><p>his trigger is invoked when a user submits their information to sign up, allowing you to perform custom validation to accept or deny the sign up request.</p><p>This lambda function is responsible to auto confirm and auto verify phone number or email id during sign up.</p><pre>export async function preSignup (event) {</pre><pre>event.response.autoConfirmUser = true</pre><pre>// Set the SMS as verified if it is in the request</pre><pre>if (event.request.userAttributes.hasOwnProperty(&#39;phone_number&#39;)) {</pre><pre>event.response.autoVerifyPhone = true</pre><pre>}</pre><pre>// Set the email as verified if it is in the request</pre><pre>if (event.request.userAttributes.hasOwnProperty(&#39;email&#39;)) {</pre><pre>event.response.autoVerifyEmail = true</pre><pre>}</pre><pre>return event</pre><pre>}</pre><h3>Implementing the custom sign-in page</h3><p>To coordinate with the user pool’s custom authentication flow, a custom sign-in page is needed. You can use the <a href="https://aws-amplify.github.io/docs/js/authentication">AWS Amplify Framework</a> to integrate your custom sign-in page with Amazon Cognito.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e620bc30b4c2" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>