<?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 Kelvin on Medium]]></title>
        <description><![CDATA[Stories by Kelvin on Medium]]></description>
        <link>https://medium.com/@kelvinmwinuka?source=rss-70822592ab6------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/2*X5vAxmUOfg6xymPubgCPVA.jpeg</url>
            <title>Stories by Kelvin on Medium</title>
            <link>https://medium.com/@kelvinmwinuka?source=rss-70822592ab6------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 17:10:53 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@kelvinmwinuka/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[EchoVault: Embeddable Redis Alternative in Go]]></title>
            <link>https://kelvinmwinuka.medium.com/echovault-embeddable-redis-alternative-in-go-e32d7bed0ff4?source=rss-70822592ab6------2</link>
            <guid isPermaLink="false">https://medium.com/p/e32d7bed0ff4</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[redis]]></category>
            <category><![CDATA[open-source]]></category>
            <category><![CDATA[go]]></category>
            <category><![CDATA[github]]></category>
            <dc:creator><![CDATA[Kelvin]]></dc:creator>
            <pubDate>Tue, 23 Jul 2024 15:44:21 GMT</pubDate>
            <atom:updated>2024-07-23T15:44:21.137Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yik_djIPG_5IsbPeU7LQKw.png" /></figure><p>I started working on an open-source project about a year ago to build an embeddable alternative to Redis in Go. That’s when I started building the EchoVault project. Since then, the project has gained some interest and even a few contributors.</p><p>This article introduces <a href="https://github.com/EchoVault/EchoVault">EchoVault</a>, its features, use cases, and the motivations behind its development.</p><h3>What is EchoVault?</h3><p>EchoVault is an embeddable in-memory datastore tailored for Go applications. It provides a RESP-compatible interface over TCP while offering the flexibility to be embedded directly into applications.</p><p>By doing so, EchoVault aims to replace traditional in-memory data stores like Redis in some use cases, offering similar functionalities with enhanced integration for Go.</p><h3>Why EchoVault was Built</h3><p>My initial motivations for building EchoVault were:</p><ul><li>Embedded Flexibility: Traditional in-memory data stores like Redis are external services that require separate management and deployment. EchoVault eliminates this overhead by allowing developers to embed the data store directly into their applications, streamlining the deployment process.</li><li>Go Ecosystem Integration: EchoVault is designed primarily for Go, ensuring seamless integration and optimal performance within Go applications. However, it also maintains RESP compatibility over TCP, making it compatible with existing Redis clients such as redis-cli and Jedis.</li><li>Redis License Changes: EchoVault is open-source (licensed under Apache 2.0). We’re committed to staying on this fully open-source model and not open-core.</li></ul><h3>Features Provided by EchoVault</h3><p>EchoVault is packed with features that make it a robust choice for in-memory data storage:</p><ul><li>TLS and mTLS Support: Secure communication with support for multiple server and client Root Certificate Authorities (RootCAs). Replication Cluster Support: Utilizes the RAFT algorithm for replication and clustering.</li><li>Access Control Layer: Provides user authentication and authorization to secure data access.</li><li>Distributed Pub/Sub Functionality: Supports publish/subscribe to channels and patterns for real-time data processing.</li><li>Data Structures: We support a variety of data structures, including sets, sorted sets, hashes, lists, and more. We are continuing to add more data structures and commands within them.</li><li>Persistence Layer: This layer ensures data durability with snapshot and append-only file persistence. The AOF files are RESP compatible but not yet fully Redis compatible.</li><li>Key Eviction Policies: Implements various strategies for key eviction to manage memory usage. EchoVault has passive and active key eviction. With passive key eviction, expired keys are not evicted until the next time they are accessed. With active eviction, EchoVault will proactively delete keys that are expired.</li><li>Command Extensions: Allows runtime extension of commands via shared object files and an embedded API.</li></ul><p>The feature list continues to expand as we’re in the early stages of development. We have some more cool features lined up for the future, including:</p><ul><li>Streams.</li><li>Extensions with Lua modules.</li><li>Sharding.</li></ul><h3>Architecture of EchoVault</h3><p>EchoVault supports both standalone and clustered deployments.</p><h3>Standalone Mode</h3><p>In standalone mode, EchoVault operates a single (standalone) instance. This is the easiest way to run EchoVault. You can run a standalone instance from the embedded library or start it as its own process that accepts TCP connections. The embedded instance can also accept TCP connections, allowing you to communicate with your Go process from a TCP client.</p><h3>RAFT Replication Cluster Mode</h3><p>For applications requiring strong consistency and fault tolerance, EchoVault supports a RAFT-based replication cluster mode.</p><p>RAFT is a consensus algorithm that ensures data consistency across distributed systems. In this mode, multiple EchoVault instances can form a cluster, providing data replication and ensuring that data remains consistent even in the event of node failures.</p><h4>Key Features of RAFT Cluster Mode:</h4><ul><li>Fault Tolerance: Ensures data availability even if some nodes in the cluster fail.</li><li>Consistency: Guarantees that all nodes in the cluster have the same data.</li><li>Scalability: Allows for horizontal scaling by adding more nodes to the cluster.</li></ul><p>You can run EchoVault clusters even in embedded modes. This means that your application instances can communicate with each other through the EchoVault layer without having to deploy a third service. This is ideal for use cases such as session management across a cluster of an application’s instances.</p><h3>Use Cases for EchoVault</h3><p>EchoVault’s versatility makes it suitable for a wide range of applications. Here are some potential use cases:</p><ul><li>In-Memory Caching Scenario: An e-commerce website needs to cache product details and user session information to improve performance. Solution: Use EchoVault to cache frequently accessed data to speed up response times. Benefits: Faster page loads, improved user experience, and reduced database strain.</li><li>Service Discovery Scenario: A microservices architecture requires dynamic service discovery for inter-service communication. Solution: Store service endpoints in EchoVault, allowing services to discover and communicate with each other efficiently. Benefits: Simplified service discovery and enhanced communication efficiency.</li><li>Session Management Scenario: A distributed web application must manage user sessions across multiple instances. Solution: Use EchoVault embedded cluster to store session data, ensuring consistency and accessibility across all application instances. Benefits: Consistent session management across the application’s cluster without deploying a secondary service like Redis.</li><li>Real-Time Analytics Scenario: A financial trading platform requires real-time analytics and monitoring of trade data. Solution: Store and process real-time trade data in EchoVault, leveraging its sorted sets and pub/sub capabilities for tracking and analysis. Benefits: Real-time data processing and faster analytics.</li><li>Distributed Task Queue Scenario: A backend system needs to manage and distribute tasks to multiple worker nodes. Solution: Implement a task queue using EchoVault’s list data structure, where tasks are pushed onto the list and worker nodes pop tasks for processing. Benefits: Efficient task distribution and scalability.</li><li>Feature Flags and Configuration Management Scenario: A SaaS application needs to dynamically enable or disable features and manage configuration settings without redeploying the application. Solution: Store feature flags and configuration settings in EchoVault. Benefits: Dynamic configuration management and reduced downtime.</li><li>Rate Limiting and Throttling Scenario: An API gateway needs to enforce rate limits and throttle requests to prevent abuse and ensure fair usage. Solution: Implement rate limiting using EchoVault’s in-memory capabilities to track request counts and enforce limits in real-time. Benefits: Effective rate limiting and improved API reliability.</li><li>Leader Election Scenario: A cluster of distributed services needs to elect a leader to coordinate tasks. Solution: Rely on EchoVault’s embedded distributed cluster’s leader election to ensure that only one application instance is designated as the leader. Benefits: Reliable leader election and improved coordination without implementing it yourself at the application level.</li></ul><h3>Conclusion</h3><p>EchoVault is an ambitious project. In these early stages, we expect many kinks to have to be ironed out and many features to be added. However, we welcome this challenge and would love to get the Go community involved in the project.</p><p>If this article has triggered your curiosity, or you’re interested in contributing to a project like this, <a href="https://github.com/EchoVault/EchoVault">check out our GitHub</a> and drop us a star! We’re always open to more feedback and contributions!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e32d7bed0ff4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Google Login on AWS Cognito Without Hosted UI (Work-around)]]></title>
            <link>https://kelvinmwinuka.medium.com/google-login-on-aws-cognito-without-hosted-ui-work-around-81680f7757e0?source=rss-70822592ab6------2</link>
            <guid isPermaLink="false">https://medium.com/p/81680f7757e0</guid>
            <category><![CDATA[authentication]]></category>
            <category><![CDATA[webdev]]></category>
            <category><![CDATA[google]]></category>
            <category><![CDATA[cognito]]></category>
            <category><![CDATA[aws]]></category>
            <dc:creator><![CDATA[Kelvin]]></dc:creator>
            <pubDate>Sat, 23 Apr 2022 18:09:23 GMT</pubDate>
            <atom:updated>2022-04-23T18:09:23.278Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*zhA_69Tlou7A5Ggt" /></figure><p>I’ve previously written an article about <a href="https://kelvinmwinuka.com/basic-authentication-with-aws-cognito-and-nextjs">basic username/password authentication with AWS Cognito</a>. This article will cover registration and authentication using Google.</p><p>Cognito offers this functionality built into the hosted-ui. However, if you find the hosted UI to be limited in terms of design or functionality, you might want to implement this authentication method using the <a href="https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/index.html">AWS SDK</a> in your own custom UI.</p><p>Unfortunately, there is no straightforward way of doing this, so this is a possible workaround to that particular limitation.</p><p>If you haven’t read the other articles in this series, I’m using a react frontend with a nodejs backend for this tutorial. My framework of choice is NextJS. You don’t have to use this exact framework. As long as you use a JS frontend and a NodeJS backend, you should be able to adapt this tutorial to your own stack.</p><h3>Setup</h3><p>First, we need to install a couple of packages to help us out in our implementation. The 2 packages we need are react-google-login to facilitate Google login in the frontend, and google-auth-library for verifying Google tokens in the backend.</p><p>Install the packages with the following command in the terminal: npm install react-google-login google-auth-library.</p><h3>Registration</h3><p>On the registration page, import GoogleLogin from react-google-login and add the button to the layout.</p><p>You can find more information about this package and how to customise the button <a href="https://www.npmjs.com/package/react-google-login">here</a>.</p><pre>&lt;GoogleLogin<br>    clientId={process.env.NEXT_PUBLIC_GOOGLE_CLIENT_ID}<br>    responseType={&#39;id_token&#39;}<br>    buttonText=&quot;Register with Google&quot;<br>    onSuccess={googleRegisterSuccess}<br>    onFailure={googleRegisterFailure}<br>/&gt;</pre><p>We pass the googleRegisterSuccess function to the onSuccess prop. We have a useRegister hook that contains the googleRegisterSuccess function.</p><p>Now, define the googleRegisterSuccess function in the useRegister hook as follows:</p><pre>const googleRegisterSuccess = (googleResponse) =&gt; {<br>        fetch(&#39;/api/register/google&#39;, {<br>            method: &#39;POST&#39;,<br>            headers: {<br>                &#39;Content-Type&#39;: &#39;application/json&#39;<br>            },<br>            body: JSON.stringify({ id_token: googleResponse?.tokenId })<br>        }).then(res =&gt; {<br>            if (!res.ok) throw res<br>            router.push({<br>                pathname: &#39;/login&#39;<br>            })<br>        }).catch(err =&gt; {<br>            console.error(err)<br>        })<br>    }<br><br>const googleRegisterFailure = (googleResponse) =&gt; {<br>    console.error(googleResponse)<br>}</pre><p>All we’re interested in from the response object is the tokenId, which we send to the backend for verification.</p><p>In the handler for the Google register route, we have the following code:</p><pre>import { CognitoIdentityProviderClient, SignUpCommand } from &#39;@aws-sdk/client-cognito-identity-provider&#39;<br>import { OAuth2Client } from &#39;google-auth-library&#39;<br><br>const {<br>  COGNITO_REGION,<br>  COGNITO_APP_CLIENT_ID,<br>  GOOGLE_TOKEN_ISSUER,<br>  NEXT_PUBLIC_GOOGLE_CLIENT_ID,<br>} = process.env<br><br>export default async function handler(req, res) {<br>  if (req.method !== &#39;POST&#39;) return res.status(405).send()<br><br>  let googlePayload<br><br>  try {<br>    // Verify the id token from google<br>    const oauthClient = new OAuth2Client(NEXT_PUBLIC_GOOGLE_CLIENT_ID)<br>    const ticket = await oauthClient.verifyIdToken({<br>      idToken: req.body.id_token,<br>      audience: NEXT_PUBLIC_GOOGLE_CLIENT_ID<br>    })<br>    googlePayload = ticket.getPayload()<br>    if (<br>      !googlePayload?.iss === GOOGLE_TOKEN_ISSUER ||<br>      !googlePayload?.aud === NEXT_PUBLIC_GOOGLE_CLIENT_ID<br>    ) {<br>      throw new Error(&quot;Token issuer or audience invalid.&quot;)<br>    }<br>  } catch (err) {<br>    return res.status(422).json({ message: err.toString() })<br>  }<br><br>  // Register the user<br>  try {<br>    const params = {<br>      ClientId: COGNITO_APP_CLIENT_ID,<br>      Username: googlePayload.email.split(&quot;@&quot;)[0], // Username extracted from email address<br>      Password: googlePayload.sub,<br>      UserAttributes: [<br>        {<br>          Name: &#39;email&#39;,<br>          Value: googlePayload.email<br>        },<br>        {<br>          Name: &#39;custom:RegistrationMethod&#39;,<br>          Value: &#39;google&#39;<br>        }<br>      ],<br>      ClientMetadata: {<br>        &#39;EmailVerified&#39;: googlePayload.email_verified.toString()<br>      }<br>    }<br>    const cognitoClient = new CognitoIdentityProviderClient({<br>      region: COGNITO_REGION<br>    })<br>    const signUpCommand = new SignUpCommand(params)<br>    const response = await cognitoClient.send(signUpCommand)<br>    return res.status(response[&#39;$metadata&#39;].httpStatusCode).send()<br>  } catch (err) {<br>    console.log(err)<br>    return res.status(err[&#39;$metadata&#39;].httpStatusCode).json({ message: err.toString() })<br>  }<br>}</pre><p>Let’s go through what’s happening here:</p><ol><li>We need to verify the idToken by using the google-auth-library package. After verifying the token, we get a &quot;payload&quot; that contains some useful information about the user and about the token.</li><li>We need to check that the token issuer is accounts.google.com or https://accounts.google.com and that the audience matches our Google client id.</li><li>Next, we register the user with the SignUpCommand. We use a substring of the email as the username and the sub as the password. You&#39;ll want to be careful, you may need to find a more creative way to set the password.</li></ol><p>Just make sure you can reproduce the string that you pass here otherwise the user will not be able to sign in later. Here, I’ve used sub because it does not change. You can hash this, add a prefix/suffix, or both if you want to go the extra mile.</p><p>In ClientMetadata, we specify the verification status for this email address. We will be using this in the pre-signup trigger later on.</p><p>Optionally, you can set a custom attribute custom:RegistrationMethod in case you have several registration methods for your user pool.</p><h3>PreSignup Trigger</h3><p>In a previous article on <a href="https://kelvinmwinuka.com/pre-signup-validation-on-aws-cognito">cognito pre-signup triggers</a>, we added some custom logic upon signup that checks if the provided email address is already in use. Feel free to check that article out for more details on that.</p><p>We are going to add some logic to that pre-signup trigger to cater to users who register using Google.</p><pre>module.exports.handler = async (event, context, callback) =&gt; {<br>  // Check if the provided email address is already in use<br><br>  // Verify user&#39;s email address if it&#39;s already verified with Google.<br>  if (event.request.userAttributes[&#39;custom:RegistrationMethod&#39;] === &quot;google&quot;) {<br>    let userEmailVerified = event.request.clientMetadata[&#39;EmailVerified&#39;] === &#39;true&#39;<br>    event.response.autoVerifyEmail = userEmailVerified<br>    event.response.autoConfirmUser = userEmailVerified<br>  }<br><br>  callback(null, event);<br>};</pre><p>If the user’s email address is already verified by Google, we don’t need to verify it ourselves. So we set autoVerifyEmail to whatever value we set in the EmailVerified attribute of the ClientMetadata.</p><p>When you set autoVerifyEmail to true, you also have to do the same for autoConfirmUser as you cannot verify an email address without confirming the user in cognito.</p><p>You can find the code for the cognito triggers I use in this series in <a href="https://github.com/kelvinmwinuka/cognito-triggers">this Github repo</a>.</p><h3>Sign in</h3><p>Now, that we’ve handled registration, let’s handle signing in. On your login page, add the GoogleLogin button just like we did in the registration page.</p><pre>&lt;GoogleLogin <br>    clientId={process.env.NEXT_PUBLIC_GOOGLE_CLIENT_ID}<br>    buttonText=&quot;Login with Google&quot;<br>    responseType={&#39;id_token&#39;}<br>    onSuccess={googleSignInSuccess}<br>    onFailure={googleSignInFailure}<br>/&gt;</pre><p>The useAuth hook contains a googleSignInSuccess function that sends the tokenId from Google to the Google login API endpoint on the backend.</p><pre>const googleSignInSuccess = (googleResponse) =&gt; {<br>    fetch(&#39;/api/login/google&#39;, {<br>      method: &#39;POST&#39;,<br>      headers: { <br>        &#39;Content-Type&#39;: &#39;application/json&#39;<br>      },<br>      body: JSON.stringify({ id_token: googleResponse?.tokenId })<br>    }).then(res =&gt; {<br>      if (!res.ok) throw res<br>      return res.json()<br>    }).then(data =&gt; {<br>      console.log(data)<br>    }).catch(err =&gt; {<br>      console.error(err)<br>    })<br>  }<br><br>  const googleSignInFailure = (googleResponse) =&gt; {<br>    console.error(googleResponse)<br>  }</pre><p>In the backend, we handle the login as follows:</p><pre>import { CognitoIdentityProviderClient, AdminInitiateAuthCommand } from &quot;@aws-sdk/client-cognito-identity-provider&quot;;<br>import { OAuth2Client } from &quot;google-auth-library&quot;;<br><br>const {<br>  COGNITO_REGION,<br>  COGNITO_APP_CLIENT_ID,<br>  COGNITO_USER_POOL_ID,<br>  GOOGLE_TOKEN_ISSUER,<br>  NEXT_PUBLIC_GOOGLE_CLIENT_ID<br>} = process.env<br><br>export default async function handler(req, res){<br>  if (!req.method === &#39;POST&#39;) return res.status(405).send()<br><br>  let googlePayload<br><br>  try {<br>    const oauthClient = new OAuth2Client(NEXT_PUBLIC_GOOGLE_CLIENT_ID)<br>    const ticket = await oauthClient.verifyIdToken({<br>      idToken: req.body.id_token,<br>      audience: NEXT_PUBLIC_GOOGLE_CLIENT_ID<br>    })<br>    googlePayload = ticket.getPayload()<br>    if (<br>      !googlePayload?.iss === GOOGLE_TOKEN_ISSUER ||<br>      !googlePayload?.aud === NEXT_PUBLIC_GOOGLE_CLIENT_ID<br>    ) {<br>      throw new Error(&quot;Token issuer or audience invalid.&quot;)<br>    }<br>  } catch (err) {<br>    return res.status(422).json({ message: err.toString() })<br>  }<br><br>  // Sign the user in<br>  try {<br>    const params = {<br>      AuthFlow: &#39;ADMIN_USER_PASSWORD_AUTH&#39;,<br>      ClientId: COGNITO_APP_CLIENT_ID,<br>      UserPoolId: COGNITO_USER_POOL_ID,<br>      AuthParameters: {<br>        USERNAME: googlePayload?.email,<br>        PASSWORD: googlePayload?.sub<br>      }<br>    }<br>    const cognitoClient = new CognitoIdentityProviderClient({<br>      region: COGNITO_REGION<br>    })<br>    const adminInitiateAuthCommand = new AdminInitiateAuthCommand(params)<br>    const response = await cognitoClient.send(adminInitiateAuthCommand)<br>    return res.status(response[&#39;$metadata&#39;].httpStatusCode).json({<br>      ...response.AuthenticationResult<br>    })<br>  } catch (err) {<br>    console.log(err)<br>    return res.status(err[&#39;$metadata&#39;].httpStatusCode).json({ message: err.toString() })<br>  }<br>}</pre><p>The first part of the handler is quite similar to the registration: we verify the token and grab the user’s profile details along with more information about the token.</p><p>We check the token’s issuer and audience to make sure they are correct, and then we proceed to the sign in.</p><p>For signing in, we use AdminInitiateAuthCommand along with the ADMIN_USER_PASSWORD_AUTH authentication flow in the params.</p><p>AdminInitiateAuthCommand is the recommended way to handle auth in a secure backend environment as it requires developer credentials, adding an extra layer of security.</p><p>Pass the username in the params and then generate the password the same way you did in the registration handler. This is why it&#39;s important to be able to reproduce the password you created in the registration.</p><p>Although we’re logging in with Google on the surface, we’re still using username/password “under the hood”.</p><h3>Conclusion</h3><p>That’s it on this workaround on Google login with AWS Cognito without going through the hosted UI. This is not an ideal solution, but it serves the purpose if you want to quickly implement simple Google signup/sign-in in your app.</p><p>You can check out <a href="https://github.com/kelvinmwinuka/cognito-next">this repository</a> for the code I reference in this series.</p><p><em>Originally published at </em><a href="https://kelvinmwinuka.com/google-login-on-aws-cognito-without-hosted-ui-work-around"><em>https://kelvinmwinuka.com</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=81680f7757e0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Pre Signup Validation on AWS Cognito]]></title>
            <link>https://kelvinmwinuka.medium.com/pre-signup-validation-on-aws-cognito-532b473a1560?source=rss-70822592ab6------2</link>
            <guid isPermaLink="false">https://medium.com/p/532b473a1560</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[authentication]]></category>
            <category><![CDATA[cognito]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[lambda]]></category>
            <dc:creator><![CDATA[Kelvin]]></dc:creator>
            <pubDate>Mon, 18 Apr 2022 23:00:20 GMT</pubDate>
            <atom:updated>2022-04-18T23:00:20.705Z</atom:updated>
            <content:encoded><![CDATA[<p>In the last article, we leveraged AWS Cognito to handle user authentication in our application. There was a caveat with the setup, email sharing was allowed.</p><p>We want to make sure that we only have one user per email. We could build this logic into the sign-up handler in our app’s backend but there are a couple of reasons why it’s not the best practice.</p><ol><li>The validation will only live in this particular backend. If we create another app that interacts with the same user pool, we will have to repeat this logic there too.</li><li>We’re adding bloat to the request handler, we could keep this handler clean by avoiding unnecessary code if we can.</li></ol><p>Enter Cognito user pool triggers. We’ll specifically look at the pre-signup trigger. This trigger is executed before Cognito’s own signup validation with a couple of notable advantages:</p><ol><li>We can add custom validation when registering a new user to the user pool. In our case, it’s to check if the submitted email is already in use.</li><li>The logic is baked into the user pool. Any signup event for this user pool will be validated regardless of where it’s coming from.</li></ol><h3>Implementation</h3><h3>Lambda</h3><p>Make sure that the lambda is in the same region as the user pool. The following is the lambda’s code:</p><pre>const { CognitoIdentityProviderClient, ListUsersCommand } = require(&quot;<a href="http://twitter.com/aws">@aws</a>-sdk/client-cognito-identity-provider&quot;);</pre><pre>exports.handler = async (event, context, callback) =&gt; {<br>    // TODO implement<br>    const params = {<br>        UserPoolId: &#39;us-west-2_rxOJKcUKc&#39;,<br>        Filter: `email = &quot;${event.request.userAttributes.email}&quot;`<br>    };</pre><pre>const client = new CognitoIdentityProviderClient();<br>    const listUsersCommand = new ListUsersCommand(params);</pre><pre>const data = await client.send(listUsersCommand);</pre><pre>if (data?.Users?.length &gt; 0) {<br>        callback(new Error(&quot;Email is already taken&quot;), event);<br>    } else {<br>        callback(null, event);<br>    }</pre><pre>};</pre><p>Before we link this lambda to the user pool, we need to make sure it runs properly. In this example, I’m using the JavaScript v3 SDK. If we try to run this, the @aws-sdk/client-cognito-identity-provider module will not be found.</p><h3>Layer</h3><p>This section is only applicable if you’re using the v3 SDK at the time of writing this article. If you’re not using the v3 SDK, you can skip ahead to the permissions section.</p><p>We need to create a lambda layer containing this package so we can use it in the lambda. Create a new project in your development environment. Navigate to the folder and run npm init.</p><p>Complete the setup process and then run npm install @aws-sdk/client-cognito-identity-provider to install the package.</p><p>Open the package.json file and add the following line to the scripts section:</p><pre>{<br>  ...<br>  &quot;scripts&quot;: {<br>    ...<br>    &quot;build&quot;: &quot;rm -rf nodejs &amp;&amp; rm cognito-base-layer.zip &amp;&amp; npm install &amp;&amp; mkdir nodejs &amp;&amp; mv node_modules nodejs &amp;&amp; zip -r cognito-base-layer.zip . &amp;&amp; cp cognito-base-layer.zip ~/Downloads&quot;<br>  },<br>  ...<br>}</pre><p>This is the build script for the layer. It does the following:</p><ol><li>Delete the previous nodejs directory and cognito-base-layer.zip file from the previous build.</li><li>Install the packages.</li><li>Create a directory called nodejs.</li><li>Move the node_modules folder into nodejs.</li><li>Zip the current directory into a zip file called cognito-base-layer.zip.</li><li>Copy the zip file to the desired location (Optional).</li></ol><p>If you’re wondering why we move the node_modules to a subfolder, this is where the lambda will look for the installed packages. If you only have node_modules at the root, your packages will not be found.</p><p>When you’re ready, run npm run build. A new zip file will be created. Now that we have the zip file, let&#39;s create a layer:</p><p>Go to the lambda service and click on Layers</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*pi93qqQSJ-VME8PJ" /></figure><p>Click on “Create layer”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*zwSEbsJ0ZS6J6eq5" /></figure><p>Fill in the layer details:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*lA_nwJ4DDSXRCDDn" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*1vIVTNaxW0EqZUHf" /></figure><p>Name the layer whatever you like. In the upload section, upload the zip file that was generated in the previous build.</p><p>In the “compatible architectures” section, make sure to select the same architecture that your lambda is based on. In my case, it’s x86_64.</p><p>When you’re done click “Create”.</p><p>Let’s add this layer to the lambda to allow it to make use of the package(s) in the layer.</p><p>Navigate to the lambda function and click on Layers:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*OjMdBr1Xx2wBPw-s" /></figure><p>Click on Add a layer.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*_meYFBrcPXo3r0u-" /></figure><p>Fill in the layer details:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Q-lkaKISJum4IT-S" /></figure><p>For the layer source, select Custom layers. In the custom layers dropdown menu, select the layer you just created. Once selected, you&#39;ll have the option to select a layer version.</p><p>Every time you make another upload on a layer, a new version is created and the old version is kept. This is to prevent breaking lambda functions that depend on the current version as each lambda has to specify which layer version they depend on.</p><p>Once you’re done, click “Add”.</p><p>That’s it on layers, now our lambda can make use of the AWS JavaScript v3 SDK.</p><h3>Permissions</h3><p>We’re not done yet. This lambda currently doesn’t have the correct permissions to list users from a Cognito user pool. Let’s grant the correct permissions to the lambda function. First, take note of the lambda function’s role.</p><p>You can find this in the Configuration tab of the lambda function:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*kFOZjA1P1lkVrkSP" /></figure><p>Navigate to the IAM Management Console and click on the Policies tab:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*dj4899vkugZN6v3O" /></figure><p>Click on “Create Policy”:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*r7HG1fbOSPrCWEbI" /></figure><p>Click on the JSON tab and you should see a template like this:</p><pre>{<br>    &quot;Version&quot;: &quot;2012-10-17&quot;,<br>    &quot;Statement&quot;: []<br>}</pre><p>In the statement array add the following code:</p><pre>{<br>    &quot;Effect&quot;: &quot;Allow&quot;,<br>    &quot;Action&quot;: &quot;cognito-idp:ListUsers&quot;,<br>    &quot;Resource&quot;: &quot;arn:aws:cognito-idp:&lt;region&gt;:&lt;account_id&gt;:userpool/&lt;userpool_id&gt;&quot;<br>}</pre><p>The above policy statement allows us to list users from the specified Cognito user pool. Replace the Resource value with your user pool&#39;s ARN.</p><p>Now let’s attach this policy to the lambda’s role in order to allow the lambda to make use of it.</p><p>Navigate to “Roles” in the IAM Management Console:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*QKYomc5v9nmvllaG" /></figure><p>Search for the lambda’s role and click on it:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*8b0fsbEU9h5t6mPn" /></figure><p>Click on the “Add permissions” dropdown and then click on “Attach policies”:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*umzJ6Ale1qzfkSK9" /></figure><p>Search for the policy you just created, click on the check box and then click on “Attach policies” at the bottom of the page.</p><p>Now we have the right permissions and layers to execute this lambda. All we need to do now is set the lambda as a pre signup trigger for the user pool.</p><h3>Triggers</h3><p>Navigate to the user pool’s console and click on the “Triggers” tab:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*klu2CYThrcCx3GFz" /></figure><p>Click on the Pre sign-up dropdown and select the lambda function we created:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*qxPxk9V3VLODINiV" /></figure><p>Click on “Save changes” at the bottom of the page.</p><h3>Result</h3><p>That’s all there is to the setup for our use case. Now we can go ahead and try to sign up with an email address that is already used in the user pool. Doing so should return an error that looks like this:</p><pre>UserLambdaValidationException: PreSignUp failed with error Email is already taken.<br>...<br>{<br>    &#39;$fault&#39;: &#39;client&#39;,<br>    &#39;$metadata&#39;: {<br>        httpStatusCode: 400,<br>        requestId: &#39;3bc8f968-cbf5-4960-857f-e48daa312870&#39;,<br>        extendedRequestId: undefined,<br>        cfId: undefined,<br>        attempts: 1,<br>        totalRetryDelay: 0<br>  },<br>  __type: &#39;UserLambdaValidationException&#39;<br>}</pre><h3>Bonus</h3><p>“response”: { “autoConfirmUser”: “boolean”, “autoVerifyPhone”: “boolean” “autoVerifyEmail”: “boolean” }</p><p>These all default to false. They can be set to true if you&#39;d like to skip some parts of the default sign up flow. Before invoking the callback, you can add the following statements:</p><pre>event.response.autoConfirmUser = true event.response.autoVerifyPhone = true event.response.autoVerifyEmail = true</pre><p><em>Originally published at </em><a href="https://kelvinmwinuka.com/pre-signup-validation-on-aws-cognito"><em>https://kelvinmwinuka.com</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=532b473a1560" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Deploy Cognito Triggers Using Serverless Framework]]></title>
            <link>https://kelvinmwinuka.medium.com/deploy-cognito-triggers-using-serverless-framework-34ed7f77475d?source=rss-70822592ab6------2</link>
            <guid isPermaLink="false">https://medium.com/p/34ed7f77475d</guid>
            <category><![CDATA[cognito]]></category>
            <category><![CDATA[serverless-framework]]></category>
            <category><![CDATA[authentication]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[lambda]]></category>
            <dc:creator><![CDATA[Kelvin]]></dc:creator>
            <pubDate>Mon, 18 Apr 2022 22:59:20 GMT</pubDate>
            <atom:updated>2022-04-18T22:59:20.194Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*YcM_z0FEp5ew8qrk" /></figure><p>Recently, I posted an article about <a href="https://kelvinmwinuka.com/pre-signup-validation-on-aws-cognito">pre signup triggers for AWS Cognito user pools</a>. The article went over setting up pre signup validation using a lambda function.</p><p>In this article, I’m going to demonstrate how to achieve the same goal, but using the serverless framework instead of the AWS console to develop and deploy the lambdas and policies.</p><h3>Setup</h3><p>First, install the serverless framework using the following command: npm install -g serverless.</p><p>Once serverless is installed, create a project with the following command; serverless create --template aws-nodejs -n cognito-triggers.</p><p>With the command above, we’re creating a nodejs serverless project intended to be hosted on the AWS cloud platform. We then pass the name of cognito-triggers for the project.</p><p>Feel free to use whatever language you want in this project, just be sure to follow your language’s package installation and build steps where necessary.</p><h3>Implementation</h3><p>First, let’s create a .env file at the root of the project with the following content:</p><pre>COGNITO_USER_POOL_NAME=&lt;user_pool_name&gt;<br>COGNITO_USER_POOL_ID=&lt;user_pool_id&gt;<br>COGNITO_USER_POOL_ARN=&lt;user_pool_arn&gt;<br>REGION=us-west-2</pre><p>If you’re deploying to multiple environments (e.g. testing, staging, production) then you should have multiple env files in your project named in the format .env.{stage}. So the production env file will be .env.production.</p><p>For this project, we will stick to one env file for the sake of simplicity.</p><p>Let’s install a few packages we’re going to need for this project with the following command: npm install @aws-sdk/client-cognito-identity-provider dotenv serverless-dotenv-plugin</p><p>We will need the dotenv and serverless-dotenv-plugin for loading environment variables. We also need the serverless-offline package if we want to invoke our lambda functions locally. We won&#39;t be going into that in this article but you can install it with npm install -D serverless-offline.</p><p>You’ll notice that there’s a serveless.yml file at the root of the project. Open the file and add the following code:</p><pre>service: cognito-triggers</pre><pre>useDotenv: true</pre><pre>plugins:<br>  - serverless-dotenv-plugin<br>  - serverless-offline</pre><pre>frameworkVersion: &#39;3&#39;</pre><p>In the code above, we’re setting the service name, setting useDotenv: true to allow us to load environment variables.</p><p>The plugins section has 2 plugins:</p><ol><li>serverless-dotenv-plugin for loading environment variables.</li><li>serverless-offline for running the project on the local machine (in case you want to invoke the functions locally).</li></ol><p>Now let’s define the provider:</p><pre>provider:<br>  name: aws<br>  runtime: nodejs14.x<br>  stage: ${opt:stage, &#39;dev&#39;}<br>  region: ${env:REGION}<br>  profile: default<br>  iam:<br>    role:<br>      statements:<br>        - Effect: &#39;Allow&#39;<br>          Action: &#39;cognito-idp:ListUsers&#39;<br>          Resource: &#39;${env:COGNITO_USER_POOL_ARN}&#39;</pre><pre>package:<br>  patterns:<br>    - &#39;!.gitignore&#39;</pre><p>We set the provider name to aws because we&#39;re using the AWS platform. Our runtime of choice is nodejs14.x. Be sure to use a runtime that&#39;s available for the platform you&#39;re deploying to.</p><p>When setting the stage, we prefer the provided --stage in the command options. If one is not provided, default to dev. This will dictate which environment file to use when running the service offline or deploying. For example sls offline --stage staging will run the service on your local machine using .env.staging while sls deploy --stage production will deploy the service with the .env.production file.</p><p>Now for the interesting part, the actual lambda functions! At the top level of the serverless.yml file right below the provider section, create a function section with the following code:</p><pre>functions:<br>  pre_signup:<br>    handler: ./src/pre_signup.handler<br>    events:<br>      - cognitoUserPool:<br>          pool: ${env:COGNITO_USER_POOL_NAME}<br>          trigger: PreSignUp<br>          existing: true</pre><p>The functions section is where we declare the lambda functions in our service. Here we have a pre_signup function.</p><p>The handler property of the function points to the handler function exported by a js file. Make sure the path matches the location of your file. Here we have the file in an src folder that&#39;s located at the root of the project.</p><p>The events property determines what kind of events can trigger this lambda function. This can be an HTTP request through an API gateway, or in our case, a Cognito signup to a user pool.</p><p>If you already have an existing user pool, you have to set the existing property to true for the cognitoUserPool while specifying the user pool&#39;s name in the pool property.</p><p>Let’s create the js function to handle all the pre signup logic.</p><p>Create an src folder at the root of the project and then create a file called pre_signup.js within that folder. The file will have the following content:</p><pre>&#39;use strict&#39;;<br>require(&quot;dotenv&quot;).config({});</pre><pre>const { COGNITO_USER_POOL_ID } = process.env;</pre><pre>const {<br>  CognitoIdentityProviderClient,<br>  ListUsersCommand<br>} = require(&quot;<a href="http://twitter.com/aws">@aws</a>-sdk/client-cognito-identity-provider&quot;);</pre><pre>module.exports.handler = async (event, context, callback) =&gt; {<br>  const client = new CognitoIdentityProviderClient();</pre><pre>const listUsersCommand = new ListUsersCommand({<br>    UserPoolId: COGNITO_USER_POOL_ID,<br>    Filter: `email = &quot;${event.request.userAttributes.email}&quot;`<br>  });</pre><pre>const result = await client.send(listUsersCommand);</pre><pre>if (result.Users.length &gt; 0) return callback(new Error(&quot;Email is already in use.&quot;), event);</pre><pre>callback(null, event);<br>};</pre><p>This code is very familiar if you read my previous article on <a href="https://kelvinmwinuka.com/pre-signup-validation-on-aws-cognito">Pre Signup Validation on AWS Cognito</a>. Basically, we’re listing the users in our user pool that have the same email address as the one provided in this signup attempt. If we have more than 0, then throw an error stating that the email address is already in use.</p><p>Notice, we’re exporting a handler function. This is the function that we reference in the serverless.yml file.</p><p>While we’re here, let’s create another function to edit the messages sent to the user’s email address. Cognito user pools have a Custom message trigger that allows us to intercept a message before it&#39;s sent and edit its content.</p><p>In the functions section of serverless.yml, create a function called custom_message with the following properties:</p><pre>custom_message:<br>    handler: ./src/custom_message.handler<br>    events:<br>      - cognitoUserPool:<br>          pool: ${env:COGNITO_USER_POOL_NAME}<br>          trigger: CustomMessage<br>          existing: true</pre><p>It is identical to the pre_signup functions except it’s referencing a different handler and hooking into the CustomMessage trigger.</p><p>In the src folder create a custom_message.js file with the following content:</p><pre>&#39;use strict&#39;;<br>require(&quot;dotenv&quot;).config({});</pre><pre>module.exports.handler = async (event, context, callback) =&gt; {<br>  switch(event.triggerSource) {<br>    case &quot;CustomMessage_SignUp&quot;:<br>      event.response.smsMessage = `Hi ${event.userName}, your signup code is ${event.request.codeParameter}`;<br>      event.response.emailSubject = `Your registration code`;<br>      event.response.emailMessage = `Hi ${event.userName}, your signup code is ${event.request.codeParameter}`;<br>      break;<br>    case &quot;CustomMessage_ForgotPassword&quot;:<br>      event.response.smsMessage = `Hi ${event.userName}, your password reset code is ${event.request.codeParameter}. If you did not request this code, ignore this message. Please DO NOT share this code with anyone.`;<br>      event.response.emailSubject = `Your password reset code`;<br>      event.response.emailMessage = `Hi ${event.userName}, your password reset code is ${event.request.codeParameter}. If you did not request this code, ignore this email. Please DO NOT share this code with anyone.`;<br>      break;<br>    case &quot;CustomMessage_ResendCode&quot;:<br>      event.response.smsMessage = `Hi ${event.userName}, your requested code is ${event.request.codeParameter}`;<br>      event.response.emailSubject = `Your requested code`;<br>      event.response.emailMessage = `Hi ${event.userName}, your requested verification code is ${event.request.codeParameter}`;<br>      break;<br>    default:<br>      event.response.smsMessage = `Hi ${event.userName}, your requested code is ${event.request.codeParameter}`;<br>      event.response.emailSubject = `Your requested code`;<br>      event.response.emailMessage = `Hi ${event.userName}, your requested code is ${event.request.codeParameter}`;<br>  }<br>  callback(null, event);<br>}</pre><p>The handler captures different message events and displays a relevant message depending on the message event. CustomMessage_SignUp is the trigger source when the signup verification email is triggered, CustomMessage_ForgotPassword for the password reset email and CustomMessage_ResendCode when a manual code request is triggered (e.g attempting to log in when unconfirmed).</p><p>You can find more information about the different trigger sources <a href="https://docs.aws.amazon.com/cognito/latest/developerguide/user-pool-lambda-custom-message.html">here</a>.</p><p>The event object for this trigger looks like this:</p><pre>{<br>  version: &#39;1&#39;,<br>  region: &#39;us-west-2&#39;,<br>  userPoolId: &#39;&lt;user_pool_id&gt;&#39;,<br>  userName: &#39;&lt;username&gt;&#39;,<br>  callerContext: {<br>    awsSdkVersion: &#39;aws-sdk-js-3.58.0&#39;,<br>    clientId: &#39;&lt;client_id&gt;&#39;<br>  },<br>  triggerSource: &#39;CustomMessage_SignUp&#39;,<br>  request: {<br>    userAttributes: {<br>      sub: &#39;d98dad2a-c2f3-4f97-bc49-a3ed3c81f27a&#39;,<br>      email_verified: &#39;false&#39;,<br>      &#39;cognito:user_status&#39;: &#39;UNCONFIRMED&#39;,<br>      email: &#39;&lt;user_email_address&gt;&#39;<br>    },<br>    codeParameter: &#39;{####}&#39;,<br>    linkParameter: &#39;{##Click Here##}&#39;,<br>    usernameParameter: null<br>  },<br>  response: { smsMessage: null, emailMessage: null, emailSubject: null }<br>}</pre><p>Make sure you include the codeParameter in your custom message.</p><h3>Deployment</h3><p>To deploy the app, run: sls deploy. If you are deploying to a specific environment, specify it with the --stage option (e.g. sls deploy --stage staging or sls deploy --stage production).</p><p>If you’d like to remove the deployed service, run sls remove or sls remove --stage &lt;stage&gt; and the service along with any resources you might have created in this service will be destroyed.</p><p><em>Originally published at </em><a href="https://kelvinmwinuka.com/deploy-cognito-triggers-using-serverless-framework"><em>https://kelvinmwinuka.com</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=34ed7f77475d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Basic Authentication with AWS Cognito and Next.js]]></title>
            <link>https://javascript.plainenglish.io/basic-authentication-with-aws-cognito-nextjs-69ef122096cf?source=rss-70822592ab6------2</link>
            <guid isPermaLink="false">https://medium.com/p/69ef122096cf</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[nextjs]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Kelvin]]></dc:creator>
            <pubDate>Mon, 18 Apr 2022 22:42:44 GMT</pubDate>
            <atom:updated>2022-04-23T10:39:39.879Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*qeQuzbyeTc-8_uWB" /></figure><p>I’ve written quite a few articles about authentication before. This is yet another user auth article.</p><p>However, this time, it’s a little different. Previous articles have been about managing user authentication yourself. In this article, we will be leveraging AWS Cognito and its user pools for the same functionality.</p><p>You can check out some of my previous articles on handling user auth manually here:</p><ol><li><a href="https://kelvinmwinuka.com/how-to-create-registration-authentication-with-express-passportjs/#more-918">How to Create Registration &amp; Authentication with Express &amp; Passport.js</a>.</li><li><a href="https://kelvinmwinuka.com/how-to-handle-password-reset-in-expressjs/">How to Handle Password Reset in Express</a>.</li><li><a href="https://kelvinmwinuka.com/how-to-verify-users-in-expressjs/">How to Verify Users in Express</a></li></ol><h3>Setup</h3><p>This article assumes that you have an AWS Cognito user pool set up and that you have some Next.js boilerplate code set up as well. I will write another article explaining how to set up a Cognito user pool using the AWS console.</p><p>First, let’s understand the project structure.</p><pre>.<br>├── components<br>│   ├── layouts<br>│   │   └── InputLayout.js<br>│   ├── AuthLinkText.js<br>│   ├── InputField.js<br>│   ├── InputHelperText.js<br>│   ├── Label.js<br>│   └── SubmitButton.js<br>├── hooks<br>│   ├── useAuth.js<br>│   ├── useRegister.js<br>│   └── useValidationSchema.js<br>├── pages<br>│   ├── api<br>│   │   ├── confirm<br>│   │   │   ├── index.js<br>│   │   │   └── send.js<br>│   │   ├── password<br>│   │   │   ├── reset.js<br>│   │   │   └── reset_code.js<br>│   │   ├── login.js<br>│   │   └── register.js<br>│   ├── password<br>│   │   ├── reset.js<br>│   │   └── reset_code.js<br>│   ├── _app.js<br>│   ├── confirm.js<br>│   ├── index.js<br>│   ├── login.js<br>│   └── register.js<br>├── public<br>│   ├── favicon.ico<br>│   └── vercel.svg<br>├── styles<br>│   ├── Home.module.css<br>│   └── globals.css<br>├── README.md<br>├── next.config.js<br>├── package-lock.json<br>└── package.json</pre><p>Most of these are nothing special as they’re created automatically when you set up a Next.js project.</p><p>The “components” folder contains all the re-usable custom components like form input fields and layouts.</p><p>For this article, I will focus on the “hooks” and “pages” folders. If you’d like to look at the full code, you can find it on <a href="https://github.com/kelvinmwinuka/cognito-next">Github</a>.</p><p>The “hooks” folder has 3 files:</p><ol><li>useAuth.js contains a hook that will handle user sign-in and password reset.</li><li>useRegister.js contains a hook that will handle user registration and verification.</li><li>useValidationSchema.js contains the form validation schemas. We won’t be covering this in the article. Feel free to check the repo out for more details on this.</li></ol><p>I prefer to use hooks because they allow me to separate the business logic from the UI logic in the component.</p><p>The “pages” folder has an “API” sub-directory. This is where all the backend code lives.</p><p>Next.js uses file system-based routing so the file structure is what determines the API endpoints.</p><p>All the other files and sub-directories outside the API sub-directory will be treated as frontend pages.</p><p>Make sure to install the <a href="https://www.npmjs.com/package/@aws-sdk/client-cognito-identity-provider">@aws-sdk/client-cognito-identity-provider</a> package.</p><p>You can refer to the full <a href="https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/clients/client-cognito-identity-provider/index.html#aws-sdkclient-cognito-identity-provider">CognitoIdentityServiceProvider SDK</a> for more in-depth explanations of what is discussed in this article.</p><h3>Sign Up</h3><p>First, let’s handle user registration. Navigate to the “pages/api/register.js” and add the following code:</p><pre>import { CognitoIdentityProviderClient, SignUpCommand } from &#39;<a href="http://twitter.com/aws">@aws</a>-sdk/client-cognito-identity-provider&#39;</pre><pre>const { COGNITO_REGION, COGNITO_APP_CLIENT_ID } = process.env</pre><pre>export default async function handler(req, res) {<br>    if (req.method !== &#39;POST&#39;) return res.status(405).send()</pre><pre>const params = {<br>        ClientId: COGNITO_APP_CLIENT_ID,<br>        Password: req.body.password,<br>        Username: req.body.username,<br>        UserAttributes: [<br>            {<br>                Name: &#39;email&#39;,<br>                Value: req.body.email<br>            }<br>        ]<br>    }</pre><pre>const cognitoClient = new CognitoIdentityProviderClient({<br>        region: COGNITO\_REGION<br>    })<br>    const signUpCommand = new SignUpCommand(params)</pre><pre>try {<br>        const response = await cognitoClient.send(signUpCommand)<br>        return res.status(response[&#39;$metadata&#39;].httpStatusCode).send()<br>    } catch (err) {<br>        console.log(err)<br>        return res.status(err[&#39;$metadata&#39;].httpStatusCode).json({ message: err.toString() })<br>    }<br>}</pre><p>This is a handler for the “/api/register” endpoint. Include a guard clause to make sure only POST requests are allowed, return a 405 error for any other type of request.</p><p>In the params, we have the following:</p><ol><li>ClientId — App client Id that you created for this user pool in the AWS console.</li><li>Password — The user’s chosen password.</li><li>Username -The user’s chosen username.</li><li>UserAttributes — Any additional attributes provided by the user upon signing up. The default list of attributes includes address, nickname, birthdate, phone number, email, family name, preferred username, gender, profile, given name, zoneinfo, locale, updated at, middle name, website and name. You can add custom attributes as well (for example, “Department” if you’re creating an auth system for an organisation).</li></ol><p>Keep in mind that if you’re setting a custom user attribute you need to follow the following format:</p><pre>{<br>    Name: &#39;custom:&lt;AttributeName&gt;&#39;,                <br>    Value: &#39;&lt;AttributeValue&gt;&#39;<br>}</pre><p>In the case of adding a department attribute, it would look like this:</p><pre>{<br>    Name: &#39;custom:Department&#39;,                <br>    Value: &#39;Engineering&#39;<br>}</pre><p>Then we send the SignUpCommand to trigger a user sign up. Return a status 200 response if all goes well, otherwise, return the error code from Cognito and the stringified version of the error.</p><p>Cognito will usually return an error that looks like this:</p><pre>UsernameExistsException: User already exists<br>...<br>{<br>  &#39;$fault&#39;: &#39;client&#39;,<br>  &#39;$metadata&#39;: {<br>    httpStatusCode: 400,<br>    requestId: &#39;9442223e-ef29-40c1-880e-6689638d8042&#39;,<br>    extendedRequestId: undefined,<br>    cfId: undefined,<br>    attempts: 1,<br>    totalRetryDelay: 0<br>  },<br>  __type: &#39;UsernameExistsException&#39;<br>}</pre><p>Grab the status code and message and then forward them to the front end.</p><p>When the request is successful, Cognito will return a response that looks like this:</p><pre>{<br>  &#39;$metadata&#39;: {<br>    httpStatusCode: 200,<br>    requestId: &#39;67f6d99c-d13c-4677-ab46-957d88f62bb9&#39;,<br>    extendedRequestId: undefined,<br>    cfId: undefined,<br>    attempts: 1,<br>    totalRetryDelay: 0<br>  },<br>  AuthenticationResult: {<br>    AccessToken: &quot;...&quot;,<br>    ExpiresIn: 3600,<br>    NewDeviceMetadata: undefined,<br>    RefreshToken: &quot;...&quot;,<br>    TokenType: &quot;Bearer&quot;<br>  },<br>  ChallengeName: undefined,<br>  ChallengeParameters: {},<br>  Session: undefined<br>}</pre><p>For this application, we’re only interested in the Authentication result as it contains the access and refresh tokens.</p><p>Flesh out the useRegister hook in order to make use of the API endpoint we created above.</p><p>Create a method called “register” with the following logic:</p><pre>import { useRouter } from &#39;next/router&#39;</pre><pre>export default function useRegister() {</pre><pre>const router = useRouter()</pre><pre>const register = (values, { setSubmitting }) =&gt; {<br>        fetch(&#39;/api/register&#39;, {<br>            method: &#39;POST&#39;,<br>            headers: {<br>                &#39;Content-Type&#39;: &#39;application/json&#39;<br>            },<br>            body: JSON.stringify(values)<br>        }).then(res =&gt; {<br>            if (!res.ok) throw res<br>            router.push({<br>                pathname: &#39;/confirm&#39;,<br>                query: { username: values?.username }<br>            },<br>                &quot;/confirm&quot;)<br>        }).catch(err =&gt; {<br>            console.error(err)<br>        }).finally(() =&gt; {<br>            setSubmitting(false)<br>        })<br>    }</pre><pre>const confirm = (values, { setSubmitting }) =&gt; {<br>        // Confirm the user<br>    }</pre><pre>return {<br>        register,<br>        confirm<br>    }<br>}</pre><p>The register method is the submit method for our registration form. The “values” object contains the form data and “setSubmitting” allows us to update the loading state once we’re done processing the request.</p><p>This will be a common theme with most of the hooks in this project.</p><p>Set the Content-Type header to “application/json” to help Next.js parse the request body.</p><p>In this method, we call the register endpoint and pass all the form values (which include username, email, and password). If the request is successful, we redirect to the confirm page and prompt the user to verify their email address. More on this in the <a href="https://kelvinmwinuka.com/basic-authentication-with-aws-cognito-and-nextjs#verification">verification</a> section.</p><p>You might notice we have an empty confirm method here. This method will handle the request to verify the user. We will cover this in the verification stage as well.</p><p>Here is what the registration form will look like, notice we import the useRegister hook and pass the register method as the form submit handler.</p><pre>import { Formik } from &quot;formik&quot;;<br>import InputLayout from &quot;../components/layouts/InputLayout&quot;;<br>import Label from &quot;../components/Label&quot;;<br>import InputField from &quot;../components/InputField&quot;;<br>import InputHelperText from &quot;../components/InputHelperText&quot;;<br>import AuthLinkText from &quot;../components/AuthLinkText&quot;;<br>import SubmitButton from &quot;../components/SubmitButton&quot;;<br>import useValidationSchema from &quot;../hooks/useValidationSchema&quot;;<br>import useRegister from &#39;../hooks/useRegister&#39;<br>import Link from &quot;next/link&quot;;</pre><pre>export default function Register() {</pre><pre>const { registerSchema } = useValidationSchema()<br>    const { register } = useRegister()</pre><pre>return (<br>        &lt;div style={{<br>            padding: &quot;10px&quot;<br>        }}&gt;<br>            &lt;Formik<br>                initialValues={{<br>                    username: &quot;&quot;,<br>                    email: &quot;&quot;,<br>                    password: &quot;&quot;,<br>                    confirm_password: &quot;&quot;<br>                }}<br>                validationSchema={registerSchema}<br>                onSubmit={register}<br>                validateOnMount={false}<br>                validateOnChange={false}<br>                validateOnBlur={false}&gt;<br>                {({<br>                    isSubmitting,<br>                    errors,<br>                    values,<br>                    handleSubmit,<br>                    handleChange,<br>                    handleBlur<br>                }) =&gt; (<br>                    &lt;form onSubmit={handleSubmit}&gt;<br>                        &lt;InputLayout&gt;<br>                            &lt;Label&gt;Username&lt;/Label&gt;<br>                            &lt;InputField<br>                                type=&quot;text&quot;<br>                                name=&quot;username&quot;<br>                                placeholder=&quot;Username&quot;<br>                                onChange={handleChange}<br>                                onBlur={handleBlur}<br>                                value={values?.username}<br>                            /&gt;<br>                            &lt;InputHelperText isError&gt;{errors?.username}&lt;/InputHelperText&gt;<br>                        &lt;/InputLayout&gt;<br>                        &lt;InputLayout&gt;<br>                            &lt;Label&gt;Email&lt;/Label&gt;<br>                            &lt;InputField<br>                                type=&quot;email&quot;<br>                                name=&quot;email&quot;<br>                                placeholder=&quot;Email&quot;<br>                                onChange={handleChange}<br>                                onBlur={handleBlur}<br>                                value={values?.email}<br>                            /&gt;<br>                            &lt;InputHelperText isError&gt;{errors?.email}&lt;/InputHelperText&gt;<br>                        &lt;/InputLayout&gt;<br>                        &lt;InputLayout&gt;<br>                            &lt;Label&gt;Password&lt;/Label&gt;<br>                            &lt;InputField<br>                                type=&quot;password&quot;<br>                                name=&quot;password&quot;<br>                                placeholder=&quot;Password&quot;<br>                                onChange={handleChange}<br>                                onBlur={handleBlur}<br>                                value={values?.password}<br>                            /&gt;<br>                            &lt;InputHelperText isError&gt;{errors?.password}&lt;/InputHelperText&gt;<br>                        &lt;/InputLayout&gt;<br>                        &lt;InputLayout&gt;<br>                            &lt;Label&gt;Confirm password&lt;/Label&gt;<br>                            &lt;InputField<br>                                type=&quot;password&quot;<br>                                name=&quot;confirm_password&quot;<br>                                placeholder=&quot;Confirm password&quot;<br>                                onChange={handleChange}<br>                                onBlur={handleBlur}<br>                                value={values?.confirm_password}<br>                            /&gt;<br>                            &lt;InputHelperText isError&gt;{errors?.confirm_password}&lt;/InputHelperText&gt;<br>                        &lt;/InputLayout&gt;<br>                        &lt;InputLayout&gt;<br>                            &lt;AuthLinkText href=&quot;/login&quot;&gt;Already have an account? Log in&lt;/AuthLinkText&gt;<br>                        &lt;/InputLayout&gt;<br>                        &lt;SubmitButton isSubmitting={isSubmitting} /&gt;<br>                    &lt;/form&gt;<br>                )}<br>            &lt;/Formik&gt;<br>        &lt;/div&gt;<br>    )<br>}</pre><h3>Sign In</h3><p>Now that we’ve registered our users, it’s time to allow them to log into our application by authenticating them against our Cognito user pool.</p><p>Add the following code to the “pages/api/login.js” file.</p><pre>import { CognitoIdentityProviderClient, AdminInitiateAuthCommand } from &quot;@aws-sdk/client-cognito-identity-provider&quot;<br><br>const { COGNITO_REGION, COGNITO_APP_CLIENT_ID, COGNITO_USER_POOL_ID } = process.env<br><br>export default async function handler(req, res) {<br>    if (req.method !== &#39;POST&#39;) return res.status(405).send()<br><br>    const params = {<br>        AuthFlow: &#39;ADMIN_USER_PASSWORD_AUTH&#39;,<br>        ClientId: COGNITO_APP_CLIENT_ID,<br>        UserPoolId: COGNITO_USER_POOL_ID,<br>        AuthParameters: {<br>            USERNAME: req.body.username,<br>            PASSWORD: req.body.password<br>        }<br>    }<br><br>    const cognitoClient = new CognitoIdentityProviderClient({<br>        region: COGNITO_REGION<br>    })<br>    const adminInitiateAuthCommand = new AdminInitiateAuthCommand(params)<br><br>    try {<br>        const response = await cognitoClient.send(adminInitiateAuthCommand)<br>        console.log(response)<br>        return res.status(response[&#39;$metadata&#39;].httpStatusCode).json({<br>            ...response.AuthenticationResult<br>        })<br>    } catch(err) {<br>        console.log(err)<br>        return res.status(err[&#39;$metadata&#39;].httpStatusCode).json({ message: err.toString() })<br>    }<br>}</pre><p>At the moment, we’re handling only username/password auth. To do this we need to use the ADMIN_USER_PASSWORD_AUTH flow. This authentication flow requires developer credentials. If you&#39;re authenticating users in a secure server, this is the recommended method over InitiateAuthCommand with USER_PASSWORD_AUTH.</p><p>The final parameter is AuthParameters. This simply contains the username and password passed to the endpoint upon form submission. Be careful here and make sure the auth parameters are in all uppercase as you see here, otherwise, they will not be recognised.</p><p>Now let’s divert our attention to the “useAuth” hook. Add this code to the “hooks/useAuth.js” file:</p><pre>import { useRouter } from &quot;next/router&quot;;</pre><pre>export default function useAuth(){</pre><pre>const router = useRouter()</pre><pre>const login = (values, { setSubmitting }) =&gt; {<br>    fetch(&#39;/api/login&#39;, {<br>      method: &#39;POST&#39;,<br>      headers: {<br>        &#39;Content-Type&#39;: &#39;application/json&#39;<br>      },<br>      body: JSON.stringify(values)<br>    }).then(res =&gt; {<br>      if (!res.ok) throw res<br>    }).then(data =&gt; {<br>      console.log(data)<br>    }).catch(async err =&gt; {<br>      const responseData = await err.json()<br>      if (responseData?.message?.includes(&quot;UserNotConfirmedException:&quot;)) {<br>        // Trigger confirmation code email<br>        await fetch(&#39;/api/confirm/send&#39;, {<br>          method: &#39;POST&#39;,<br>          headers: {<br>            &#39;Content-Type&#39;: &#39;application/json&#39;<br>          },<br>          body: JSON.stringify({ username: values.username })<br>        })<br>        await router.push(<br>      {<br>            pathname: &quot;/confirm&quot;,<br>            query: {username: values.username},<br>          },<br>          &quot;/confirm&quot;)<br>      }<br>    }).finally(() =&gt; {<br>      setSubmitting(false)<br>    })<br>  }</pre><pre>const resetPasswordRequest = (values, { setSubmitting }) =&gt; {<br>    // Send the password reset code<br>  }</pre><pre>const resetPassword = (values, { setSubmitting }) =&gt; {<br>    // Send request to reset password<br>  }</pre><pre>return {<br>    login,<br>    resetPasswordRequest,<br>    resetPassword<br>  }<br>}</pre><p>Here we have a login method that is similar to the register method we created above. The “values” object represents our form data (username and password).</p><p>It’s important to note that Cognito will not allow a user to be authenticated if they have not yet been verified/confirmed. So attempting this login with an unconfirmed user will return an error.</p><p>To handle this, trigger an endpoint to send a confirmation email to the user and then redirect them to the confirm page so they can be verified. More on this endpoint in the <a href="https://kelvinmwinuka.com/basic-authentication-with-aws-cognito-and-nextjs#verification">verification</a> section.</p><p>Our login page has the following code:</p><pre>import { Formik } from &quot;formik&quot;;<br>import InputLayout from &quot;../components/layouts/InputLayout&quot;;<br>import Label from &quot;../components/Label&quot;;<br>import InputField from &quot;../components/InputField&quot;;<br>import InputHelperText from &quot;../components/InputHelperText&quot;;<br>import AuthLinkText from &quot;../components/AuthLinkText&quot;;<br>import SubmitButton from &quot;../components/SubmitButton&quot;;<br>import useAuth from &quot;../hooks/useAuth&quot;;<br>import useValidationSchema from &quot;../hooks/useValidationSchema&quot;;<br>import { useRouter } from &quot;next/router&quot;;</pre><pre>export default function Login() {</pre><pre>const router = useRouter();<br>  const { success } = router.query;</pre><pre>const { loginSchema } = useValidationSchema();<br>  const { login } = useAuth();</pre><pre>return (<br>    &lt;div style={{<br>      padding: &quot;10px&quot;<br>    }}&gt;<br>      {<br>        success === &quot;true&quot; &amp;&amp;<br>        &lt;div style={{<br>          paddingTop: &quot;10px&quot;,<br>          paddingBottom: &quot;10px&quot;,<br>          color: &quot;green&quot;<br>        }}&gt;<br>          {&#39;You\\&#39;re signed up!&#39;}<br>        &lt;/div&gt;<br>      }<br>      &lt;Formik<br>        initialValues={{<br>          username: &quot;&quot;,<br>          password: &quot;&quot;<br>        }}<br>        validationSchema={loginSchema}<br>        onSubmit={login}<br>        validateOnMount={false}<br>        validateOnChange={false}<br>        validateOnBlur={false}&gt;<br>        {({<br>          isSubmitting,<br>          errors,<br>          values,<br>          handleChange,<br>          handleBlur,<br>          handleSubmit<br>        }) =&gt; (<br>          &lt;form onSubmit={handleSubmit}&gt;<br>            &lt;InputLayout&gt;<br>              &lt;Label&gt;Username&lt;/Label&gt;<br>              &lt;InputField<br>                type=&quot;text&quot;<br>                name=&quot;username&quot;<br>                placeholder=&quot;Username or email&quot;<br>                onChange={handleChange}<br>                onBlur={handleBlur}<br>                value={values?.username}<br>              /&gt;<br>              &lt;InputHelperText isError&gt;{errors?.username}&lt;/InputHelperText&gt;<br>            &lt;/InputLayout&gt;<br>            &lt;InputLayout&gt;<br>              &lt;Label&gt;Password&lt;/Label&gt;<br>              &lt;InputField<br>                type=&quot;password&quot;<br>                name=&quot;password&quot;<br>                placeholder=&quot;Password&quot;<br>                onChange={handleChange}<br>                onBlur={handleBlur}<br>                value={values?.password}<br>              /&gt;<br>              &lt;InputHelperText isError&gt;{errors?.password}&lt;/InputHelperText&gt;<br>            &lt;/InputLayout&gt;<br>            &lt;InputLayout&gt;<br>              &lt;AuthLinkText href=&quot;/password/reset_code&quot;&gt;{&#39;Forgot password?&#39;}&lt;/AuthLinkText&gt;<br>            &lt;/InputLayout&gt;<br>            &lt;InputLayout&gt;<br>              &lt;AuthLinkText href=&quot;/register&quot;&gt;{&#39;Don\\&#39;t have an account? Register.&#39;}&lt;/AuthLinkText&gt;<br>            &lt;/InputLayout&gt;<br>            &lt;SubmitButton isSubmitting={isSubmitting} /&gt;<br>          &lt;/form&gt;<br>        )}<br>      &lt;/Formik&gt;<br>    &lt;/div&gt;<br>  );<br>}</pre><p>Just like before, we import the useAuth hook and make use of its login method as the form submission handler.</p><p>We will discuss the 2 password reset methods in the useAuth hook in the <a href="https://kelvinmwinuka.com/basic-authentication-with-aws-cognito-and-nextjs#passwordreset">password reset</a> section.</p><h3>Verification</h3><p>So we’ve registered our users, but we cannot authenticate them because they are not verified. Let’s fix that.</p><p>A few things to note before we continue:</p><ol><li>I have set up my user pool to use an email code for verification. This is where AWS will send an email with a code that the user has to enter manually on your app. Other authentication methods include: a clickable verification link and a verification code sent to their phone number. If you are using any of the other verification methods (except verification code to a phone number), then you can go ahead and skip this section.</li><li>Cognito will automatically trigger the chosen verification method upon successful registration. Verification can also be triggered via the SDK.</li></ol><p>In the “pages/api/confirm/index.js” file, add the following code:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*5jj8JqQpjw_o6X-MgnT9Xg.png" /></figure><pre>import {<br>    CognitoIdentityProviderClient,<br>    ConfirmSignUpCommand<br>} from &quot;<a href="http://twitter.com/aws">@aws</a>-sdk/client-cognito-identity-provider&quot;</pre><pre>const { COGNITO_REGION, COGNITO_APP_CLIENT_ID } = process.env</pre><pre>export default async function handler (req, res) {<br>    if (req.method !== &#39;POST&#39;) return res.status(405).send()</pre><pre>const params = {<br>        ClientId: COGNITO_APP_CLIENT_ID,<br>        ConfirmationCode: req.body.code,<br>        Username: req.body.username<br>    }</pre><pre>const cognitoClient = new CognitoIdentityProviderClient({<br>        region: COGNITO_REGION<br>    })<br>    const confirmSignUpCommand = new ConfirmSignUpCommand(params)</pre><pre>try {<br>        const response = await cognitoClient.send(confirmSignUpCommand)<br>        console.log(response)<br>        return res.status(response[&#39;$metadata&#39;].httpStatusCode).send()<br>    } catch (err) {<br>        console.log(err)<br>        return res.status(err[&#39;$metadata&#39;].httpStatusCode).json({ message: err.toString() })<br>    }<br>}</pre><p>Here create and send confirmSignUpCommand with the following parameters:</p><ol><li>ClientId.</li><li>ConfirmationCode — The code sent to the user’s email/phone by Cognito.</li><li>Username — The username of the user you’d like to verify.</li></ol><p>Note that because this is the index file within the confirm directory, we do not need to specify the filename when calling this endpoint. The endpoint would just be “/api/confirm”</p><p>In the same confirm directory, we have a file called “send.js”. This file is responsible for manually triggering the confirmation code email.</p><p>Add the following code to this file:</p><pre>import {<br>    CognitoIdentityProviderClient,<br>    ResendConfirmationCodeCommand<br>} from &quot;<a href="http://twitter.com/aws">@aws</a>-sdk/client-cognito-identity-provider&quot;</pre><pre>const { COGNITO_REGION, COGNITO_APP_CLIENT_ID } = process.env</pre><pre>export default async function handler (req, res) {<br>    if (req.method !== &#39;POST&#39;) return res.status(405).send()</pre><pre>const params = {<br>        ClientId: COGNITO_APP_CLIENT_ID,<br>        Username: req.body.username<br>    }</pre><pre>const cognitoClient = new CognitoIdentityProviderClient({<br>        region: COGNITO_REGION<br>    })<br>    const resendConfirmationCodeCommand = new ResendConfirmationCodeCommand(params)</pre><pre>try {<br>        const response = await cognitoClient.send(resendConfirmationCodeCommand)<br>        console.log(response)<br>        return res.status(response[&#39;$metadata&#39;].httpStatusCode).send()<br>    } catch (err) {<br>        console.log(err)<br>        return res.stat(err[&#39;$metadata&#39;].httpStatusCode).json({ message: err.toString() })<br>    }<br>}</pre><p>Here, simply create and send ResendConfirmationCodeCommand with a params object containing the ClientId and the username of the user you&#39;d like to verify.</p><p>Cognito will search for the user with the specified username, then send a verification code to their email/phone number depending on your settings and/or which one is provided.</p><p>You might be wondering why this command is called ResendConfirmationCodeCommand.</p><p>Cognito will automatically send a verification code to the user upon signing up.</p><p>If you are triggering the registration manually, then you are always “re-sending” the code.</p><p>Remember that “confirm” method in the useRegister hook? It’s time to flesh it out.</p><p>Add the following logic in that method:</p><pre>const confirm = (values, { setSubmitting }) =&gt; {<br>        fetch(&#39;/api/confirm&#39;, {<br>            method: &#39;POST&#39;,<br>            headers: {<br>                &#39;Content-Type&#39;: &#39;application/json&#39;<br>            },<br>            body: JSON.stringify(values)<br>        }).then(res =&gt; {<br>            if (!res.ok) throw res<br>            router.push({<br>                pathname: &#39;/login&#39;,<br>                query: { confirmed: true }<br>            },<br>                &quot;/login&quot;)<br>        }).catch(err =&gt; {<br>            console.error(err)<br>        }).finally(() =&gt; {<br>            setSubmitting(false)<br>        })<br>    }</pre><p>From this method, call the “/api/confirm” endpoint with the form values. If the confirmation is successful, redirect the user to the login page so they can sign in.</p><p>Here’s a look at the confirm page in the “pages/confirm.js” file:</p><pre>import { Formik } from &quot;formik&quot;;<br>import InputLayout from &quot;../components/layouts/InputLayout&quot;;<br>import Label from &quot;../components/Label&quot;;<br>import InputField from &quot;../components/InputField&quot;;<br>import InputHelperText from &quot;../components/InputHelperText&quot;;<br>import SubmitButton from &quot;../components/SubmitButton&quot;;<br>import useValidationSchema from &quot;../hooks/useValidationSchema&quot;;<br>import useRegister from &quot;../hooks/useRegister&quot;;<br>import { useRouter } from &quot;next/router&quot;;</pre><pre>export default function Confirm(){</pre><pre>const router = useRouter();<br>    const { username } = router.query;</pre><pre>const { confirm } = useRegister();<br>    const { confirmSchema } = useValidationSchema();</pre><pre>return (<br>        &lt;div style={{<br>            padding: &quot;10px&quot;<br>        }}&gt;<br>            &lt;Formik<br>                initialValues={{<br>                    username: username,<br>                    code: &quot;&quot;<br>                }}<br>                onSubmit={confirm}<br>                validationSchema={confirmSchema}<br>                validateOnMount={false}<br>                validateOnChange={false}<br>                validateOnBlur={false}&gt;<br>                {<br>                    ({<br>                        isSubmitting,<br>                        errors,<br>                        values,<br>                        handleSubmit,<br>                        handleChange,<br>                        handleBlur<br>                     }) =&gt; (<br>                        &lt;form onSubmit={handleSubmit}&gt;<br>                            &lt;InputLayout&gt;<br>                                &lt;Label&gt;Confirmation Code&lt;/Label&gt;<br>                                &lt;InputField<br>                                    type={&quot;text&quot;}<br>                                    name={&quot;code&quot;}<br>                                    placeholder={&quot;Code&quot;}<br>                                    onChange={handleChange}<br>                                    onBlur={handleBlur}<br>                                    value={values?.code}<br>                                /&gt;<br>                                &lt;InputHelperText isError&gt;{errors?.code}&lt;/InputHelperText&gt;<br>                            &lt;/InputLayout&gt;<br>                            &lt;SubmitButton isSubmitting={isSubmitting} /&gt;<br>                        &lt;/form&gt;<br>                    )<br>                }<br>            &lt;/Formik&gt;<br>        &lt;/div&gt;<br>    )<br>}</pre><h3>Password reset</h3><p>One of the most important features in any auth system is the ability to reset passwords.</p><p>Fortunately, password reset is made dead simple by Cognito.</p><p>The password reset flow is similar to the verification flow but with some extra steps:</p><ol><li>The user clicks the “Forgot password” link and is redirected to a page where they are prompted to enter their username.</li><li>Send a confirmation code to the user’s email/number.</li><li>If the code is sent successfully, redirect the user to a reset page where they enter the code, along with their new password.</li></ol><p>First, prepare the endpoint to trigger the verification email containing the code.</p><p>Add the following code to “pages/api/password/reset_code.js”:</p><pre>import { CognitoIdentityProviderClient, ForgotPasswordCommand } from &#39;<a href="http://twitter.com/aws">@aws</a>-sdk/client-cognito-identity-provider&#39;</pre><pre>const { COGNITO_REGION, COGNITO_APP_CLIENT_ID } = process.env</pre><pre>export default async function handler (req, res) {<br>    if (req.method !== &#39;POST&#39;) return res.status(405).send()</pre><pre>const params = {<br>        ClientId: COGNITO_APP_CLIENT_ID,<br>        Username: req.body.username<br>    }</pre><pre>const cognitoClient = new CognitoIdentityProviderClient({<br>        region: COGNITO_REGION<br>    })<br>    const forgotPasswordCommand = new ForgotPasswordCommand(params)</pre><pre>try {<br>        const response = await cognitoClient.send(forgotPasswordCommand)<br>        console.log(response)<br>        return res.status(response[&#39;$metadata&#39;].httpStatusCode).send()<br>    } catch (err) {<br>        console.log(err)<br>        return res.status(err[&#39;$metadata&#39;].httpStatusCode).json({ message: toString() })<br>    }<br>}</pre><p>Here we accept the ClientId and username params for the “ForgotPasswordCommand” command. Cognito will find a user with the matching username and send them a verification code using the configured method.</p><p>In the “pages/api/password/reset.js” file, add the code below:</p><pre>import {<br>    CognitoIdentityProviderClient,<br>    ConfirmForgotPasswordCommand<br>} from &quot;<a href="http://twitter.com/aws">@aws</a>-sdk/client-cognito-identity-provider&quot;</pre><pre>const { COGNITO_REGION, COGNITO_APP_CLIENT_ID } = process.env</pre><pre>export default async function handler(req, res) {<br>    if (req.method !== &#39;POST&#39;) return res.status(405).send()</pre><pre>const params = {<br>        ClientId: COGNITO_APP_CLIENT_ID,<br>        ConfirmationCode: req.body.code,<br>        Password: req.body.password,<br>        Username: req.body.username<br>    }</pre><pre>const cognitoClient = new CognitoIdentityProviderClient({<br>        region: COGNITO_REGION<br>    })<br>    const confirmForgotPasswordCommand = new ConfirmForgotPasswordCommand(params)</pre><pre>try {<br>        const response = await cognitoClient.send(confirmForgotPasswordCommand)<br>        console.log(response)<br>        return res.status(response[&#39;$metadata&#39;].httpStatusCode).send()<br>    } catch (err) {<br>        console.log(err)<br>        return res.status(err[&#39;$metadata&#39;].httpStatusCode).json({ message: err.toString() })<br>    }<br>}</pre><p>Here we accept the ConfirmationCode that was sent to the user, their new password and their username.</p><p>Cognito will take care of all the logic of making sure that the code provided is valid and is the one that was sent to the user with the specified username.</p><p>You’ll remember that in the useAuth hook, we had 2 empty methods “resetPasswordRequest” and “resetPassword”. We are going to flesh those out now.</p><p>Add the following logic to those methods:</p><pre>const resetPasswordRequest = (values, { setSubmitting }) =&gt; {<br>    fetch(&#39;/api/password/reset\_code&#39;, {<br>      method: &#39;POST&#39;,<br>      headers: {<br>        &#39;Content-Type&#39;: &#39;application/json&#39;<br>      },<br>      body: JSON.stringify(values)<br>    }).then(res =&gt; {<br>      if (!res.ok) throw res<br>      router.push({<br>        pathname: &#39;/password/reset&#39;,<br>        query: { username: values.username }<br>      },<br>        &quot;/password/reset&quot;)<br>    }).catch(err =&gt; {<br>      console.error(err)<br>    }).finally(() =&gt; {<br>      setSubmitting(false)<br>    })<br>  }</pre><pre>const resetPassword = (values, { setSubmitting }) =&gt; {<br>    fetch(&#39;/api/password/reset&#39;, {<br>      method: &#39;POST&#39;,<br>      headers: {<br>        &#39;Content-Type&#39;: &#39;application/json&#39;<br>      },<br>      body: JSON.stringify(values)<br>    }).then(res =&gt; {<br>      if (!res.ok) throw res<br>      router.push({<br>        pathname: &#39;/login&#39;,<br>        query: { reset: true }<br>      },<br>        &quot;/login&quot;)<br>    }).catch(err =&gt; {<br>      console.error(err)<br>    }).finally(() =&gt; {<br>      setSubmitting(false)<br>    })<br>  }</pre><p>The resetPasswordRequest method triggers the &quot;/api/password/reset_code&quot; endpoint.</p><p>From the user’s perspective, they are redirected to a page where they enter their username. Once they submit the form, they receive an email and are redirected to the password reset page (if the email was successfully sent).</p><p>The resetPassword method triggers the &quot;/api/password/reset&quot; endpoint to actually reset the password.</p><p>Here’s how the forgot password form looks:</p><pre>import { Formik } from &quot;formik&quot;;<br>import InputLayout from &quot;../../components/layouts/InputLayout&quot;;<br>import Label from &quot;../../components/Label&quot;;<br>import InputField from &quot;../../components/InputField&quot;;<br>import InputHelperText from &quot;../../components/InputHelperText&quot;;<br>import SubmitButton from &quot;../../components/SubmitButton&quot;;<br>import useValidationSchema from &quot;../../hooks/useValidationSchema&quot;;<br>import useAuth from &#39;../../hooks/useAuth&#39;;</pre><pre>export default function ResetCode(){</pre><pre>const { resetPasswordRequestSchema } = useValidationSchema();<br>    const { resetPasswordRequest } = useAuth();</pre><pre>return (<br>        &lt;div style={{<br>            padding: &quot;10px&quot;<br>        }}&gt;<br>            &lt;Formik<br>                initialValues={{<br>                    username: &quot;&quot;<br>                }}<br>                onSubmit={resetPasswordRequest}<br>                validationSchema={resetPasswordRequestSchema}<br>                validateOnMount={false}<br>                validateOnChange={false}<br>                validateOnBlur={false}<br>                &gt;<br>                {<br>                    ({<br>                        isSubmitting,<br>                        errors,<br>                        values,<br>                        handleSubmit,<br>                        handleChange,<br>                        handleBlur<br>                    }) =&gt; (<br>                        &lt;form onSubmit={handleSubmit}&gt;<br>                            &lt;InputLayout&gt;<br>                                &lt;Label&gt;Username&lt;/Label&gt;<br>                                &lt;InputField<br>                                    type={&quot;text&quot;}<br>                                    name={&quot;username&quot;}<br>                                    placeholder={&quot;Username&quot;}<br>                                    onChange={handleChange}<br>                                    onBlur={handleBlur}<br>                                    value={values?.username}<br>                                /&gt;<br>                                &lt;InputHelperText isError&gt;{errors?.username}&lt;/InputHelperText&gt;<br>                            &lt;/InputLayout&gt;<br>                            &lt;SubmitButton isSubmitting={isSubmitting} /&gt;<br>                        &lt;/form&gt;<br>                    )<br>                }<br>            &lt;/Formik&gt;<br>        &lt;/div&gt;<br>    )<br>}</pre><p>Here’s how the password reset form looks:</p><pre>import { Formik } from &quot;formik&quot;;<br>import InputLayout from &quot;../../components/layouts/InputLayout&quot;;<br>import Label from &quot;../../components/Label&quot;;<br>import InputField from &quot;../../components/InputField&quot;;<br>import InputHelperText from &quot;../../components/InputHelperText&quot;;<br>import SubmitButton from &quot;../../components/SubmitButton&quot;;<br>import useValidationSchema from &quot;../../hooks/useValidationSchema&quot;;<br>import useAuth from &#39;../../hooks/useAuth&#39;;<br>import { useRouter } from &quot;next/router&quot;;</pre><pre>export default function Reset(){</pre><pre>const router = useRouter()<br>    const { username } = router.query</pre><pre>const { resetPasswordSchema } = useValidationSchema();<br>    const { resetPassword } = useAuth()</pre><pre>return (<br>        &lt;div style={{<br>            padding: &quot;10px&quot;<br>        }}&gt;<br>            &lt;Formik<br>                initialValues={{<br>                    username: username,<br>                    code: &quot;&quot;,<br>                    password: &quot;&quot;,<br>                    confirm\_password: &quot;&quot;<br>                }}<br>                validationSchema={resetPasswordSchema}<br>                onSubmit={resetPassword}<br>                validateOnMount={false}<br>                validateOnChange={false}<br>                validateOnBlur={false}<br>            &gt;<br>                {<br>                    ({<br>                        isSubmitting,<br>                        errors,<br>                        values,<br>                        handleSubmit,<br>                        handleBlur,<br>                        handleChange<br>                    }) =&gt; (<br>                        &lt;form onSubmit={handleSubmit}&gt;<br>                            &lt;InputLayout&gt;<br>                                &lt;Label&gt;Reset code&lt;/Label&gt;<br>                                &lt;InputField<br>                                    type={&quot;text&quot;}<br>                                    name={&quot;code&quot;}<br>                                    placeholder={&quot;Reset code&quot;}<br>                                    onChange={handleChange}<br>                                    onBlur={handleBlur}<br>                                    value={values?.code}<br>                                /&gt;<br>                                &lt;InputHelperText isError&gt;{errors?.code}&lt;/InputHelperText&gt;<br>                            &lt;/InputLayout&gt;<br>                            &lt;InputLayout&gt;<br>                                &lt;Label&gt;New password&lt;/Label&gt;<br>                                &lt;InputField<br>                                    type={&quot;password&quot;}<br>                                    name={&quot;password&quot;}<br>                                    placeholder={&quot;New password&quot;}<br>                                    onChange={handleChange}<br>                                    onBlur={handleBlur}<br>                                    value={values?.password}<br>                                /&gt;<br>                                &lt;InputHelperText isError&gt;{errors?.password}&lt;/InputHelperText&gt;<br>                            &lt;/InputLayout&gt;<br>                            &lt;InputLayout&gt;<br>                                &lt;Label&gt;Confirm password&lt;/Label&gt;<br>                                &lt;InputField<br>                                    type={&quot;password&quot;}<br>                                    name={&quot;confirm_password&quot;}<br>                                    placeholder={&quot;Confirm password&quot;}<br>                                    onChange={handleChange}<br>                                    onBlur={handleBlur}<br>                                    value={values?.confirm_password}<br>                                /&gt;<br>                                &lt;InputHelperText isError&gt;{errors?.confirm_password}&lt;/InputHelperText&gt;<br>                            &lt;/InputLayout&gt;<br>                            &lt;SubmitButton isSubmitting={isSubmitting} /&gt;<br>                        &lt;/form&gt;<br>                    )<br>                }<br>            &lt;/Formik&gt;<br>        &lt;/div&gt;<br>    )<br>}</pre><h3>Caveat</h3><p>A major caveat with the implementation we’ve just created is that 2 or more users can actually register with the same email.</p><p>We don’t want any user to receive a code for another user’s password reset.</p><p>For this and many other reasons, you may want to force unique emails for each user.</p><p>We can easily achieve this using Cognito triggers which are event triggers that run custom lambda functions. These allow us to customise our workflows.</p><p>We can trigger lambdas during any of the following events (and more):</p><ol><li>Pre-signup — Right before Cognito signup is triggered.</li><li>Pre-authentication — Right before the user is authenticated by Cognito.</li><li>Custom message — Right before a verification/confirmation message is sent. We can dynamically edit the message here.</li><li>Post-authentication — After the user is successfully authenticated. If the authentication fails, this will not be triggered.</li><li>Post-confirmation — After a user is verified/confirmed. You can use this to send a welcome email or enable certain privileges that are only available to confirmed users.</li></ol><p>These are only a few of the triggers available to us. You can find more information on these triggers <a href="https://docs.aws.amazon.com/cognito/latest/developerguide/cognito-user-identity-pools-working-with-aws-lambda-triggers.html">here</a>.</p><p>In our case, the trigger we’re most interested in is the Pre-signup trigger. We can check if there are any current users who have the same email address as the one we’ve just received for signup. If so, throw an error and fail early before the Cognito signup.</p><p>I will publish an article that demonstrates how to achieve this.</p><p><em>Originally published at </em><a href="https://kelvinmwinuka.com/basic-authentication-with-aws-cognito-and-nextjs"><em>https://kelvinmwinuka.com</em></a><em>.</em></p><p><em>More content at </em><a href="https://plainenglish.io/"><strong><em>PlainEnglish.io</em></strong></a><em>. Sign up for our </em><a href="http://newsletter.plainenglish.io/"><strong><em>free weekly newsletter</em></strong></a><em>. Follow us on </em><a href="https://twitter.com/inPlainEngHQ"><strong><em>Twitter</em></strong></a><em> and </em><a href="https://www.linkedin.com/company/inplainenglish/"><strong><em>LinkedIn</em></strong></a><em>. Join our </em><a href="https://discord.gg/GtDtUAvyhW"><strong><em>community Discord</em></strong></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=69ef122096cf" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/basic-authentication-with-aws-cognito-nextjs-69ef122096cf">Basic Authentication with AWS Cognito and Next.js</a> was originally published in <a href="https://javascript.plainenglish.io/">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Verify Users in Express.js]]></title>
            <link>https://javascript.plainenglish.io/how-to-verify-users-in-express-js-24c020433b2a?source=rss-70822592ab6------2</link>
            <guid isPermaLink="false">https://medium.com/p/24c020433b2a</guid>
            <category><![CDATA[expressjs]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[mongoose]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Kelvin]]></dc:creator>
            <pubDate>Wed, 30 Dec 2020 06:29:00 GMT</pubDate>
            <atom:updated>2020-12-30T07:27:02.392Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*PXERgH2KjBhj1j2c.jpg" /></figure><p>If you’re building an application, you likely want a lot of users on your platform. However, you don’t just want a large number of users, you want real and high-quality users who will interact with your app. You want to verify those users.</p><p>It’s common for bots or users with fake email addresses and no intention of seriously using your application to register. One way to deal with this at the start is by making sure to verify users.</p><p>This article is a tutorial on user verification in ExpressJS and a continuation of my Express web development series. I will be building on top of the concepts discussed in my previous article on <a href="https://kelvinmwinuka.com/how-to-handle-password-reset-in-expressjs/">handling password resets.</a></p><p>The setup and required packages are specified in that article but you will be able to see what packages are used in the code examples.</p><p>I’d suggest taking a look at the other articles in the series first, although you should be able to follow along with this one regardless. Check out the project on <a href="https://github.com/kelvinmwinuka/express-tutorial">GitHub</a> if you’d like to track it as the series progresses.</p><h3>Models</h3><p>Let’s first create the model that holds the verification tokens. Navigate to the models folder and create a file called ‘UserVerification.js’. The file should have the following content:</p><pre>const { Schema, model } = require(&#39;mongoose&#39;)</pre><pre>const schema = new Schema({<br>  user : {<br>    type: Schema.Types.ObjectId,<br>    ref: &#39;User&#39;,<br>    required: true<br>  },<br>  token: {<br>    type: Schema.Types.String,<br>    required: true<br>  }<br>}, {<br>  timestamps: true<br>})</pre><pre>schema.index({ &#39;updatedAt&#39;: 1 }, { expireAfterSeconds: 300 })</pre><pre>const UserVerification = model(&#39;UserVerification&#39;, schema)</pre><pre>module.exports = UserVerification</pre><p>The model schema contains a token that will be included in the verification link, and the user it’s associated with.</p><p>Create an index on the ‘updatedAt’ field that instructs MongoDB to delete the record after 5 minutes from the time the record is updated. 5 minutes is reasonable for testing but you’ll want to increase this to something more reasonable in production.</p><p>In the user model, add a boolean ‘verified’ property to the schema. Set the default to false as the user would not be verified upon registration.</p><pre>const { Schema, model } = require(&#39;mongoose&#39;)</pre><pre>const saltRounds = 10</pre><pre>var userSchema = new Schema({<br>  name: {<br>    type: Schema.Types.String,<br>    required: [true, &#39;You must provide a name&#39;]<br>  },<br>  email: {<br>    type: Schema.Types.String,<br>    required: [true, &#39;Email address is required&#39;]<br>  },<br>  username: {<br>    type: Schema.Types.String,<br>    required: [true, &#39;Username is required&#39;]<br>  },<br>  password: {<br>    type: Schema.Types.String,<br>    required: [true, &#39;You must provide a password&#39;]<br>  },<br>  verified: {<br>    type: Schema.Types.Boolean,<br>    required: true,<br>    default: false<br>  }<br>})</pre><pre>...</pre><pre>const User = model(&#39;User&#39;, userSchema)</pre><pre>module.exports = User</pre><h3>Routes</h3><h3>Profile routes</h3><p>The first route we have to create is the profile route. This route will simply render a template with the user’s profile details. Create a file in the routes folder named ‘profile.js’ and add a route that renders the ‘profile.html’ template.</p><pre>const router = require(&#39;express&#39;).Router()</pre><pre>router.get(&#39;/profile&#39;, (req, res) =&gt; {<br>  if (!req.isAuthenticated()) return res.redirect(&#39;/login&#39;)<br>  return res.render(&#39;profile.html&#39;)<br>})</pre><pre>module.exports = router</pre><h3>User verification routes</h3><p>Now let’s create the routes that will handle user verification. In the routes folder, create a file named ‘user-verification.js’. To start with, the file will have the following contents:</p><pre>const router = require(&#39;express&#39;).Router()<br>const { v4 } = require(&#39;uuid&#39;)<br>const { User, UserVerification } = require(&#39;../models&#39;)<br>const { sendEmail } = require(&#39;../helpers&#39;)</pre><pre>/* Create routes here */</pre><pre>module.exports = router</pre><p>Import the User and UserVerification models. Import the ‘sendMail’ helper function that we created in the previous article. This is simply a function that uses NodeMailer to send an email using the arguments passed to it.</p><p>Now let’s create the routes.</p><h4>Create verification url</h4><p>The first route is a get route ‘/verify’. This route is responsible for creating the verification URL and has the following contents:</p><pre>router.get(&#39;/verify&#39;, async (req, res) =&gt; {<br>  if (!req.isAuthenticated()) return res.redirect(&#39;/login&#39;)<br>  if (req.user.verified) return res.redirect(&#39;back&#39;)</pre><pre>const token = v4().toString().replace(/-/g, &#39;&#39;)<br>  const verificationUrl = `${process.env.DOMAIN}/verify-confirm/${token}`</pre><pre>await UserVerification.updateOne({ <br>    user: req.user._id <br>  }, {<br>    user: req.user._id,<br>    token: token<br>  }, {<br>    upsert: true<br>  })</pre><pre>sendEmail({<br>    to: req.user.email,<br>    subject: &#39;Verify your email address&#39;,<br>    text: `Here&#39;s your email verification link: ${verificationUrl}`<br>  })</pre><pre>req.flash(&#39;verify_success&#39;, &#39;Check your email address for your verification link. It may take a few minutes&#39;)<br>  res.redirect(&#39;/profile&#39;)<br>})</pre><p>First, check if the user is authenticated. The user should only be able to request a verification link when they are logged in. If they aren’t, redirect them to the login page.</p><p>Check if the user is already verified. We don’t want to send a verification link if the user is already verified. If they are, redirect to the previous page.</p><p>Create the token and then the verification URL that contains the token.</p><p>Update the UserVerification record associated with the current user. Make sure to set the upsert option to ‘true’. We want to replace the current verification link so that only one can be active at a time, but we also want to create a new one if there isn’t one in the collection.</p><p>Send the email containing the user verification link, flash a success message urging the user to check their email address and then redirect to the user’s profile.</p><h4>Verify user</h4><p>The second route handles the link sent to the user:</p><pre>router.get(&#39;/verify-confirm/:token&#39;, async (req, res) =&gt; {<br>  if (!req.isAuthenticated()) return res.redirect(&#39;/login&#39;)<br>  <br>  const token = req.params.token</pre><pre>const userVerification = await UserVerification.findOne({<br>    user: req.user._id,<br>    token: token<br>  })</pre><pre>if (userVerification) {<br>    await User.updateOne({ _id: req.user._id }, { verified: true })<br>    await UserVerification.deleteOne({ <br>      user: req.user._id,<br>      token: token<br>    })<br>    sendEmail({<br>      to: req.user.email,<br>      subject: &#39;Verified&#39;,<br>      text: `Congratulations ${req.user.name}, your account is now verified!`<br>    })<br>    req.flash(&#39;verify_success&#39;, &#39;Congrats, you are now verified!&#39;)<br>  } else {<br>    req.flash(&#39;verify_error&#39;, &#39;Verification link is invalid or has expired.&#39;)<br>  }</pre><pre>return res.redirect(&#39;/profile&#39;)<br>})</pre><p>This route expects a token which we will validate later. First check whether the user is logged in, if not, redirect to the login page.</p><p>Extract the token from the url and query the UserVerification collection for a document with the current token and the current user.</p><p>If the document doesn’t exist, flash an error message stating that the link is invalid or expired.</p><p>If the document exists, update the user’s verified status to ‘true’ and delete the current UserVerification document in order to prevent the link from being clicked again (this would be pointless anyway but it’s good practice).</p><p>Send the user an email confirming their verification status and then flash a success message stating that the user has now been verified. Redirect to the user’s profile page afterwards.</p><h3>Import routes</h3><p>Go into the app’s entry folder and include the profile and user-verification routes with the following code:</p><pre>app.use(&#39;/&#39;, require(&#39;./routes/profile&#39;)) <br>app.use(&#39;/&#39;, require(&#39;./routes/user-verification&#39;))</pre><h3>Templates</h3><p>There’s one new template that we need to create for this feature: the profile template.</p><pre>{% extends &#39;base.html&#39; %}</pre><pre>{% set title = &#39;Profile&#39; %}</pre><pre>{% block content %}<br>  {% if messages.verify_success %}<br>    &lt;div class=&quot;alert alert-success&quot; role=&quot;alert&quot;&gt;<br>      {{ messages.verify_success }}<br>    &lt;/div&gt;<br>  {% endif %}<br>  {% if messages.verify_error %}<br>    &lt;div class=&quot;alert alert-danger&quot; role=&quot;alert&quot;&gt;<br>      {{ messages.verify_error }}<br>    &lt;/div&gt;<br>  {% endif %}<br>  &lt;div&gt;<br>    &lt;h5&gt;Hi, {{ user.name }}&lt;/h5&gt;<br>    {% if not user.verified %}<br>      Your email is not verified, <br>      &lt;a class=&quot;btn btn-sm btn-warning&quot; href=&quot;/verify&quot;&gt;Verify Email&lt;/a&gt;<br>    {% endif %}<br>  &lt;/div&gt;<br>{% endblock %}</pre><pre>{% block scripts %}<br>{% endblock %}</pre><p>This template renders the error or success message flashed in the previous request. We have a div that displays the user’s name and a button to generate the verification URL conditionally based on the user’s verified status.</p><h3>Conclusion</h3><p>In this article, I demonstrated how to verify users in your Express application. There are many reasons you may want to verify users: You may want to make sure you have active, human users on your app or maybe you want to restrict features that require users to be verified.</p><p>Whatever the reason, I hope that this article has provided sufficient guidance on the flow and execution of the verification process.</p><p>The next article will be about creating user following and follower relationships using many-to-many relationships in MongoDB.</p><p><strong>If you enjoyed this article, consider following my </strong><a href="https://kelvinmwinuka.com/"><strong>personal website</strong></a><strong> for early access to my content before it gets published on Medium. Also, feel free to comment on this post. I’d love to hear your thoughts!</strong></p><p><em>Originally published at </em><a href="https://kelvinmwinuka.com/how-to-verify-users-in-expressjs/"><em>https://kelvinmwinuka.com</em></a><em> on December 30, 2020.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=24c020433b2a" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/how-to-verify-users-in-express-js-24c020433b2a">How to Verify Users in Express.js</a> was originally published in <a href="https://javascript.plainenglish.io/">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Handle Password Reset in Express.js]]></title>
            <link>https://javascript.plainenglish.io/how-to-handle-password-reset-in-expressjs-fde6f5015332?source=rss-70822592ab6------2</link>
            <guid isPermaLink="false">https://medium.com/p/fde6f5015332</guid>
            <category><![CDATA[expressjs]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[mongoose]]></category>
            <dc:creator><![CDATA[Kelvin]]></dc:creator>
            <pubDate>Thu, 24 Dec 2020 13:05:34 GMT</pubDate>
            <atom:updated>2020-12-30T07:29:44.460Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*MQSXvfuRP4UKXu7x.jpg" /></figure><p>No authentication system is complete without a password reset feature. I would personally never ship a product that did not have this feature included. It is necessary to provide a way for users to recover access to their accounts/data in case of a lost or forgotten password. In this article, I will be demonstrating how to handle password resets in ExpressJS.</p><p>In the last 2 articles, I wrote about <a href="https://kelvinmwinuka.com/how-to-set-up-mongoose-with-expressjs/">how to connect ExpressJS application to MongoDB database</a> and <a href="https://kelvinmwinuka.com/how-to-create-registration-authentication-with-express-passportjs/">building a user registration and authentication system</a>.</p><p>Both of these articles tie into today’s article. We’re going to use mongoose and our saved user data to enable password resets.</p><p>If you’ve read those articles, or already have your own authentication system, read on. Even if you’re using a different tech stack, you may still gain some valuable ideas from this approach.</p><p>As always, this project is hosted on <a href="https://github.com/kelvinmwinuka/express-tutorial">Github</a>. Feel free to clone the project to get access to the source code I use in this article.</p><h3>The password reset flow</h3><p>Before we dive into the code, let’s first establish what the password reset flow will look like from the user’s perspective and then design the implementation of this flow.</p><h3>User’s perspective</h3><p>From the user’s perspective, the process should go as follows:</p><ol><li>Click on the ‘Forgot password’ link in the login page.</li><li>Redirected to a page which requires an email address.</li><li>Receive password reset link in an email.</li><li>Link redirects to a page that requires a new password and password confirmation.</li><li>After submission, redirected to the login page with a success message.</li></ol><h3>Reset system characteristics</h3><p>We also need to understand some characteristics of a good password reset system:</p><ol><li>Unique password reset link should be generated for the user such that when the user visits the link, they are instantly identified. This means including a unique token in the link.</li><li>Password reset link should have an expiry time (e.g. 2 hours) after which it is no longer valid and cannot be used to reset the password.</li><li>The reset link should expire once the password has been reset to prevent the same link from being used to reset the password several times.</li><li>If the user requests to change password multiple times without following through on the whole process, each generated link should invalidate the previous one. This prevents having multiple active links from which the password can be reset.</li><li>If the user chooses to ignore the password reset link sent to their email, their current credentials should be left intact and valid for future authentication.</li></ol><h3>Implementation steps</h3><p>We now have a clear picture of the reset flow from the user’s perspective and the characteristics of a password reset system. Here are the steps we will take in the implementation of this system:</p><ol><li>Create a mongoose model called ‘PasswordReset’ to manage active password reset requests/tokens. The records set here should expire after a specified time period.</li><li>Include the ‘Forgot password’ link in the login form that leads to a route that contains an email form.</li><li>Once the email is submitted to a post route, check whether a user with the provided email address exists.</li><li>If the user does not exist, redirect back to the email input form and notify the user that no user with provided email was found.</li><li>If the user exists, generate a password reset token and save it to PasswordReset collection in a document that references the user. If there already is a document in this collection associated with this user, update/replace the current document (there can only be one per user).</li><li>Generate a link that includes the password reset token within it, email the link to the user.</li><li>Redirect to the login page with success message prompting the user to check their email address for the reset link.</li><li>Once the user clicks the link, it should lead to a GET route that expects the token as one of the route params.</li><li>Within this route, extract the token and query the PasswordReset collection for this token. If the document is not found, alert the user that the link is invalid/expired.</li><li>If the document is found, load a form to reset the password. The form should have 2 fields (new password &amp; confirm password fields).</li><li>When the form is submitted, its post route will update the user’s password to the new password.</li><li>Delete the password reset document associated with this user in the PasswordReset collection.</li><li>Redirect the user to the login page with a success message.</li></ol><h3>Implementation</h3><h3>The setup</h3><p>Firstly, we’ll have to set up the project. Install the <a href="https://www.npmjs.com/package/uuid">uuid</a> package for generating a unique token, and the <a href="https://www.npmjs.com/package/nodemailer">nodemailer</a> package for sending emails.</p><pre>npm install uuid nodemailer</pre><p>Add the full domain to the environment variables. We’ll need this in order to generate a fill link string to email to the user.</p><pre>DOMAIN=http://localhost:8000</pre><p>Make some changes to the app entry file in the following areas:</p><ol><li>Set ‘useCreateIndex’ to ‘true’ in the mongoose connection options. This makes mongoose’s default index build use createIndex instead of ensureIndex and prevents MongoDB deprecation warnings.</li><li>Import a new route file that will contain all the reset routes called ‘password-reset’. We will create these routes later.</li></ol><pre>const connection = mongoose.connect(process.env.MONGO_URI, {<br>  useNewUrlParser: true,<br>  useUnifiedTopology: true,<br>  useCreateIndex: true<br>})</pre><pre>...</pre><pre>app.use(&#39;/&#39;, require(&#39;./routes/password-reset&#39;))</pre><h3>Models</h3><p>We need to have a dedicated model to handle the password reset records. In the models folder, create a model called ‘PasswordReset’ with the following code:</p><pre>const { Schema, model } = require(&#39;mongoose&#39;)</pre><pre>const schema = new Schema({<br>  user: {<br>    type: Schema.Types.ObjectId,<br>    ref: &#39;User&#39;,<br>    required: true<br>  },<br>  token: {<br>    type: Schema.Types.String,<br>    required: true<br>  }<br>}, {<br>  timestamps: true<br>})</pre><pre>schema.index({ &#39;updatedAt&#39;: 1 }, { expireAfterSeconds: 300 })</pre><pre>const PasswordReset = model(&#39;PasswordReset&#39;, schema)</pre><pre>module.exports = PasswordReset</pre><p>We have two properties in this model, the user that’s requested the password reset, and the unique token assigned to the particular request.</p><p>Make sure to set the timestamps option to true in order to include ‘createdAt’ and ‘updatedAt’ fields in the document.</p><p>After defining the schema, create an index on the updatedAt field with an expiry time of 300 seconds (5 minutes). I’ve set it this low for testing purposes. In production, you can increase this to something more practical like 2 hours.</p><p>In the User model we created in <a href="https://kelvinmwinuka.com/how-to-set-up-mongoose-with-expressjs/">this article</a> (or the user model you currently have), update the pre-save hook to the following:</p><pre>userSchema.pre(&#39;save&#39;, async function(next){<br>  if (this.isNew || this.isModified(&#39;password&#39;)) this.password = await bcrypt.hash(this.password, saltRounds)<br>  next()<br>})</pre><p>Do this to make sure the password field is hashed whether the document is new or the password field has been changed in an existing document.</p><h3>Routes</h3><p>Create a new file in the route’s folder called ‘password-reset.js’. This is the file we import in the app entry file.</p><p>In this file, import the User and PasswordReset models. Import the v4 function from the uuid package for token generation.</p><pre>const router  = require(&#39;express&#39;).Router()<br>const { User, PasswordReset } = require(&#39;../models&#39;)<br>const { v4 } = require(&#39;uuid&#39;)</pre><pre>/* Create routes here */</pre><pre>module.exports = router</pre><p>Create the first 2 routes. These routes are associated with the form which accepts the user’s email address.</p><pre>router.get(&#39;/reset&#39;, (req, res) =&gt; res.render(&#39;reset.html&#39;))</pre><pre>router.post(&#39;/reset&#39;, async (req, res) =&gt; {<br>  /* Flash email address for pre-population in case we redirect back to reset page. */<br>  req.flash(&#39;email&#39;, req.body.email)</pre><pre>/* Check if user with provided email exists. */<br>  const user = await User.findOne({ email: req.body.email })<br>  if (!user) {<br>    req.flash(&#39;error&#39;, &#39;User not found&#39;)<br>    return res.redirect(&#39;/reset&#39;)<br>  }</pre><pre>/* Create password reset token and save in collection along with user. <br>     If there already is a record with current user, replace it. */<br>  const token = v4().toString().replace(/-/g, &#39;&#39;)<br>  PasswordReset.updateOne({ <br>    user: user._id <br>  }, {<br>    user: user._id,<br>    token: token<br>  }, {<br>    upsert: true<br>  })<br>  .then( updateResponse =&gt; {<br>    /* Send email to user containing password reset link. */<br>    const resetLink = `${process.env.DOMAIN}/reset-confirm/${token}`<br>    console.log(resetLink)</pre><pre>req.flash(&#39;success&#39;, &#39;Check your email address for the password reset link!&#39;)<br>    return res.redirect(&#39;/login&#39;)<br>  })<br>  .catch( error =&gt; {<br>    req.flash(&#39;error&#39;, &#39;Failed to generate reset link, please try again&#39;)<br>    return res.redirect(&#39;/reset&#39;)<br>  })<br>})</pre><p>The first is a GET route to ‘/reset’. In this route, render the ‘reset.html’ template. We will create this template later.</p><p>The second route is a POST route for ‘/reset’. This route expects the user’s email in the request body. In this route:</p><ol><li>Flash email back for pre-population in case we redirect back to the email form.</li><li>Check if the user with the email provided exists. If not, flash an error and redirect back to ‘/reset’.</li><li>Create a token using v4.</li><li>Update PasswordReset document associated with the current user. Set upsert to true in options to create a new document if there isn’t one already.</li><li>If update is successful, mail the link to the user, flash a success message and redirect to the login page.</li><li>If update is unsuccessful, flash an error message and redirect back to the email page.</li></ol><p>At the moment, we’re only logging the link to the console. We will implement the email logic later.</p><p>Create the 2 routes that come into play when the user visits the link generated link above.</p><pre>router.get(&#39;/reset-confirm/:token&#39;, async (req, res) =&gt; {<br>  const token = req.params.token<br>  const passwordReset = await PasswordReset.findOne({ token })<br>  res.render(&#39;reset-confirm.html&#39;, { <br>    token: token,<br>    valid: passwordReset ? true : false<br>  })<br>})</pre><pre>router.post(&#39;/reset-confirm/:token&#39;, async (req, res) =&gt; {<br>  const token = req.params.token<br>  const passwordReset = await PasswordReset.findOne({ token })<br>  <br>  /* Update user */<br>  let user = await User.findOne({ _id: passwordReset.user })<br>  user.password = req.body.password<br>  <br>  user.save().then( async savedUser =&gt;  {<br>    /* Delete password reset document in collection */<br>    await PasswordReset.deleteOne({ _id: passwordReset._id })<br>    /* Redirect to login page with success message */<br>    req.flash(&#39;success&#39;, &#39;Password reset successful&#39;)<br>    res.redirect(&#39;/login&#39;)<br>  }).catch( error =&gt; {<br>    /* Redirect back to reset-confirm page */<br>    req.flash(&#39;error&#39;, &#39;Failed to reset password please try again&#39;)<br>    return res.redirect(`/reset-confirm/${token}`)<br>  })<br>})</pre><p>The first route is a get route that expects the token in the url. The token is extracted and then validated. Validate the token by searching the PasswordReset collection for a document with the provided token.</p><p>If the document is found, set the ‘valid’ template variable to true, otherwise, set it to false. Be sure to pass the token itself to the template. We will use this in the password reset form.</p><p>Check the validity of the token by searching the PasswordReset collection by the token.</p><p>The second route is a POST route that accepts the password reset form submission. Extract the token from the url and then retrieve the password reset document associated with it.</p><p>Update the user associated with this particular password reset document. Set the new password and save the updated user.</p><p>Once the user is updated, delete the password reset document to prevent it from being reused to reset the password.</p><p>Flash a success message and redirect the user to the login page where they can log in with their new password.</p><p>If the update is unsuccessful, flash an error message and redirect back to the same form.</p><h3>Templates</h3><p>Once we’ve created the routes, we need to create the templates</p><p>In the views folder, create a ‘reset.html’ template file with the following content:</p><pre>{% extends &#39;base.html&#39; %}</pre><pre>{% set title = &#39;Reset&#39; %}</pre><pre>{% block styles %}<br>{% endblock %}</pre><pre>{% block content %}<br>  &lt;form action=&#39;/reset&#39; method=&quot;POST&quot;&gt;<br>    {% if messages.error %}<br>      &lt;div class=&quot;alert alert-danger&quot; role=&quot;alert&quot;&gt;{{ messages.error }}&lt;/div&gt;<br>    {% endif %}<br>    &lt;div class=&quot;mb-3&quot;&gt;<br>      &lt;label for=&quot;name&quot; class=&quot;form-label&quot;&gt;Enter your email address&lt;/label&gt;<br>      &lt;input <br>        type=&quot;text&quot; <br>        class=&quot;form-control {% if messages.error %}is-invalid{% endif %}&quot; <br>        id=&quot;email&quot; <br>        name=&quot;email&quot;<br>        value=&quot;{{ messages.email or &#39;&#39; }}&quot;<br>        required&gt;<br>    &lt;/div&gt;<br>    &lt;div&gt;<br>      &lt;button type=&quot;submit&quot; class=&quot;btn btn-primary&quot;&gt;Send reset link&lt;/button&gt;<br>    &lt;/div&gt;<br>  &lt;/form&gt;<br>{% endblock %}</pre><p>Here we have one email field that is pre-populated with an email value if one was flashed in the previous request.</p><p>Include an alert that displays an error message if one has been flashed from the previous request.</p><p>Create another template in the same folder named ‘reset-confirm.html’ with the following content:</p><pre>{% extends &#39;base.html&#39; %}</pre><pre>{% set title = &#39;Confirm Reset&#39; %}</pre><pre>{% block content %}<br>  {% if not valid %}<br>    &lt;h1&gt;Oops, looks like this link is expired, try to &lt;a href=&quot;/reset&quot;&gt;generate another reset link&lt;/a&gt;&lt;/h1&gt;<br>  {% else %}<br>    &lt;form action=&#39;/reset-confirm/{{ token }}&#39; method=&quot;POST&quot;&gt;<br>      {% if messages.error %}<br>        &lt;div class=&quot;alert alert-danger&quot; role=&quot;alert&quot;&gt;{{ messages.error }}&lt;/div&gt;<br>      {% endif %}<br>      &lt;div class=&quot;mb-3&quot;&gt;<br>        &lt;label for=&quot;name&quot; class=&quot;form-label&quot;&gt;Password&lt;/label&gt;<br>        &lt;input <br>          type=&quot;password&quot; <br>          class=&quot;form-control {% if messages.password_error %}is-invalid{% endif %}&quot; <br>          id=&quot;password&quot; <br>          name=&quot;password&quot;&gt;<br>        &lt;div class=&quot;invalid-feedback&quot;&gt;{{ messages.password_error }}&lt;/div&gt;<br>      &lt;/div&gt;<br>      &lt;div class=&quot;mb-3&quot;&gt;<br>        &lt;label for=&quot;name&quot; class=&quot;form-label&quot;&gt;Confirm password&lt;/label&gt;<br>        &lt;input <br>          type=&quot;password&quot; <br>          class=&quot;form-control {% if messages.confirm_error %}is-invalid{% endif %}&quot; <br>          id=&quot;confirmPassword&quot; <br>          name=&quot;confirmPassword&quot;&gt;<br>        &lt;div class=&quot;invalid-feedback&quot;&gt;{{ messages.confirm_error }}&lt;/div&gt;<br>      &lt;/div&gt;<br>      &lt;div&gt;<br>        &lt;button type=&quot;submit&quot; class=&quot;btn btn-primary&quot;&gt;Confirm reset&lt;/button&gt;<br>      &lt;/div&gt;<br>    &lt;/form&gt;<br>  {% endif %}<br>{% endblock %}</pre><p>In this form, check for the value of the ‘valid’ variable that we set in the GET route, if false, render the expired token message. Otherwise, render the password reset form.</p><p>Include an alert that displays an error message if one was flashed in the previous request.</p><p>Go to the login form that we created in the <a href="https://kelvinmwinuka.com/how-to-create-registration-authentication-with-express-passportjs/">registration &amp; authentication</a> article and add the following code to the top of the form:</p><pre>{% if messages.success %}<br>    &lt;div class=&quot;alert alert-success&quot; role=&quot;alert&quot;&gt;{{ messages.success }}&lt;/div&gt;<br>{% endif %}</pre><p>This renders the success messages that we flash when we create/send the reset link and when we update the user’s password before redirecting to the login page.</p><h3>Mail</h3><p>In the previous routes section, we logged the reset link in the console. Ideally, we should send an email to the user when they’ve requested a password reset link.</p><p>For this example, I’ve used <a href="https://ethereal.email/">ethereal.email</a> to generate a test email account for development purposes. Head over there and create one (it’s a one-click process).</p><p>Once you’ve created the test account, add the following variables to your environment variables:</p><pre>EMAIL_HOST=smtp.ethereal.email EMAIL_NAME=Leanne Zulauf EMAIL_ADDRESS=leanne.zulauf@ethereal.email EMAIL_PASSWORD=aDhwfMry1h3bbbR9Av EMAIL_PORT=587 EMAIL_SECURITY=STARTTLS</pre><p>These are my values at the time of writing, plug in your own values here.</p><p>Create a ‘helpers.js’ file in the root of the project. This file will have a bunch of useful functions that are likely to be reused across the entire project.</p><p>Define these functions here so that we can import them when they’re needed rather than repeating similar logic all over our application.</p><pre>const nodemailer = require(&#39;nodemailer&#39;)</pre><pre>module.exports = {<br>  sendEmail: async ({ to, subject, text }) =&gt; {<br>    /* Create nodemailer transporter using environment variables. */<br>    const transporter = nodemailer.createTransport({<br>      host: process.env.EMAIL_HOST,<br>      port: Number(process.env.EMAIL_PORT),<br>      auth: {<br>        user: process.env.EMAIL_ADDRESS,<br>        pass: process.env.EMAIL_PASSWORD<br>      }<br>    })<br>    /* Send the email */<br>    let info = await transporter.sendMail({<br>      from: `&quot;${process.env.EMAIL_NAME}&quot; &lt;${process.env.EMAIL_ADDRESS}&gt;`,<br>      to,<br>      subject,<br>      text<br>    })<br>    /* Preview only available when sending through an Ethereal account */<br>    console.log(`Message preview URL: ${nodemailer.getTestMessageUrl(info)}`)<br>  }<br>}</pre><p>Export an object with various functions. The first being the ‘sendEmail’ function.</p><p>This function takes the recipient’s address, email subject and email text. Create the NodeMailer transporter, using the environment variables defined previously in the options. Send the email using the arguments passed to the function.</p><p>The last line of the function logs the message url in the console so you can view the message on Ethereal mail. The test account does not actually send the email.</p><p>Go back to the ‘password-reset.js’ routes and add the email functionality. First, import the function:</p><pre>const { sendEmail } = require(&#39;../helpers&#39;)</pre><p>In the ‘/reset’ POST route, instead of logging the reset link on the console, add the following code:</p><pre>sendEmail({<br>      to: user.email, <br>      subject: &#39;Password Reset&#39;,<br>      text: `Hi ${user.name}, here&#39;s your password reset link: ${resetLink}. <br>      If you did not request this link, ignore it.`<br>    })</pre><p>Send an additional email to notify the user of a successful password change in the ‘/reset-confirm’ POST route once the user is successfully updated:</p><pre>user.save().then( async savedUser =&gt;  {<br>    /* Delete password reset document in collection */<br>    await PasswordReset.deleteOne({ _id: passwordReset._id })<br>    /* Send successful password reset email */<br>    sendEmail({<br>      to: user.email, <br>      subject: &#39;Password Reset Successful&#39;,<br>      text: `Congratulations ${user.name}! Your password reset was successful.`<br>    })<br>    /* Redirect to login page with success message */<br>    req.flash(&#39;success&#39;, &#39;Password reset successful&#39;)<br>    res.redirect(&#39;/login&#39;)<br>  }).catch( error =&gt; {<br>    /* Redirect back to reset-confirm page */<br>    req.flash(&#39;error&#39;, &#39;Failed to reset password please try again&#39;)<br>    return res.redirect(`/reset-confirm/${token}`)<br>  })</pre><h3>Conclusion</h3><p>In this article, I demonstrated how to implement a password reset feature in ExpressJS using NodeMailer.</p><p>In the next article, I will write about implementing a user email verification system in your Express application. I will use a similar approach to the one used in this article, with NodeMailer being the email package of choice.</p><p><strong>If you enjoyed this article, consider following my </strong><a href="https://kelvinmwinuka.com/"><strong>personal website</strong></a><strong> for early access to my content before it gets published on Medium (don’t worry, it’s still free with no annoying pop-up ads!). Also, feel free to comment on this post. I’d love to hear your thoughts!</strong></p><p><em>Originally published at </em><a href="https://kelvinmwinuka.com/how-to-handle-password-reset-in-expressjs/"><em>https://kelvinmwinuka.com</em></a><em> on December 24, 2020.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fde6f5015332" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/how-to-handle-password-reset-in-expressjs-fde6f5015332">How to Handle Password Reset in Express.js</a> was originally published in <a href="https://javascript.plainenglish.io/">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Create Registration & Authentication with Express & PassportJS]]></title>
            <link>https://javascript.plainenglish.io/how-to-create-registration-authentication-with-express-passportjs-eb9450a9fa3b?source=rss-70822592ab6------2</link>
            <guid isPermaLink="false">https://medium.com/p/eb9450a9fa3b</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[authentication]]></category>
            <category><![CDATA[expressjs]]></category>
            <category><![CDATA[mongodb]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Kelvin]]></dc:creator>
            <pubDate>Mon, 21 Dec 2020 06:47:38 GMT</pubDate>
            <atom:updated>2020-12-26T17:09:45.995Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*OTFFSeGNUQDYjlsX.jpg" /></figure><p>In this article, I’m going to demonstrate how to build a user registration and authentication system in ExpressJS. In the previous article, we <a href="https://kelvinmwinuka.com/how-to-set-up-mongoose-with-expressjs/">set up a MongoDB connection using Mongoose</a>. Here we’ll be using that connection to save user data and use it for authentication.</p><p>This project is available on <a href="https://github.com/kelvinmwinuka/express-tutorial">Github</a>. Feel free to clone it if you’d like to follow along.</p><h3>Setup</h3><p>Let’s start by setting up the necessary packages and libraries for this portion of the project.</p><p>Run the following command to install the necessary package:</p><pre>npm install passport passport-local express-session bcrypt connect-mongo express-flash joi</pre><p>Here’s a breakdown of the packages we’ve just installed:</p><ol><li><a href="http://www.passportjs.org/">passport</a> and <a href="http://www.passportjs.org/packages/passport-local/">passport-local</a> — User authentication.</li><li><a href="https://www.npmjs.com/package/express-session">express-session</a> — Sessions in ExpressJS.</li><li><a href="https://www.npmjs.com/package/bcrypt">bcrypt</a> — Password encryption and comparison on authentication.</li><li><a href="https://www.npmjs.com/package/connect-mongo">connect-mongo</a> — Mongo store for express sessions.</li><li><a href="https://www.npmjs.com/package/express-flash">express-flash</a> — Flashing messages for display in the front-end.</li><li><a href="https://joi.dev/api/?v=17.3.0">joi</a> — User input validation.</li></ol><p>Include bootstrap (optional, as long as the form can send post data to the server, it will work).</p><p>In the <strong><em>base.html</em></strong> file, add the link and script tags for the bootstrap imports. They are imported once and then included in every template that extends the base template.</p><p>At this stage, base.html file should look like this:</p><pre>&lt;!DOCTYPE html&gt;<br>&lt;html&gt;<br>  &lt;head&gt;<br>    &lt;meta charset=&quot;utf-8&quot;&gt;<br>    &lt;meta http-equiv=&quot;X-UA-Compatible&quot; content=&quot;IE=edge&quot;&gt;<br>    &lt;title&gt;{{ title }}&lt;/title&gt;<br>    &lt;meta name=&quot;description&quot; content=&quot;&quot;&gt;<br>    &lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1&quot;&gt;<br>    &lt;!-- Bootstrap CSS --&gt;<br>    &lt;link <br>      href=&quot;<a href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta1/dist/css/bootstrap.min.css">https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta1/dist/css/bootstrap.min.css</a>&quot; <br>      rel=&quot;stylesheet&quot; <br>      integrity=&quot;sha384-giJF6kkoqNQ00vy+HMDP7azOuL0xtbfIcaT9wjKHr8RbDVddVHyTfAAsrekwKmP1&quot; <br>      crossorigin=&quot;anonymous&quot;&gt;<br>    {% block styles %}<br>      {# This block will be replaced by child templates when importing styles #}<br>    {% endblock %}<br>  &lt;/head&gt;<br>  &lt;body&gt;<br>    {% block content %}<br>      {# This block will be replaced by child templates when adding content to the  #}<br>    {% endblock %}</pre><pre>&lt;!-- Bootstrap JavaScript Bundle with Popper --&gt;<br>    &lt;script <br>      src=&quot;<a href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta1/dist/js/bootstrap.bundle.min.js">https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta1/dist/js/bootstrap.bundle.min.js</a>&quot; <br>      integrity=&quot;sha384-ygbV9kiqUc6oa4msXn9868pTtWMgiQaeYH7/t7LECLbyPA2x65Kgf80OJFdroafW&quot; <br>      crossorigin=&quot;anonymous&quot;&gt;<br>    &lt;/script&gt;<br>    {% block scripts %}<br>      {# This block will be replaced by child templates when importing scripts #}<br>    {% endblock %}<br>  &lt;/body&gt;<br>&lt;/html&gt;</pre><h3>Implementation</h3><p>Go into the entry point file and require the following packages:</p><pre>const session = require(&#39;express-session&#39;) <br>const MongoStore = require(&#39;connect-mongo&#39;)(session) <br>const passport = require(&#39;passport&#39;)</pre><p>Right after the app declaration, add built-in express middleware to parse incoming requests with url-encoded data to process the data that will be received from the forms.</p><pre>var app = express() <br>app.use(express.urlencoded({extended: true}))</pre><p>Next, set up the session middleware. Make sure to place this code after the mongoose connection as we will use the existing mongoose connection to store the session data. Otherwise, you’ll have to create a new connection for this.</p><pre>app.use(session({<br>  secret: process.env.SESSION_SECRET,<br>  resave: false,<br>  saveUninitialized: true,<br>  store: new MongoStore({<br>    mongooseConnection: mongoose.connection,<br>    collection: &#39;sessions&#39;<br>  }),<br>  cookie: {<br>    secure: false<br>  }<br>}))</pre><p>Let’s walk through the code above:</p><ol><li>We’re adding the session middleware to the app.</li><li>secret — The string used to encrypt the session. Declare this in the .env file or system environment variables.</li><li>resave — Determines whether the session object is saved back into the session store even if it was not modified by the request.</li><li>saveUninitialized — Determines whether a new session should be saved into the store even before it’s modified.</li><li>store — The store used to save session data.</li></ol><h3>Update models</h3><p>In this section, I’m referring to the user model we created in the previous article. <a href="https://kelvinmwinuka.com/how-to-set-up-mongoose-with-expressjs/">Take a look here</a>.</p><p>Now we need to update the user model in order to enable authentication and password hashing upon saving. We’re doing this in the model in order to avoid writing the authentication login in multiple places shall we need it.</p><p>This logic is unique to this model so it makes sense to have it here. Navigate to the User.js model file we created previously and add the following code right after the first require statement:</p><pre>const bcrypt = require(&#39;bcrypt&#39;) <br>const saltRounds = 10</pre><p>After the schema definition, add the following code:</p><pre>userSchema.pre(&#39;save&#39;, async function(next){<br>  if (this.isNew) this.password = await bcrypt.hash(this.password, saltRounds)<br>  next()<br>})</pre><pre>userSchema.static(&#39;userExists&#39;, async function({username, email}){<br>  let user = await this.findOne({ username })<br>  if (user) return { username: &#39;This username is already in use&#39; }<br>  user = await this.findOne({ email })<br>  if (user) return { email: &#39;This email address is already in use&#39; }<br>  return false<br>})</pre><pre>userSchema.static(&#39;authenticate&#39;, async function(username, plainTextPassword){<br>  const user = await this.findOne({ $or: [ {email: username}, {username} ] })<br>  if (user &amp;&amp; await bcrypt.compare(plainTextPassword, user.password)) return user<br>  return false<br>})</pre><p>There are a few things happening here:</p><ol><li>The first is a pre-save hook. This runs before every document save. We use it to determine if the current document is new (not an update call). If the document is new, hash the password. Always save a hashed password rather than plain text.</li><li>The second block is a static method that checks if the user exists. We will query the database by username and then email. If a user is found, return an object specifying which one is already in use. Otherwise, return false.</li><li>The third method is a static method added to the schema. We’re using this to authenticate the user. If the user exists and the password comparison between plainTextPassword and the hashed user password passes, return the user object. Otherwise, return false for. failed authentication.</li></ol><h3>Registration</h3><p>Create the registration form; a simple form that collects the user’s name, username, email address and password.</p><p>Place this code in ‘register.html’ in the views folder.</p><pre>{% extends &#39;base.html&#39; %}</pre><pre>{% set title = &#39;Register&#39; %}</pre><pre>{% block styles %}<br>  &lt;style&gt;<br>    form {<br>      margin-top: 20px;<br>      margin-left: 20px;<br>      margin-right: 20px;<br>    }<br>  &lt;/style&gt;<br>{% endblock %}</pre><pre>{% block content %}<br>  &lt;form action=&quot;/register&quot; method=&quot;POST&quot;&gt;<br>    &lt;div class=&quot;mb-3&quot;&gt;<br>      &lt;label for=&quot;name&quot; class=&quot;form-label&quot;&gt;Name&lt;/label&gt;<br>      &lt;input <br>        type=&quot;text&quot; <br>        class=&quot;form-control {% if messages.name_error %}is-invalid{% endif %}&quot; <br>        id=&quot;name&quot; <br>        name=&quot;name&quot;<br>        value=&quot;{{ messages.name or &#39;&#39; }}&quot;<br>        placeholder=&quot;Full Name&quot;&gt;<br>      &lt;div class=&quot;invalid-feedback&quot;&gt;{{ messages.name_error }}&lt;/div&gt;<br>    &lt;/div&gt;<br>    &lt;div class=&quot;mb-3&quot;&gt;<br>      &lt;label for=&quot;username&quot; class=&quot;form-label&quot;&gt;Username&lt;/label&gt;<br>      &lt;input <br>        type=&quot;text&quot; <br>        class=&quot;form-control {% if messages.username_error %}is-invalid{% endif %}&quot; <br>        id=&quot;username&quot; <br>        name=&quot;username&quot;<br>        value=&quot;{{ messages.username or &#39;&#39; }}&quot;<br>        placeholder=&quot;Username&quot;&gt;<br>      &lt;div class=&quot;invalid-feedback&quot;&gt;{{ messages.username_error }}&lt;/div&gt;<br>    &lt;/div&gt;<br>    &lt;div class=&quot;mb-3&quot;&gt;<br>      &lt;label for=&quot;email&quot; class=&quot;form-label&quot;&gt;Email address&lt;/label&gt;<br>      &lt;input <br>        type=&quot;email&quot; <br>        class=&quot;form-control {% if messages.email_error %}is-invalid{% endif %}&quot; <br>        id=&quot;email&quot;<br>        name=&quot;email&quot;<br>        value=&quot;{{ messages.email or &#39;&#39; }}&quot;<br>        placeholder=&quot;Email Address&quot;&gt;<br>      &lt;div class=&quot;invalid-feedback&quot;&gt;{{ messages.email_error }}&lt;/div&gt;<br>    &lt;/div&gt;<br>    &lt;div class=&quot;mb-3&quot;&gt;<br>      &lt;label for=&quot;password&quot; class=&quot;form-label&quot;&gt;Password&lt;/label&gt;<br>      &lt;input <br>        type=&quot;password&quot; <br>        class=&quot;form-control {% if messages.password_error %}is-invalid{% endif %}&quot; <br>        id=&quot;password&quot; <br>        name=&quot;password&quot; <br>        value=&quot;{{ messages.password or &#39;&#39; }}&quot;<br>        placeholder=&quot;Password&quot;&gt;<br>      &lt;div class=&quot;invalid-feedback&quot;&gt;{{ messages.password_error }}&lt;/div&gt;<br>    &lt;/div&gt;<br>    &lt;div&gt;<br>      &lt;button type=&quot;submit&quot; class=&quot;btn btn-primary&quot;&gt;Sign me up!&lt;/button&gt;<br>    &lt;/div&gt;<br>  &lt;/form&gt;<br>{% endblock %}</pre><pre>{% block scripts %}<br>{% endblock %}</pre><p>We’re using nunjucks to implement some dynamic behaviour.</p><p>The first is adding the is-invalid class to the form controls using flashed messages from the server. This adds an error message attached to the form control.</p><p>The second is setting the previous value entered by the user (an optional UX feature for the purposes of this tutorial).</p><p>After creating the register template, create the routes associated with the template.</p><p>Create a folder named ‘routes’ in the root of the project. This folder will hold all of our routes. Create a file ‘register.js’ in this folder. The contents of this file should be as follows:</p><pre>var router = require(&#39;express&#39;).Router()<br>const Joi = require(&#39;joi&#39;)<br>const { User } = require(&#39;../models&#39;)</pre><pre>const validateRegistrationInfo = async (req, res, next) =&gt; {<br>  for(let [key, value] of Object.entries(req.body)) {<br>    req.flash(`${key}`, value)<br>  }<br>  /* Validate the request parameters.<br>  If they are valid, continue with the request.<br>  Otherwise, flash the error and redirect to registration form. */<br>  const schema = Joi.object({<br>    name: Joi.string().required(),<br>    username: Joi.string().alphanum().min(6).max(12).required(),<br>    email: Joi.string()<br>        .email({ minDomainSegments: 2, tlds: { allow: [&#39;com&#39;, &#39;net&#39;] } }).required(),<br>    password: Joi.string().min(8).required()<br>  })</pre><pre>const error = schema.validate(req.body, { abortEarly: false }).error<br>  if (error) {<br>    error.details.forEach(currentError =&gt; {<br>      req.flash(`${currentError.context.label}_error`, currentError.message)<br>    })<br>    return res.redirect(&#39;/register&#39;)<br>  }</pre><pre>/** Check if user exists */<br>  const userExists = await User.userExists(req.body)<br>  if (userExists) {<br>    for(let [key, message] of Object.entries(userExists)) {<br>      req.flash(`${key}`, message)<br>    }<br>    return res.redirect(&#39;/register&#39;)<br>  }</pre><pre>next()  <br>}</pre><pre>router.get(&#39;/register&#39;, (req, res) =&gt; res.render(&#39;register.html&#39;))</pre><pre>router.post(&#39;/register&#39;, validateRegistrationInfo, async (req, res) =&gt; {<br>  let savedUser = await (new User(req.body)).save()<br>  res.redirect(&#39;/&#39;)<br>})</pre><pre>module.exports = router</pre><p>The first significant block of code is a function called <strong><em>validateRegistrationInfo</em></strong>. This is middleware that will be used to validate the user’s registration information.</p><p>In the first phase of the validation, we immediately flash the current information for pre-population in case we redirect back to the registration page.</p><p>Phase 2 is validating each entry against a validation schema. The <a href="https://joi.dev/">Joi</a> package makes this process easy.</p><p>If there are any errors on validation, flash each error message for that particular entry before redirecting to the register page. Display this error message in the template.</p><p>The final phase of validation is checking whether the username/email provided are already in use. If they are, flash the error message before redirecting to the register route.</p><p>Create a GET route that simply renders ‘register.html’. This is the route we redirect to when validation fails.</p><p>Create a post route that receives the data entered by the user in the request body passing the validation middleware to it.</p><p>In the route handler itself, we don’t have to worry about invalid data as it would have passed all the validation checks if the handler is being executed.</p><p>Create a new user using the provided data, save it, and redirect to the home page.</p><p>Export this router object and import it in the entry file as follows:</p><pre>// Import rotues <br>app.use(&#39;/&#39;, require(&#39;./routes/register&#39;))</pre><h3>Authentication</h3><p>Now that we’ve taken care of the registration, it’s time to implement the authentication logic of our application.</p><p>Start by creating a login form. This form has a username/email field and a password field. We’ll also include a condition that checks for an error message to display in an alert. This will be displayed when we redirect to the login page after flashing a message.</p><p>Place this form in a ‘login.html’ template file in the views folder alongside the register template.</p><pre>{% extends &#39;base.html&#39; %}</pre><pre>{% set title = &#39;Login&#39; %}</pre><pre>{% block styles %}<br>  &lt;style&gt;<br>    form {<br>      margin-top: 20px;<br>      margin-left: 20px;<br>      margin-right: 20px;<br>    }<br>  &lt;/style&gt;<br>{% endblock %}</pre><pre>{% block content %}<br>  &lt;form action=&quot;/login&quot; method=&quot;POST&quot;&gt;<br>    {% if messages.error %}<br>      &lt;div class=&quot;alert alert-danger&quot; role=&quot;alert&quot;&gt;{{ messages.error }}&lt;/div&gt;<br>    {% endif %}<br>    &lt;div class=&quot;mb-3&quot;&gt;<br>      &lt;label for=&quot;name&quot; class=&quot;form-label&quot;&gt;Username or Email&lt;/label&gt;<br>      &lt;input <br>        type=&quot;text&quot; <br>        class=&quot;form-control {% if messages.name_error %}is-invalid{% endif %}&quot; <br>        id=&quot;username&quot; <br>        name=&quot;username&quot;<br>        value=&quot;{{ messages.name or &#39;&#39; }}&quot;&gt;<br>      &lt;div class=&quot;invalid-feedback&quot;&gt;{{ messages.name_error }}&lt;/div&gt;<br>    &lt;/div&gt;<br>    &lt;div class=&quot;mb-3&quot;&gt;<br>      &lt;label for=&quot;name&quot; class=&quot;form-label&quot;&gt;Password&lt;/label&gt;<br>      &lt;input <br>        type=&quot;password&quot; <br>        class=&quot;form-control {% if messages.name_error %}is-invalid{% endif %}&quot; <br>        id=&quot;password&quot; <br>        name=&quot;password&quot;<br>        value=&quot;{{ messages.name or &#39;&#39; }}&quot;&gt;<br>      &lt;div class=&quot;invalid-feedback&quot;&gt;{{ messages.name_error }}&lt;/div&gt;<br>    &lt;/div&gt;<br>    &lt;div&gt;<br>      &lt;button type=&quot;submit&quot; class=&quot;btn btn-primary&quot;&gt;Login&lt;/button&gt;<br>    &lt;/div&gt;<br>  &lt;/form&gt;<br>{% endblock %}</pre><pre>{% block scripts %}<br>{% endblock %}</pre><p>The next task is to define the passport strategy used to authenticate the user. We’re using the strategy from passport-local because we’re authenticating against our own stored user credentials.</p><p>Create a new file in the root of the project called ‘passport-helper.js’ with the following contents:</p><pre>const LocalStrategy = require(&#39;passport-local&#39;).Strategy<br>const { User } = require(&#39;./models&#39;)</pre><pre>module.exports = (app, passport) =&gt; {</pre><pre>passport.use(new LocalStrategy((username, password, done) =&gt; {<br>    User.authenticate(username, password)<br>    .then( user =&gt; {<br>      done(null, user)<br>    })<br>    .catch( error =&gt; {<br>      done(error)<br>    })<br>  }))</pre><pre>passport.serializeUser((user, done) =&gt; {<br>    done(null, user._id)<br>  })</pre><pre>passport.deserializeUser((id, done) =&gt; {<br>    User.findById(id, (error, user) =&gt; {<br>      if (error) return done(error)<br>      done(null, user)<br>    })<br>  })</pre><pre>app.use(passport.initialize())<br>  app.use(passport.session())<br>}</pre><p>The first step is importing the Strategy and the User model.</p><p>The second step is configuring the strategy. We create a new instance of the strategy passing it a function that takes username, password and a verify callback (done) function that is executed after the authentication process is complete.</p><p>The authentication logic is placed inside this function. In order to keep this clean, we will simply use the ‘authenticate’ static method we created in the user model.</p><p>When authenticating in passport, a user object is passed to the verify callback upon successful authentication, otherwise false is returned (provided there’s no error thrown in which case, pass the error).</p><p>Our authenticate method returns a user object if the user is found and false otherwise so its output is perfect for this scenario.</p><p>Once we’ve configured the strategy, we have to specify the user serialization and deserialization logic.</p><p>This step is optional if you’re not using sessions, but we’re trying to create a login system with sessions so in our case, it’s necessary.</p><p>The serializeUser method takes a function with a user object and a callback as parameters which determines the data that will be stored in the session itself.</p><p>To keep the data stored in the session small, we store only the user ID in the session. This serialization process happens on initial login.</p><p>The deserializeUser method takes a function that receives the user ID and a callback. This method runs on all subsequent requests after login/serialization.</p><p>The user ID is grabbed from the session and the user is retrieved from the database. Once the user is retrieved, they are stored in req.user.</p><p>After serialization/deserialization, make sure to add passport initialize and session middleware to the app. We’ll wrap all of this up in a function that takes our app and passport objects as parameters.</p><p>Our passport configuration is now complete. The next step is to initialize passport.</p><p>In the application entry file, import the function we created in the previous step and then execute it, passing the app and passport objects.</p><p>Make sure to have the require statement after the passport require statement. The initialization function must be called after session middleware is defined because the passport session middleware utilises it.</p><pre>const initializePassport = require(&#39;./passport-helper&#39;) </pre><pre>... </pre><pre>initializePassport(app, passport)</pre><p>Now let’s create the login routes. Inside the routes folder, create a file called ‘login.js’ and add the following code:</p><pre>const createLoginRoutes = passport =&gt; {<br>  const router = require(&#39;express&#39;).Router()</pre><pre>router.get(&#39;/login&#39;, (req, res) =&gt; {<br>    if (req.isAuthenticated()) return res.redirect(&#39;/&#39;)<br>    res.render(&#39;login.html&#39;)<br>  })<br>  <br>  router.post(<br>    &#39;/login&#39;,<br>    passport.authenticate(&#39;local&#39;, {<br>      failureRedirect: &#39;/login&#39;, <br>      successRedirect: &#39;/&#39;,<br>      failureFlash: &#39;User not found&#39;, <br>    }),<br>    (error, req, res, next) =&gt; {<br>      if (error) next(error)<br>    }<br>  )</pre><pre>router.get(&#39;/logout&#39;, (req, res) =&gt; {<br>    req.logout()<br>    res.redirect(&#39;/login&#39;)<br>  })<br>  <br>  return router<br>}</pre><pre>module.exports = createLoginRoutes</pre><p>Instead of creating routes in the same way we did in the register route file, we’re doing it a bit differently here.</p><p>Since we’re going to need the passport object, we will instead export a function that accepts a passport object as a parameter, defines the routes and returns the router object.</p><p>The first route is a GET route for ‘/login’. This renders the form when there is no active session. Use the ‘isAuthenticated’ method provided by passport in the request object in order to determine whether there is currently an active session.</p><p>The second route is a POST route from ‘/login’. This route accepts the form input from the user.</p><p>Pass the passport.authenticate middleware to this route to handle the authentication. This middleware accepts the strategy type and an options object.</p><p>In the options object, specify the redirect path in case of failure and in case of success. The failureFlash property specifies the message to flash in case of authentication failure. This is the message you should check for and display on the login page.</p><p>Finally, create a logout route that calls req.logout to end the current user’s session. This logout method is also provided by passport.</p><p>Now import the login route creator in the entry file and pass the passport object to it:</p><pre>app.use(&#39;/&#39;, require(&#39;./routes/auth&#39;)(passport))</pre><p>Update the home page route to the following:</p><pre>app.get(&#39;/&#39;, async (req, res) =&gt; {<br>  if (!req.isAuthenticated()) return res.redirect(&#39;/login&#39;)<br>  res.render(&#39;home.html&#39;)<br>})</pre><p>The home page route is now a protected route. This means it should only be accessed by an authenticated user.</p><p>We achieve this by using the req.isAuthenticated method to make sure the user is authenticated. If not, redirect to the login page.</p><p>Go back to the register route file and update the GET route. to the following:</p><pre>router.get(&#39;/register&#39;, (req, res) =&gt; {<br>  if (req.isAuthenticated()) return res.redirect(&#39;/&#39;)<br>  res.render(&#39;register.html&#39;)<br>})</pre><p>We only need to render the registration form if the user is not authenticated, otherwise, redirect to the home page.</p><h3>Conclusion</h3><p>In this article, I demonstrated how to create a simple registration/authentication system in ExpressJS using PassportJS. However, an authentication system is not complete without a password reset feature.</p><p>The next article will be a tutorial on <a href="https://kelvinmwinuka.com/how-to-handle-password-reset-in-expressjs/">creating a password reset feature using mongoose and NodeMailer.</a></p><p><strong>If you enjoyed this article, consider following my </strong><a href="https://kelvinmwinuka.com/"><strong>personal website</strong></a><strong> for early access to my content before it gets published on Medium (don’t worry, it’s still free with no annoying pop-up ads!). Also, feel free to comment on this post. I’d love to hear your thoughts!</strong></p><p><em>Originally published at </em><a href="https://kelvinmwinuka.com/how-to-create-registration-authentication-with-express-passportjs/"><em>https://kelvinmwinuka.com</em></a><em> on December 21, 2020.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=eb9450a9fa3b" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/how-to-create-registration-authentication-with-express-passportjs-eb9450a9fa3b">How to Create Registration &amp; Authentication with Express &amp; PassportJS</a> was originally published in <a href="https://javascript.plainenglish.io/">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How To Set Up Mongoose With Express.js]]></title>
            <link>https://javascript.plainenglish.io/how-to-set-up-mongoose-with-expressjs-da2cc34c9219?source=rss-70822592ab6------2</link>
            <guid isPermaLink="false">https://medium.com/p/da2cc34c9219</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[expressjs]]></category>
            <dc:creator><![CDATA[Kelvin]]></dc:creator>
            <pubDate>Thu, 17 Dec 2020 03:12:58 GMT</pubDate>
            <atom:updated>2020-12-26T17:10:52.665Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ETD8F28vnid0ngvd.jpg" /></figure><p>In the previous article, I demonstrated <a href="https://kelvinmwinuka.com/how-to-set-up-nunjucks-with-expressjs/">how to set up Nunjucks template engine</a> in your express project. I decided to make this a full-fledged web app development series of articles by progressively building the example application. In this article, we are going to connect the app to a MongoDB database using Mongoose.</p><p>Mongoose is an ODM (Object Document Mapper) that allows interaction with MongoDB databases using JavaScript objects.</p><p>It provides extra functionality (such as static methods on the schema) that allows us to enhance database interactions and write cleaner code.</p><p>At the time of writing this article, the latest stable version of Mongoose is v5.11.8. This will most likely be different at the time of reading although most of the information here should still be relevant.</p><p>Makes sure you have a MongoDB server installed and running on your system before following along. If not, you can<a href="https://www.mongodb.com/cloud/atlas"> sign up for a free cluster </a>at MongoDB Atlas and connect to that instead.</p><h3>Mongoose setup</h3><p>First install Mongoose and dotenv using the following command:</p><pre>npm install mongoose dotenv</pre><p>Dotenv allows us to load environment variables into our application. We are going to place the MongoDB URI in an environment variable file instead of hard-coding it.</p><p>Doing this allows us to connect to different MongoDB instances in different environments by only changing this URI in the environment variable without changing the code itself.</p><p>Create a file called “.env” in the root of your project. The contents of the files should be as follows:</p><pre>PORT=8000 MONGO_URI=mongodb://localhost:27017/app</pre><p>We’ve defined the port here along with the MongoDB URI. make sure to change the values according to your setup.</p><p>Now go back to your index.js file (or the file in which your app instance is initialised) and add the following line at the beginning of the file:</p><pre>if (process.env.ENV === &#39;dev&#39;) require(&#39;dotenv&#39;).config()</pre><p>This loads the .env file in our project if we’re in the development environment. We can access each environment variable using “process.env.&lt;variable_name&gt;”.</p><p>The dotenv package will look for the .env file in our project when the config method is invoked.</p><p>Placing this at the top of the entry point file ensures the environment variables are available to the entire application when we decide to go with a modular approach with our route organisation.</p><p>Now import mongoose:</p><pre>const mongoose = require(&#39;mongoose&#39;)</pre><p>Create a mongoose connection by inserting the following code before the route definitions:</p><pre>const connection = mongoose.connect(process.env.MONGO_URI, {<br>  useNewUrlParser: true,<br>  useUnifiedTopology: true<br>})</pre><pre>/* Display message in the console if the connection is successful. */<br>mongoose.connection.once(&#39;open&#39;, () =&gt; {<br>  console.log(&#39;connected!&#39;)<br>})</pre><h3>Models</h3><p>Our mongoose connection has been established. The next step is to define our models. Models are object representations of the documents that will reside in our database.</p><p>Models in mongoose require a schema. A schema specifies the structure of the document.</p><p>If you’re familiar with NoSQL databases, particularly MongoDB, you might be aware that one of the benefits is that the schema is dynamic. Meaning you can add new fields to a document on the fly upon creation/update.</p><p>This may be a good idea depending on your use case but mongoose requires schemas in order to define the shape of the documents in the collection. This ensures we have consistency in a collection and a reference point for what properties are contained in each document.</p><p>Let’s begin setting up our models by creating a folder in the root of our project named ‘model’. Next, create a file inside this folder called ‘User.js’. It’s a good idea to separate models into their own files.</p><p>Inside User.js, add the following code:</p><pre>const { Schema, model } = require(&#39;mongoose&#39;)</pre><pre>var userSchema = new Schema({<br>  name: {<br>    type: Schema.Types.String,<br>    required: [true, &#39;You must provide a name&#39;]<br>  },<br>  email: {<br>    type: Schema.Types.String,<br>    required: [true, &#39;Email address is required&#39;]<br>  },<br>  username: {<br>    type: Schema.Types.String,<br>    required: [true, &#39;Username is required&#39;]<br>  },<br>  password: {<br>    type: Schema.Types.String,<br>    required: [true, &#39;You must provide a password&#39;]<br>  }<br>})</pre><pre>const User = model(&#39;User&#39;, userSchema)</pre><p>Let’s walk through the contents of this file:</p><ul><li>Import Schema and model from mongoose.</li><li>Create a schema instance that defines the structure of the user document in the User collection.</li><li>Create a model instance and pass it the collection name and schema.</li><li>Export the user model for use in routes.</li></ul><p>Now create an index file within the models directory. This file will import all of the models from its sibling files and export them in an object. We’re doing this to reduce the number of require statements in other files when importing models.</p><p>You can certainly import models directly from their respective files, but this is definitely a cleaner way of doing it.</p><p>The contents of this index.js file should look like this for now:</p><pre>const User = require(&#39;./User&#39;) module.exports = { User }</pre><h3>Using the models</h3><p>It’s time to test if this works. We’re going to insert a user into the collection if the collection is empty and retrieve the users in the collection otherwise.</p><p>In the app entry file, import the User model from the models index file as follows:</p><pre>// Import models <br>const { User } = require(&#39;./models&#39;)</pre><p>Update the home route to the following:</p><pre>app.get(&#39;/&#39;, async (req, res) =&gt; {<br>  const users = await User.find({})<br>  if (users.length) {<br>    /* Log users if users exists. */<br>    console.log(users)<br>  } else {<br>    /* If no users exist, save new user and log saved user on the console. */<br>    let newUser = new User({<br>      name: &#39;Kelvin Mwinuka&#39;,<br>      email: &#39;<a href="/service/mailto:email@kelvinmwinuka.com">email@kelvinmwinuka.com</a>&#39;,<br>      username: &#39;kelvin&#39;,<br>      password: &#39;password&#39;<br>    })<br>    let savedUser = await newUser.save()<br>    console.log(savedUser)<br>  }<br>  res.render(&#39;home.html&#39;)<br>})</pre><p>Navigate to this route in the browser and you should notice that for the first time, a single object is printed to the console:</p><pre>{<br>  _id: 5fdab492561efb3e9a2c56c7,<br>  name: &#39;Kelvin Mwinuka&#39;,<br>  email: &#39;<a href="/service/mailto:email@kelvinmwinuka.com">email@kelvinmwinuka.com</a>&#39;,<br>  username: &#39;kelvin&#39;,<br>  password: &#39;password&#39;,<br>  __v: 0<br>}</pre><p>When you refresh the page, the results should now be as follows:</p><pre>[<br>  {<br>    _id: 5fdab492561efb3e9a2c56c7,<br>    name: &#39;Kelvin Mwinuka&#39;,<br>    email: &#39;<a href="/service/mailto:email@kelvinmwinuka.com">email@kelvinmwinuka.com</a>&#39;,<br>    username: &#39;kelvin&#39;,<br>    password: &#39;password&#39;,<br>    __v: 0<br>  }<br>]</pre><p>Notice this is an array of current documents and no new user is created/saved.</p><p>That’s it. We’ve successfully set up mongoose and we’re ready to start persisting data in our MongoDB database!</p><h3>Conclusion</h3><p>In this article, we’ve gone over connecting our express application to a MongoDB database, creating mongoose models and using those models to save data into our database.</p><p>In the next article, I will be going over user registration and authentication using Passport JS.</p><p>You can track the progress of this project on <a href="https://github.com/kelvinmwinuka/express-tutorial">Github</a>.</p><p><em>If you enjoyed this article, consider following my </em><a href="https://kelvinmwinuka.com/"><em>personal website</em></a><em> for early access to my content before it gets published on Medium (don’t worry, it’s still free with no annoying pop-up ads!). Also, feel free to comment on this post. I’d love to hear your thoughts!</em></p><p><em>Originally published at </em><a href="https://kelvinmwinuka.com/how-to-set-up-mongoose-with-expressjs/"><em>https://kelvinmwinuka.com</em></a><em> on December 17, 2020.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=da2cc34c9219" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/how-to-set-up-mongoose-with-expressjs-da2cc34c9219">How To Set Up Mongoose With Express.js</a> was originally published in <a href="https://javascript.plainenglish.io/">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Set Up Nunjucks with Express.js]]></title>
            <link>https://javascript.plainenglish.io/how-to-set-up-nunjucks-with-expressjs-30f52cdf275e?source=rss-70822592ab6------2</link>
            <guid isPermaLink="false">https://medium.com/p/30f52cdf275e</guid>
            <category><![CDATA[expressjs]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Kelvin]]></dc:creator>
            <pubDate>Wed, 16 Dec 2020 02:33:04 GMT</pubDate>
            <atom:updated>2020-12-26T17:10:26.029Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*CnvyPg5Oe_dtuAWp.jpg" /></figure><p>When building a web app without a dedicated front-end framework like ReactJS, Templating engines (e.g. Blade, Nunjucks) are incredibly useful.</p><p>Though they aren’t entirely necessary, they definitely help create more dynamic pages with cleaner HTML code.</p><p>Before getting into JavaScript, Flask and Django were my preferred choices for building web applications. Coming from that background, I got very used to the Jinja2 engine.</p><p>When I switched to using Express for web app development, I wanted a solution that would have similar syntax and features to Jinja2. Fortunately, Nunjucks is exactly that. This is a templating engine that is heavily inspired by Jinja2.</p><p>In this article, I will walk you through the Nunjucks setup for ExpressJS. This is a fairly simple and straight-forward process.</p><h3>Setup</h3><p>First, create an empty folder. Navigate into the folder and run the following command to initialise npm:</p><pre>npm init</pre><p>Follow all the prompts to set up your project.</p><p>Once the setup process has completed, you should have a package.json file in the root of your project.</p><h3>Installing packages</h3><p>Next, run the following command to install express and nunjucks.</p><pre>npm install express nunjucks</pre><h3>Defining the entry point</h3><p>Now create the file that will be the entry point of our application. I name this file index.js and place it at the root of my project.</p><p>The contents of index.js are as follows:</p><pre>const express = require(&#39;express&#39;)<br>const nunjucks = require(&#39;nunjucks&#39;)</pre><pre>var app = express()</pre><pre>nunjucks.configure(&#39;views&#39;, {<br>  autoescape: true,<br>  express: app<br>})</pre><pre>app.set(&#39;view engine&#39;, &#39;html&#39;)</pre><pre>const PORT = &#39;8000&#39;</pre><pre>app.get(&#39;/&#39;, (req, res) =&amp;gt; {<br>  res.render(&#39;home.html&#39;)<br>})</pre><pre>app.listen(PORT, () =&amp;gt; {<br>  console.log(`Listening on port ${PORT}...`)<br>})</pre><ul><li>Configuring nunjucks: The first parameter is the path to the template folder. The second parameter is an object containing configuration options. <a href="https://mozilla.github.io/nunjucks/templating.html#autoescaping">Autoescape</a> makes sure all output to templates are escaped before display (recommended). You can manually mark the output as safe. The express property requires an instance of an express app.</li><li>Set the port number. We’ll use this when starting the application later.</li><li>Create a ‘get’ route at ‘/’ and return a response that simply renders the template home.html.</li><li>Listen for connections on the specified port.</li></ul><h3>Creating the templates</h3><p>At the moment if you try to load the application, you’ll get an error because we haven’t created the template that we’re trying to render yet.</p><p>Remember that we set the path to templates as ‘views’. Nunjucks will look for the ‘views’ folder in the same directory as the script that runs the configuration.</p><p>If you have your template folder in another directory or have named it something different like ‘templates’, make sure you configure the path correctly.</p><p>In this case, we have to create a folder called ‘views’ in the root of our project (because this is where index.js resides).</p><p>Inside the views folder, create a base.html template. This is the template that will be inherited by other templates. It allows us to define certain UI elements, styles and scripts only once and have them displayed/imported on every template.</p><p>This is where we’d define navigation bars and page footers.</p><p>The contents of base.html are as follows:</p><pre>&lt;!DOCTYPE html&gt;</pre><pre><strong>&lt;html&gt;</strong></pre><pre><strong>  &lt;head&gt;</strong></pre><pre><strong>    &lt;meta</strong> charset=&quot;utf-8&quot;<strong>&gt;</strong></pre><pre><strong>    &lt;meta</strong> http-equiv=&quot;X-UA-Compatible&quot; content=&quot;IE=edge&quot;<strong>&gt;</strong></pre><pre><strong>    &lt;title&gt;</strong>{{ title }}<strong>&lt;/title&gt;</strong></pre><pre><strong>    &lt;meta</strong> name=&quot;description&quot; content=&quot;&quot;<strong>&gt;</strong></pre><pre><strong>    &lt;meta</strong> name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1&quot;<strong>&gt;</strong></pre><pre><strong>    &lt;link</strong> rel=&quot;stylesheet&quot; href=&quot;&quot;<strong>&gt;</strong></pre><pre><strong>  &lt;/head&gt;</strong></pre><pre><strong>  &lt;body&gt;</strong></pre><pre>    {% block content %}{% endblock %}</pre><pre><strong>    &lt;script</strong> src=&quot;&quot; async defer<strong>&gt;&lt;/script&gt;</strong></pre><pre><strong>  &lt;/body&gt;</strong></pre><pre><strong>&lt;/html&gt;</strong></pre><p>We’ve defined a content block that will be overridden by the child templates. This is where the child templates will place their respective content.</p><p>Next, create a home.html template that extends base.html and displays a simple header in the content block.</p><pre>{% extends &#39;base.html&#39; %}</pre><pre>{% set title = &#39;Home&#39; %} </pre><pre>{% block content %} <br>  &lt;h1&gt;Welcome home!&lt;/h1&gt;<br>{% endblock %}</pre><p>Now that we’ve created the templates, we’re able to load the home page. Visit localhost at the specified port and you should see that your app is up and running!</p><h3>Conclusion</h3><p>In this article, we’ve covered setting up the nunjucks templating engine with an express web application. In the next article, I will write about <a href="https://kelvinmwinuka.com/how-to-set-up-mongoose-with-expressjs/">connecting an express application to MongoDB using mongoose</a> so we can persist data.</p><p>You can track the progress of this project on <a href="https://github.com/kelvinmwinuka/express-tutorial">Github</a>.</p><p><em>If you enjoyed this article, consider following my </em><a href="https://kelvinmwinuka.com/"><em>personal website</em></a><em> for early access to my content before it gets published on Medium (don’t worry, it’s still free with no annoying pop-up ads!). Also, feel free to comment on this post. I’d love to hear your thoughts!</em></p><p><em>Originally published at </em><a href="https://kelvinmwinuka.com/how-to-set-up-nunjucks-with-expressjs/"><em>https://kelvinmwinuka.com</em></a><em> on December 16, 2020.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=30f52cdf275e" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/how-to-set-up-nunjucks-with-expressjs-30f52cdf275e">How to Set Up Nunjucks with Express.js</a> was originally published in <a href="https://javascript.plainenglish.io/">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>