{"componentChunkName":"component---src-templates-blog-post-js","path":"/intro-to-nodejs-part-3/","result":{"data":{"site":{"siteMetadata":{"title":"tech-blog","author":"Alamgir Qazi"}},"markdownRemark":{"id":"f8d279d0-07cf-5c67-b025-67ed1bfbe610","excerpt":"This is the part 3 of post Intro to Nodejs - part 2. In this post, we will look at improving our existing code and add new features like…","html":"<p>\n  <a\n    class=\"gatsby-resp-image-link\"\n    href=\"/tech-blog/static/a717eafa290bf333c4dd1c86076c5b9e/d9199/node-js.png\"\n    style=\"display: block\"\n    target=\"_blank\"\n    rel=\"noopener\"\n  >\n  \n  <span\n    class=\"gatsby-resp-image-wrapper\"\n    style=\"position: relative; display: block;  max-width: 590px; margin-left: auto; margin-right: auto;\"\n  >\n    <span\n      class=\"gatsby-resp-image-background-image\"\n      style=\"padding-bottom: 50%; position: relative; bottom: 0; left: 0; background-image: url('data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABQAAAAKCAYAAAC0VX7mAAAACXBIWXMAAAsTAAALEwEAmpwYAAACKElEQVQoz32Sz2vTYBjHnzfVHedglzpRUUSTTE3UJq9jS9I0s/h7BwXdZbUyRUS9+A8sWZqijrGDN0+iB0U8CP4Nw7Vqi9OLStllIHrx5kWI3ydpvWngy/O27/N+np9E//m8sk2ua5ED4ayUfUkD/fMbOAQnJdXCI7SwqlPc0ShqaVSdscgtWzTllDL4wNevSJo+ZVM9MSlc06nR1WjhjUpLX8YzoJJFr0hlfvkwLb7TlLClKotvNcU+OAFQBhmBbkIFSMC/gP+VNCWK32uCgZBY+poD8+iIeqVhEEAUtlWKYE9fKgm+v3/3Hvt9h1+RA0wck2iFpEe/D1Ccw4YYCqDCjgH02g9kpZ4YFLU1B1k+gfXrTYP8aWnxPQPLFXsYQMuZlC9hq5UTNleko0UeNI6StzHwF/TM8+S3WmgW4476A9mlsD+vrxhjyKSH7B+XfXsT572AbpyfK7XxZvXGQ2M0WVdnUPZVAO8kH/RhBm6cnbW3Ati9eOvorrir9vrAzWvLZtFz5Wf4vIB6AI71gc+Dqtz+Kt29BRkybB66DeAIA/fjESH9fUQXlOYnVYXTA0zZqDdMLtmEz1NIIigP6RBKXoHdeWbWomhN34H+TUJ7eDvyoQCIhzREASUfeSAq95JqkSnQ278r47q24KFMHcfZyVcoauk86Ww4zfUcKPgSD8Uo+QwUUVstoGwxF5m8c9ma9Ncr80c/+TdVz9kMFBmwo4k0vUx/ANst4OwYAzGqAAAAAElFTkSuQmCC'); background-size: cover; display: block;\"\n    >\n      <img\n        class=\"gatsby-resp-image-image\"\n        style=\"width: 100%; height: 100%; margin: 0; vertical-align: middle; position: absolute; top: 0; left: 0; box-shadow: inset 0px 0px 0px 400px white;\"\n        alt=\"Intro To Node.js\"\n        title=\"\"\n        src=\"/tech-blog/static/a717eafa290bf333c4dd1c86076c5b9e/fcda8/node-js.png\"\n        srcset=\"/tech-blog/static/a717eafa290bf333c4dd1c86076c5b9e/12f09/node-js.png 148w,\n/tech-blog/static/a717eafa290bf333c4dd1c86076c5b9e/e4a3f/node-js.png 295w,\n/tech-blog/static/a717eafa290bf333c4dd1c86076c5b9e/fcda8/node-js.png 590w,\n/tech-blog/static/a717eafa290bf333c4dd1c86076c5b9e/efc66/node-js.png 885w,\n/tech-blog/static/a717eafa290bf333c4dd1c86076c5b9e/d9199/node-js.png 960w\"\n        sizes=\"(max-width: 590px) 100vw, 590px\"\n      />\n    </span>\n  </span>\n  \n  </a>\n    </p>\n<p>This is the part 3 of post <a href=\"https://alamgirqazi.github.io/tech-blog/intro-to-nodejs-part-2/\">Intro to Nodejs - part 2</a>.</p>\n<p>In this post, we will look at improving our existing code and add new features like password hashing. We will also take a look at JWT tokens.</p>\n<p>First we define a User model.</p>\n<div class=\"gatsby-highlight\" data-language=\"text\"><pre class=\"language-text\"><code class=\"language-text\">const Users = mongoose.model('Users', {\n    name: String,\n    email: String,\n    password: String,\n    date_added: Date\n   });</code></pre></div>\n<p>Right. Now we first set up login / Signup.</p>\n<p>We will make some changes in the Signup method we wrote in previous tutorial. Remember, we never save passwords as string in database. They are always hashed.</p>\n<p>We need to encrypt passwords. Node.js provides us a module for that, Bcrypt. Brcypt causes dependency issues so instead, we will use <code class=\"language-text\">bcryptjs</code></p>\n<div class=\"gatsby-highlight\" data-language=\"text\"><pre class=\"language-text\"><code class=\"language-text\">npm install bcryptjs</code></pre></div>\n<p>btw I would recommend installing <a href=\"https://yarnpkg.com/lang/en/\">yarn</a> and running <code class=\"language-text\">yarn add bcryptjs</code> instead.</p>\n<p>Lets get back to our code.</p>\n<p>we first include bcrypt at the top</p>\n<div class=\"gatsby-highlight\" data-language=\"text\"><pre class=\"language-text\"><code class=\"language-text\">const bcrypt = require('bcryptjs');</code></pre></div>\n<p>now modifying our /signup method</p>\n<div class=\"gatsby-highlight\" data-language=\"text\"><pre class=\"language-text\"><code class=\"language-text\"> app.post('/signup', async (req, res) => {\n\n  try{\n    const body = req.body;\n\n    // there must be a password in body\n\n    // we follow these 2 steps\n\n    const password = body.password;\n\n    var salt = bcrypt.genSaltSync(10);\n    var hash = bcrypt.hashSync(password, salt);\n\n    console.log('hash - > ', hash);\n    // const user = new Users(body);\n\n\n    // const result = await user.save();\n\n    // res.send({\n    //   message: 'Student signup successful'\n    // });\n\n  }\n\n  catch(ex){\n    console.log('ex',ex)\n\n    res.send({\n      message: 'Error',\n      detail: ex\n    }).status(500);\n  }\n\n  });</code></pre></div>\n<p>A couple of things to notice.</p>\n<ol>\n<li>I wrapped the code in try/catch. Always use it when you are using <code class=\"language-text\">await</code> in the code.</li>\n<li>we are using bcrypt to hash the password.</li>\n</ol>\n<p>let try it in Postman and see what we get in console.</p>\n<p>\n  <a\n    class=\"gatsby-resp-image-link\"\n    href=\"/tech-blog/static/9ff9af508b79073fab772f4323fc76f1/b9024/testsignup1.png\"\n    style=\"display: block\"\n    target=\"_blank\"\n    rel=\"noopener\"\n  >\n  \n  <span\n    class=\"gatsby-resp-image-wrapper\"\n    style=\"position: relative; display: block;  max-width: 590px; margin-left: auto; margin-right: auto;\"\n  >\n    <span\n      class=\"gatsby-resp-image-background-image\"\n      style=\"padding-bottom: 55.4054054054054%; position: relative; bottom: 0; left: 0; background-image: url('data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABQAAAALCAYAAAB/Ca1DAAAACXBIWXMAABJ0AAASdAHeZh94AAAB2ElEQVQoz5WQ227TQBCG/VBchKK0F4h34CmgaZ0eVBrn0IOKqFRVPAMCqkpREQLBBXfwAtzADVF6onUSe9f2+uyfmbVSGYsbRvo0u//O/Ls7xueDJzg+fIH+7gE6Vh9WbwddwmxvYHnFxPazDtbWN7FibmDVXCetjdbqGp62TFhUf9TtY7nVxtZ2D5tbFoyfR/fw9eUjnO49xOlgEWf7SxjuLeGk9wCvOw183F3A2WABJ937d7y1GnhDZ8OdJt73mxgOGvjwfBHv9psw0shGoa4B/wJIp0BGJBNa27R2So3XEIQkPKBwkflXSOU5EN1QHZ3HlNUVjMlM4HYiMHMkZQc3UwFHBHAlo8osfL0WHhNiJhSk6+LLDx+PXwXoffLBPg7VGEK4kFLAk5KMBKbX53Amt/B9T+tB4EMphTCsEiKm/NsN8e2XwvdL0hTVeQJGkqaIorIgjCIoMgrJIEkS3ZhlGYqi+AvWGPr7HUVOWhLDsG0bcRyjjALzyPOcXhfoXDXjiOhivkyb5yV5TJdH9OXxeKwN+ZCbqwbcxPzLVF9ffTntsyyHMRqNaFZSN1WDi/glVYO6UT1yGoOhB0wvnM+lCuspzbiu83yZus612pAPeVNnXvQ//AEM0R+qUthYJAAAAABJRU5ErkJggg=='); background-size: cover; display: block;\"\n    >\n      <img\n        class=\"gatsby-resp-image-image\"\n        style=\"width: 100%; height: 100%; margin: 0; vertical-align: middle; position: absolute; top: 0; left: 0; box-shadow: inset 0px 0px 0px 400px white;\"\n        alt=\"signup using postman\"\n        title=\"\"\n        src=\"/tech-blog/static/9ff9af508b79073fab772f4323fc76f1/fcda8/testsignup1.png\"\n        srcset=\"/tech-blog/static/9ff9af508b79073fab772f4323fc76f1/12f09/testsignup1.png 148w,\n/tech-blog/static/9ff9af508b79073fab772f4323fc76f1/e4a3f/testsignup1.png 295w,\n/tech-blog/static/9ff9af508b79073fab772f4323fc76f1/fcda8/testsignup1.png 590w,\n/tech-blog/static/9ff9af508b79073fab772f4323fc76f1/efc66/testsignup1.png 885w,\n/tech-blog/static/9ff9af508b79073fab772f4323fc76f1/c83ae/testsignup1.png 1180w,\n/tech-blog/static/9ff9af508b79073fab772f4323fc76f1/b9024/testsignup1.png 1203w\"\n        sizes=\"(max-width: 590px) 100vw, 590px\"\n      />\n    </span>\n  </span>\n  \n  </a>\n    </p>\n<p>Here’s what we get in our Node.js console</p>\n<p>\n  <a\n    class=\"gatsby-resp-image-link\"\n    href=\"/tech-blog/static/16854049296bcc15ff6c1163c97cb748/620ae/hash.png\"\n    style=\"display: block\"\n    target=\"_blank\"\n    rel=\"noopener\"\n  >\n  \n  <span\n    class=\"gatsby-resp-image-wrapper\"\n    style=\"position: relative; display: block;  max-width: 590px; margin-left: auto; margin-right: auto;\"\n  >\n    <span\n      class=\"gatsby-resp-image-background-image\"\n      style=\"padding-bottom: 54.05405405405405%; position: relative; bottom: 0; left: 0; background-image: url('data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABQAAAALCAYAAAB/Ca1DAAAACXBIWXMAABJ0AAASdAHeZh94AAABhklEQVQoz5WT3U7CQBCFZ1tg26KWtrQIFsT4St54oTHxAUy8MYjGn1pa8EK9NxGTQiDx7w2PU5SKIjFefJkzm52TM9kstY4O0L/vI3lIkPQHGcPHIZ6TMV6YV+ZtwHUwYj3CC+sp6Z1RP8Hb+Am90wBUrjoob1YYF9a6DXuDaTKpblqwG9ZE+6zXahYa3Pu+hXqd+8+6zmeOa6Jue6B6VaLZLKBUIkhJEIKgKASVIfofOVI5oa/B3cjDrkk4axJLLuMxtoairrOxCkHiT1JDTZUgu+TCMJZR8arwvFWG13fK3K+iVq3BsWyYKyYss8SYkPnCZHhq8sGMoSpyf64yn4gyaCahTA2VzFDMITI9Nf6JmDEmFJQ8KPdpKH4Y/ZZqcWLxZShI+fdrLiJPHE6TElKT0PlFDcP4hm7oE6Y6O+e7KUXW6azUNWi6RFErgvZ2t3B+fIr4IkQ3iBBdhoiDDusObsMYN0zvKsJdJ8Y115uwi+5ZgIBnIq6H/NNarTaCkzZ2tvfxDvyILJLWBy3wAAAAAElFTkSuQmCC'); background-size: cover; display: block;\"\n    >\n      <img\n        class=\"gatsby-resp-image-image\"\n        style=\"width: 100%; height: 100%; margin: 0; vertical-align: middle; position: absolute; top: 0; left: 0; box-shadow: inset 0px 0px 0px 400px white;\"\n        alt=\"has\"\n        title=\"\"\n        src=\"/tech-blog/static/16854049296bcc15ff6c1163c97cb748/fcda8/hash.png\"\n        srcset=\"/tech-blog/static/16854049296bcc15ff6c1163c97cb748/12f09/hash.png 148w,\n/tech-blog/static/16854049296bcc15ff6c1163c97cb748/e4a3f/hash.png 295w,\n/tech-blog/static/16854049296bcc15ff6c1163c97cb748/fcda8/hash.png 590w,\n/tech-blog/static/16854049296bcc15ff6c1163c97cb748/efc66/hash.png 885w,\n/tech-blog/static/16854049296bcc15ff6c1163c97cb748/620ae/hash.png 1043w\"\n        sizes=\"(max-width: 590px) 100vw, 590px\"\n      />\n    </span>\n  </span>\n  \n  </a>\n    </p>\n<p>So this means, we will save $2a$10$GTxdgZ.KNxiGud.rvNM9SOfOTXuWKp/963ZlN6L9IR1ydSn8TclTy in database instead of 123456 which gives us more security. Even if our database is hacked, the user wont have direct access to passwords. He only can see the hash.</p>\n<p>We still need to do some work in password. we need to replace the old password with new hash.</p>\n<p>Just one line added</p>\n<div class=\"gatsby-highlight\" data-language=\"text\"><pre class=\"language-text\"><code class=\"language-text\">  const salt = bcrypt.genSaltSync(10);\n  const hash = bcrypt.hashSync(password, salt);\n\n  body.password = hash;</code></pre></div>\n<p>new updated code</p>\n<div class=\"gatsby-highlight\" data-language=\"text\"><pre class=\"language-text\"><code class=\"language-text\"> app.post('/signup', async (req, res) => {\n\n  try{\n    const body = req.body;\n\n    // there must be a password in body\n\n    // we follow these 2 steps\n\n    const password = body.password;\n\n    var salt = bcrypt.genSaltSync(10);\n    var hash = bcrypt.hashSync(password, salt);\n\n    body.password = hash;\n    console.log('hash - > ', hash);\n    const user = new Users(body);\n\n\n    const result = await user.save();\n\n    res.send({\n      message: 'Student signup successful'\n    });\n\n  }\n\n  catch(ex){\n    console.log('ex',ex)\n\n    res.send({\n      message: 'Error',\n      detail: ex\n    }).status(500);\n  }\n\n  });</code></pre></div>\n<p>Lets take a look at the database</p>\n<p>\n  <a\n    class=\"gatsby-resp-image-link\"\n    href=\"/tech-blog/static/850690ed04dcb5a7126644af2f288582/2c118/hashsaved.png\"\n    style=\"display: block\"\n    target=\"_blank\"\n    rel=\"noopener\"\n  >\n  \n  <span\n    class=\"gatsby-resp-image-wrapper\"\n    style=\"position: relative; display: block;  max-width: 590px; margin-left: auto; margin-right: auto;\"\n  >\n    <span\n      class=\"gatsby-resp-image-background-image\"\n      style=\"padding-bottom: 56.08108108108109%; position: relative; bottom: 0; left: 0; background-image: url('data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABQAAAALCAYAAAB/Ca1DAAAACXBIWXMAABJ0AAASdAHeZh94AAABkklEQVQoz6WSW0vrQBSF5/8/+gcOgh68Hg72qU2iSF+8lNpLptW0oGhuJpoU2yYmabPcOzpSQVRwwceeJHsWa89EnJ+fYWRZuCLubu/gez4816twGcf9Ftu2EQQhjg6PIbr9AW20EU0mCB9DeL6HKI4QxzFmsxmSJPmW2XwOoES304NotztwXBfL5RJSStRqNTS0BjS9DsPQoeuvGIZRoZ4VGqNpqBMbf9Yhbq5vEFO6IktxNg6x37JRlw/QLyM0hhH+tX1sn97i76mDzRMbWy0PexchEWCX2GkH2Gs52KZ3a7tNiPv7AIvFAmmaIs8LGjdGXiyglOU5bMdB+PBI3yZ4mk6RpM80ZoL0Oat6kiSt6uXQguBLyGkTn0VBlUcvy7I6E4bXClZZLqseBYsDsQZySAl9MizeDIviPdmqyVfiHmU8ZEP/E8OPicovYSnDgTmAcOmGsyzDnK6e6+o4P0UF6fdMCP7fVJLfajwaQzSPm+TcR+eig163B7MvCbNCmpLGkO91da16GN5vWSMc/D/AC6rBNmJ1kWOnAAAAAElFTkSuQmCC'); background-size: cover; display: block;\"\n    >\n      <img\n        class=\"gatsby-resp-image-image\"\n        style=\"width: 100%; height: 100%; margin: 0; vertical-align: middle; position: absolute; top: 0; left: 0; box-shadow: inset 0px 0px 0px 400px white;\"\n        alt=\"hash saved\"\n        title=\"\"\n        src=\"/tech-blog/static/850690ed04dcb5a7126644af2f288582/fcda8/hashsaved.png\"\n        srcset=\"/tech-blog/static/850690ed04dcb5a7126644af2f288582/12f09/hashsaved.png 148w,\n/tech-blog/static/850690ed04dcb5a7126644af2f288582/e4a3f/hashsaved.png 295w,\n/tech-blog/static/850690ed04dcb5a7126644af2f288582/fcda8/hashsaved.png 590w,\n/tech-blog/static/850690ed04dcb5a7126644af2f288582/efc66/hashsaved.png 885w,\n/tech-blog/static/850690ed04dcb5a7126644af2f288582/c83ae/hashsaved.png 1180w,\n/tech-blog/static/850690ed04dcb5a7126644af2f288582/2c118/hashsaved.png 1505w\"\n        sizes=\"(max-width: 590px) 100vw, 590px\"\n      />\n    </span>\n  </span>\n  \n  </a>\n    </p>\n<p>That looks awesome. Exactly what we wanted.</p>\n<p>There’s one problem. What if user logins with email bilal@gmail.com and password: 123456, how are we going to check ? we don’t have 123456 saved but instead, the hash.</p>\n<p>Lets see how we will modify our login method</p>\n<p>Here’s what we’re doing now</p>\n<div class=\"gatsby-highlight\" data-language=\"text\"><pre class=\"language-text\"><code class=\"language-text\">app.post('/login', async (req, res) => {\n  try {\n    const body = req.body;\n\n    const email = body.email;\n\n    // lets check if email exists\n\n    const result = await Users.findOne({ email: email });\n    if (!result) {\n      // this means result is null\n      res.status(401).send({\n        Error: 'This user doesnot exists. Please signup first'\n      });\n    } else {\n      // email did exist\n      // so lets match password\n\n      if (body.password === result.password) {\n        // great, allow this user access\n\n        console.log('match');\n\n        res.send({ message: 'Successfully Logged in' });\n      } else {\n        console.log('password doesnot match');\n\n        res.status(401).send({ message: 'Wrong email or Password' });\n      }\n    }\n  } catch (ex) {\n    console.log('ex', ex);\n  }\n});</code></pre></div>\n<p>Lets try it</p>\n<p>\n  <a\n    class=\"gatsby-resp-image-link\"\n    href=\"/tech-blog/static/34ae28dd35763168c1bf78ba850291c0/8d68c/testlogin.png\"\n    style=\"display: block\"\n    target=\"_blank\"\n    rel=\"noopener\"\n  >\n  \n  <span\n    class=\"gatsby-resp-image-wrapper\"\n    style=\"position: relative; display: block;  max-width: 590px; margin-left: auto; margin-right: auto;\"\n  >\n    <span\n      class=\"gatsby-resp-image-background-image\"\n      style=\"padding-bottom: 64.86486486486486%; position: relative; bottom: 0; left: 0; background-image: url('data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABQAAAANCAYAAACpUE5eAAAACXBIWXMAABJ0AAASdAHeZh94AAACa0lEQVQ4y62TS09TURDH7/dxgWKMiSJLv4iCURNCNOEDIA81vArhrYiwcEVYGSWIQIi6oKUEJTGAFmihvFq470fv7c/poRUXxpUn+eV/Zs7Mycyce7XJjnamJiYZePmG/qFx4TUDwxP09L2go3uIWP8Y3bLvjo3QJXT2DAsjdIj2D44zNvCK511D9Iq2PetDm264xPvmWmJNt+lsuEnsUQ29j2t5+uAazXeqGGy8TvfDq7TWV9N2r5ond6toqbtMS/0VYo01jEpOq+wHm27Rfv8GWnb9LeSWCDNzRHsLFLOLovMU9+cJMgvi/wiy52gJjj/ByWc4XMJOzeBvvxPfB/FJzMEcx2vTaKntAwwXdDvkzPDIWyGGE2GKnTcLCtMWPLB8sAVd4l03YClVpG46YnIlwgtgJ5ND29rYwDTOMIRcPk/ucJ/TkyMs0xC/rtSyTGyFoTDF51lnfN83Gf1isLhhENg6uz9/oGXSewSFAp5tYTsOtn6KJbiehyN2Qc6iKFIUi8UyJbsIREJFpetMBm1zYwtPkkuB50nnISXbsix1Vrmsoq7rKiLZB2EkBYUQ+mTTabTV5Kq0a6hgtcpVlJZt2yqxYl9UeBFTyVEVZrPS8s6uaiHwffwgEEIC0SAoqHbDMFT6J+fngYzFx3IL2PJAoYwgLePTNteSWKVHMU1VqSltlh7Dk+H/vkw0/Au+H+D4BVxRT0inZYbr39bJn5rkcwYneYeTnCs46GeOBIf/xC3jeHJpEJHJ7Mt3mErxv5au6/LrTU0TX46TiCdIKD0nGV9hVUiW+ZpIKrtCYjmh8uJlTa4kmZ2Z5RfNQagzTH1ImgAAAABJRU5ErkJggg=='); background-size: cover; display: block;\"\n    >\n      <img\n        class=\"gatsby-resp-image-image\"\n        style=\"width: 100%; height: 100%; margin: 0; vertical-align: middle; position: absolute; top: 0; left: 0; box-shadow: inset 0px 0px 0px 400px white;\"\n        alt=\"test login\"\n        title=\"\"\n        src=\"/tech-blog/static/34ae28dd35763168c1bf78ba850291c0/fcda8/testlogin.png\"\n        srcset=\"/tech-blog/static/34ae28dd35763168c1bf78ba850291c0/12f09/testlogin.png 148w,\n/tech-blog/static/34ae28dd35763168c1bf78ba850291c0/e4a3f/testlogin.png 295w,\n/tech-blog/static/34ae28dd35763168c1bf78ba850291c0/fcda8/testlogin.png 590w,\n/tech-blog/static/34ae28dd35763168c1bf78ba850291c0/efc66/testlogin.png 885w,\n/tech-blog/static/34ae28dd35763168c1bf78ba850291c0/c83ae/testlogin.png 1180w,\n/tech-blog/static/34ae28dd35763168c1bf78ba850291c0/8d68c/testlogin.png 1234w\"\n        sizes=\"(max-width: 590px) 100vw, 590px\"\n      />\n    </span>\n  </span>\n  \n  </a>\n    </p>\n<p>It’s saying wrong email/password even though its right :/</p>\n<p>we make just 1 line change in our code. we compare it using bcrypt</p>\n<div class=\"gatsby-highlight\" data-language=\"text\"><pre class=\"language-text\"><code class=\"language-text\"> if ( bcrypt.compareSync(body.password, result.password))</code></pre></div>\n<p>Now using wrong login</p>\n<p>\n  <a\n    class=\"gatsby-resp-image-link\"\n    href=\"/tech-blog/static/15333006e02ce66e47749daadebf3d75/8698d/wronglogin.png\"\n    style=\"display: block\"\n    target=\"_blank\"\n    rel=\"noopener\"\n  >\n  \n  <span\n    class=\"gatsby-resp-image-wrapper\"\n    style=\"position: relative; display: block;  max-width: 590px; margin-left: auto; margin-right: auto;\"\n  >\n    <span\n      class=\"gatsby-resp-image-background-image\"\n      style=\"padding-bottom: 64.86486486486486%; position: relative; bottom: 0; left: 0; background-image: url('data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABQAAAANCAYAAACpUE5eAAAACXBIWXMAABJ0AAASdAHeZh94AAACZUlEQVQ4y62R20sWYRCH99/pKouoi6xu+zOiDKITRdBlqFDQRWpqpWmmaQVdGoFpecjM7/OQJtIRIdQ083PXPR+/fZp3XS1vumrhYd555zezM+9oLddr6X3yhNaHz2hp6xZ6aG1/TPO9Thqa2mlu6aLpbieNdzoybjc/yGgQWu5309n6iLrGLV296LWu03sYqK2k/upxbp4/TN2lI9RfPsaNMwe5dmIvjRcOcevsAWqq9lMrVJ/cK1RQfWofdRcraZWcmqoKmq4clfxKtM9jT6E0QrL4knhpgHTlNclSP+XlAcLFV8SL/bAsrA7Bz2FYG5HzIM7CC4KF53LXB+tK04f9tRdtbu4bTgimm2DaIbpTxvJSbC9Bt+MM2xUCcKMtLB88P2bse8q55yk9M2XcIOWXEaDNTE3j2CaWabCh62ysraCvr2HbFrZlSszKcB0bx7EyVMx3DD79sGkbtxn6Ir5tUFpbRfs4/5GkXMZ3HVzPw7U2cQydIAjwxI/jmLLEFWma5ig/Bco5aYZlGGjTU+8Jo3AnSelUWLKkGwff93eKbVt15/ueaFOiRIgTiHxMaUQbHRmVEWySJIG8kEpSn+u6WZd/OttNnpCDPJElI8/NZ04YhtJpJMREuVXjqh8p+zcqHoneD0JsWY4XRFmXur4pI799k72bJV1asgRbxtx6dDMvIAWT3SQ5QRjhhcpKUT+Qpcobjr8rYJgOGyWLku5R2gjE+mxuepn4X/g56uwGMYZhos3OfuB/fWppWldHF4XxAsVCkeJ4ccdOFiaYLkxmVjFTnGRK7DZKU9ihwITcDQ+O8BsG96aasQL6IQAAAABJRU5ErkJggg=='); background-size: cover; display: block;\"\n    >\n      <img\n        class=\"gatsby-resp-image-image\"\n        style=\"width: 100%; height: 100%; margin: 0; vertical-align: middle; position: absolute; top: 0; left: 0; box-shadow: inset 0px 0px 0px 400px white;\"\n        alt=\"wrong login\"\n        title=\"\"\n        src=\"/tech-blog/static/15333006e02ce66e47749daadebf3d75/fcda8/wronglogin.png\"\n        srcset=\"/tech-blog/static/15333006e02ce66e47749daadebf3d75/12f09/wronglogin.png 148w,\n/tech-blog/static/15333006e02ce66e47749daadebf3d75/e4a3f/wronglogin.png 295w,\n/tech-blog/static/15333006e02ce66e47749daadebf3d75/fcda8/wronglogin.png 590w,\n/tech-blog/static/15333006e02ce66e47749daadebf3d75/efc66/wronglogin.png 885w,\n/tech-blog/static/15333006e02ce66e47749daadebf3d75/c83ae/wronglogin.png 1180w,\n/tech-blog/static/15333006e02ce66e47749daadebf3d75/8698d/wronglogin.png 1239w\"\n        sizes=\"(max-width: 590px) 100vw, 590px\"\n      />\n    </span>\n  </span>\n  \n  </a>\n    </p>\n<p>Now using correct login</p>\n<p>\n  <a\n    class=\"gatsby-resp-image-link\"\n    href=\"/tech-blog/static/46b9564ee3193f360acc1e163c1a630e/5148a/correctlogin.png\"\n    style=\"display: block\"\n    target=\"_blank\"\n    rel=\"noopener\"\n  >\n  \n  <span\n    class=\"gatsby-resp-image-wrapper\"\n    style=\"position: relative; display: block;  max-width: 590px; margin-left: auto; margin-right: auto;\"\n  >\n    <span\n      class=\"gatsby-resp-image-background-image\"\n      style=\"padding-bottom: 64.86486486486486%; position: relative; bottom: 0; left: 0; background-image: url('data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABQAAAANCAYAAACpUE5eAAAACXBIWXMAABJ0AAASdAHeZh94AAACb0lEQVQ4y62RS08TYRSG5/+4QDRGo6gr/wmI0cQbie4RUVFulqsIEhYmJMYdl0SjoHhZ2BZIDARbroK1tKWdmc6tM30887VFFyZu/JIn7znfnO/NOWe0yZ4OJscnGBh5TmRgjMjgOH1D43T1PqGja5DuyFM6Je7sGRKGedg9dEhf/xijfaPcfzRAb/8zWtu60KZbjjDVep7eWxfounaGxzcbiLSc48HlE9xprGPoxkl6rhynvfkY94S2pjruNh3l7sV6ItcbGLl6mvZL9QzfPktb8ym0g+RryCzg776l/GOecuo95b05FXu78+oeiUl/kLqPwif4uUBx4xXu5qzkbyArNek5dqMv0PZSefLFAL3ok9cdcqaPboV5iZzhcSAYEhs2mC4UhYIFlu0xvx7Q+DJgIurj+fAtuYf2fWcbvXCArufJ5nJkU7scZNKYho5hFJSapkFRoSsMubPNPKt7BqOfDd6tFfBtncTqClpmP4PreTiWSdGyMMW8WMjjOA6W5KVSiSAIFOVyuYrkohAINYWt9XW0nZ0dbMdWhepRtSTMTdPEdd1Ds5palo1t28rU8wPckswbeGwmk2grK6sU9IIqVqfaRXhCw7DTWv67wyrUnlTebm9uycjpfTGTpcrYrit4ldjzSmpc3/eV/knlu6diy3YVgbgnkxsy8toKhuzNkG50XVca/gxHll8zC/VvhN8cacJ2wkZKJBKyw0QiKX9XJ5c1RC0yWZv9jIWhy55cH+sfqBpHjEvlSoepVIr/ddLpNNrM9AzRaIx4LE5caYUlyZdji0qXRL/GF5UuV4lH48SkXvElxvLSMjNTs/wCGAeo1Q5Bb2UAAAAASUVORK5CYII='); background-size: cover; display: block;\"\n    >\n      <img\n        class=\"gatsby-resp-image-image\"\n        style=\"width: 100%; height: 100%; margin: 0; vertical-align: middle; position: absolute; top: 0; left: 0; box-shadow: inset 0px 0px 0px 400px white;\"\n        alt=\"correct login\"\n        title=\"\"\n        src=\"/tech-blog/static/46b9564ee3193f360acc1e163c1a630e/fcda8/correctlogin.png\"\n        srcset=\"/tech-blog/static/46b9564ee3193f360acc1e163c1a630e/12f09/correctlogin.png 148w,\n/tech-blog/static/46b9564ee3193f360acc1e163c1a630e/e4a3f/correctlogin.png 295w,\n/tech-blog/static/46b9564ee3193f360acc1e163c1a630e/fcda8/correctlogin.png 590w,\n/tech-blog/static/46b9564ee3193f360acc1e163c1a630e/efc66/correctlogin.png 885w,\n/tech-blog/static/46b9564ee3193f360acc1e163c1a630e/c83ae/correctlogin.png 1180w,\n/tech-blog/static/46b9564ee3193f360acc1e163c1a630e/5148a/correctlogin.png 1228w\"\n        sizes=\"(max-width: 590px) 100vw, 590px\"\n      />\n    </span>\n  </span>\n  \n  </a>\n    </p>\n<p>Hurray !!!</p>\n<p>Here is the complete code</p>\n<div class=\"gatsby-highlight\" data-language=\"text\"><pre class=\"language-text\"><code class=\"language-text\">app.post('/login', async (req, res) => {\n  try {\n    const body = req.body;\n\n    const email = body.email;\n\n    // lets check if email exists\n\n    const result = await Users.findOne({ email: email });\n    if (!result) {\n      // this means result is null\n      res.status(401).send({\n        Error: 'This user doesnot exists. Please signup first'\n      });\n    } else {\n      // email did exist\n      // so lets match password\n\n      if ( bcrypt.compareSync(body.password, result.password)) {\n        // great, allow this user access\n\n        console.log('match');\n\n        res.send({ message: 'Successfully Logged in' });\n      } else {\n        console.log('password doesnot match');\n\n        res.status(401).send({ message: 'Wrong email or Password' });\n      }\n    }\n  } catch (ex) {\n    console.log('ex', ex);\n  }\n});</code></pre></div>\n<p>we learned how to use password hashing. We allowed user to sign in. There’s still one more thing we need to do. Once a user logs in, we need to provide it a <code class=\"language-text\">token</code>. That <code class=\"language-text\">token</code> will tell us which user it is. With that token, that user can make changes to our database but without that token, a user cannot make any changes to our database or access our secure apis. <code class=\"language-text\">Token</code> kindof works as a guards for us. remember Route Guards? the concept is very similar.</p>\n<p>We will use JWT Tokens.</p>\n<p>What we will do is whenever a user successfully logins, we will create a JWT token and send it back in response. This means whenever an Angular / Web App / Mobile app user successfully logins, he will get back a token in return. We will then save that token. For now, lets just see how to create it.</p>\n<p>What happens in real world apps is that every protected request send via HTTP includes some sort of token. that token tells the server / us where the request came from, who is the user etc. Lets see how we incorporate that.</p>\n<p>First, we need to add a JWT module for Express.</p>\n<div class=\"gatsby-highlight\" data-language=\"text\"><pre class=\"language-text\"><code class=\"language-text\">npm install jsonwebtoken\n\nor\n\nyarn add jsonwebtoken</code></pre></div>\n<p>include jsonwebtoken at the top</p>\n<div class=\"gatsby-highlight\" data-language=\"text\"><pre class=\"language-text\"><code class=\"language-text\">const jsonwebtoken = require('jsonwebtoken');</code></pre></div>\n<p>Now lets create a JWT Token</p>\n<p>Lets update the /Login method</p>\n<div class=\"gatsby-highlight\" data-language=\"text\"><pre class=\"language-text\"><code class=\"language-text\">if ( bcrypt.compareSync(body.password, result.password)) {\n        // great, allow this user access\n\n        console.log('match');\n\n        const token = jsonwebtoken.sign({\n           data: body,\n           role: 'User'\n        }, 'supersecretToken', { expiresIn: '7d' });\n\n        console.log('token -> ', token)\n\n        res.send({ message: 'Successfully Logged in', token: token });\n      }</code></pre></div>\n<p>what we’re doing here is using the <code class=\"language-text\">jsonwebtoken</code> module to sign some data. Note with body, we also send role. Here, we can handle multiple roles e.g admin, teacher etc. We manage rules using tokens as well.</p>\n<p>Lets try to login using postman and see if we get the token in console.</p>\n<p>\n  <a\n    class=\"gatsby-resp-image-link\"\n    href=\"/tech-blog/static/4778933bba679d633d1f7d8770dd2085/0d0e4/correctloginwithtoken.png\"\n    style=\"display: block\"\n    target=\"_blank\"\n    rel=\"noopener\"\n  >\n  \n  <span\n    class=\"gatsby-resp-image-wrapper\"\n    style=\"position: relative; display: block;  max-width: 590px; margin-left: auto; margin-right: auto;\"\n  >\n    <span\n      class=\"gatsby-resp-image-background-image\"\n      style=\"padding-bottom: 70.94594594594594%; position: relative; bottom: 0; left: 0; background-image: url('data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABQAAAAOCAYAAAAvxDzwAAAACXBIWXMAABJ0AAASdAHeZh94AAACo0lEQVQ4y32SSU8UQRTH+wOZKMbEGOHk1/DsgjFRMCaePeBAlGWAsIniwoF40cTEm8bEIAE1LEGcrWeGGZaGZqZ6rd7q76uaxjQXK/nlvXr1ann/V9q7sRzeLy5i+uUSJqcXMDnzGlPP32J0ch5PR6fJvsDI+ByG87OKZ2Mz/5hQ+a8wNDyF8akFDAzmoX3oO4dPj3uQf3gNI/euYuJBN8b7uzF05xIGbpzHbP9l5O9eQu72RQwSMvbk5gXkbnUh39eN0fuU29uFuUc9yPVegWaWvwDsB2AsA8crgLkKHK0oXxgrafw70KYc9hOwfgGtNfDGVyRN2tv+RnHKMZdhbH2EVqsbaNkR2naIk7aLYxaAORGYHcBkHKbFlc+8BLYvFG03gedxfC7FuL4UYX41BA8TVPQDOlDX4dgMtsVgnrRwYuyjdXwEx7EpbsElK/FcB65rd3AccJehsO/gzZqN5bKNyLehFwvQDg8OEYYhAs+lW314Vhs+EQQBzT3EcQwhxBkSisVJAkCkSB9o1mrQ9IoOznknkZISWpcI8h35ElqT8dN1aX3f78TJD+MEYRTTphC71Sq0zY1NMMZUshpCdKDhuq7aLNJ51p762XhztwHtYG9fHSZLDAIqPYwQpjaKIlWytFmkRJIoCuH5nAgQUVnVap1K3t6AzVqwSHiLGmOT+DY1ibsWXUSHSb3+A6fLefqASoVKLpXK1EEqzZJdDejwEKwVgDsBbRAZ4TOI7Fyajly7dXrh+vqGevZeLcSfLaC0AxS2gSLZSpHKKAvUdYFahWxVkE4CR4aAcZgifSOBaQLlUhNasVBUX4BeTA0A6QjSENTFju97Z5FxqhSysXEKyapGo7EHbef3jupkEHASmiubRcbOIOM8A80595Xe8gv+BZLF/0svt24AAAAAAElFTkSuQmCC'); background-size: cover; display: block;\"\n    >\n      <img\n        class=\"gatsby-resp-image-image\"\n        style=\"width: 100%; height: 100%; margin: 0; vertical-align: middle; position: absolute; top: 0; left: 0; box-shadow: inset 0px 0px 0px 400px white;\"\n        alt=\"correct login with token\"\n        title=\"\"\n        src=\"/tech-blog/static/4778933bba679d633d1f7d8770dd2085/fcda8/correctloginwithtoken.png\"\n        srcset=\"/tech-blog/static/4778933bba679d633d1f7d8770dd2085/12f09/correctloginwithtoken.png 148w,\n/tech-blog/static/4778933bba679d633d1f7d8770dd2085/e4a3f/correctloginwithtoken.png 295w,\n/tech-blog/static/4778933bba679d633d1f7d8770dd2085/fcda8/correctloginwithtoken.png 590w,\n/tech-blog/static/4778933bba679d633d1f7d8770dd2085/efc66/correctloginwithtoken.png 885w,\n/tech-blog/static/4778933bba679d633d1f7d8770dd2085/c83ae/correctloginwithtoken.png 1180w,\n/tech-blog/static/4778933bba679d633d1f7d8770dd2085/0d0e4/correctloginwithtoken.png 1230w\"\n        sizes=\"(max-width: 590px) 100vw, 590px\"\n      />\n    </span>\n  </span>\n  \n  </a>\n    </p>\n<p>You can see the token in the response.</p>\n<p>eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJkYXRhIjp7Il9pZCI6IjVkZTIxODhhY2U2Y2ZiMDQwYzMwM2I4ZCIsIm5hbWUiOiJCaWxhbCIsImVtYWlsIjoiYmlsYWxAZ21haWwuY29tIiwicGFzc3dvcmQiOiIkMmEkMTAkdWdtSHAwcFhYSTR1S2ZNVk45cm1PT1FPaENLWENPYS8xS0g0bnJ4VGtWekVRU2syM0pqRmUiLCJfX3YiOjB9LCJyb2xlIjoiVXNlciIsImlhdCI6MTU3NTEwMzg4MSwiZXhwIjoxNTc1NzA4NjgxfQ.C2C3iiiDl8N3SH8utZYbUwrqChH0NfyxzPbdUZQCyco</p>\n<p>Let open <a href=\"jwt.io\">jwt.io</a></p>\n<p>Lets copy and paste the token on the left hand side.</p>\n<p>\n  <a\n    class=\"gatsby-resp-image-link\"\n    href=\"/tech-blog/static/1cba1f1987fa6da632ef49ff6a9149f3/332b4/jwtio.png\"\n    style=\"display: block\"\n    target=\"_blank\"\n    rel=\"noopener\"\n  >\n  \n  <span\n    class=\"gatsby-resp-image-wrapper\"\n    style=\"position: relative; display: block;  max-width: 590px; margin-left: auto; margin-right: auto;\"\n  >\n    <span\n      class=\"gatsby-resp-image-background-image\"\n      style=\"padding-bottom: 50.67567567567568%; position: relative; bottom: 0; left: 0; background-image: url('data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABQAAAAKCAYAAAC0VX7mAAAACXBIWXMAABJ0AAASdAHeZh94AAABY0lEQVQoz4VRy1LCQBDMP3GBUIFgKk8LPeAJrfLkZ2shyJECFfLaR9u7SVREdCpdvTuPntmJk6YpgiDA/O4Bt/N7zG5mCMMQURQhSVJkWUZcIrWcWY7jhDkRwskEMeuvp1PLSZLAcV0Xg8EAaTpDnF2xKEWfd3c4hDcaYeyP4fs++v0+er0ehvS7Jt7mTBhLggt4nmd1HHyagq4q/GVKa/xnjpQSUhF7CbGuUK0LlKu8wfKA4qWCyBWErCH2Oeq8gBACtu4XOE1TzWSNfAEUzw3KNXlFJlSp2ZQiFEQtYUo0C3/CTtgJyneN8omijw2KJbHgmT5VgBMK1JVgpilWUOoYJ4JVobF5U9geyHuFXa55bu5C6rYpB9zwvgNkbqZs9mb4S7D1CEXRM0s3UymK1lvmvRJ8jWRDuwrDon0yPwftPrp2p7tpfEZQHmDxa9NuwiORdtrvQl3c7qoyooxJffanfABtVL8W0i5xvgAAAABJRU5ErkJggg=='); background-size: cover; display: block;\"\n    >\n      <img\n        class=\"gatsby-resp-image-image\"\n        style=\"width: 100%; height: 100%; margin: 0; vertical-align: middle; position: absolute; top: 0; left: 0; box-shadow: inset 0px 0px 0px 400px white;\"\n        alt=\"jwt io\"\n        title=\"\"\n        src=\"/tech-blog/static/1cba1f1987fa6da632ef49ff6a9149f3/fcda8/jwtio.png\"\n        srcset=\"/tech-blog/static/1cba1f1987fa6da632ef49ff6a9149f3/12f09/jwtio.png 148w,\n/tech-blog/static/1cba1f1987fa6da632ef49ff6a9149f3/e4a3f/jwtio.png 295w,\n/tech-blog/static/1cba1f1987fa6da632ef49ff6a9149f3/fcda8/jwtio.png 590w,\n/tech-blog/static/1cba1f1987fa6da632ef49ff6a9149f3/efc66/jwtio.png 885w,\n/tech-blog/static/1cba1f1987fa6da632ef49ff6a9149f3/c83ae/jwtio.png 1180w,\n/tech-blog/static/1cba1f1987fa6da632ef49ff6a9149f3/332b4/jwtio.png 1826w\"\n        sizes=\"(max-width: 590px) 100vw, 590px\"\n      />\n    </span>\n  </span>\n  \n  </a>\n    </p>\n<p>When we decode it, we can see the data for e.g User Email, ID, Role etc. We also see password which should not be in that token. so we can remove it by</p>\n<div class=\"gatsby-highlight\" data-language=\"text\"><pre class=\"language-text\"><code class=\"language-text\">  delete result['password'];\n\n        const token = jsonwebtoken.sign({\n           data: result,\n           role: 'User'\n        }, 'supersecretToken', { expiresIn: '7d' });</code></pre></div>\n<p>if delete doesn’t work</p>\n<p>then just do</p>\n<div class=\"gatsby-highlight\" data-language=\"text\"><pre class=\"language-text\"><code class=\"language-text\"> result.password = undefined;</code></pre></div>\n<p>now the JWT token won’t have password. Btw, the token will expire after 7 days. the secret key with which we can <strong><em>validate</em></strong> the token is <code class=\"language-text\">supersecretToken</code>. Right now, we wrote this in code which is a bad practice. We will fix this in the next tutorial.</p>\n<p>So in this, we improved our Login/Register methods with better practices such as password hashing and usage of JWT Tokens.</p>\n<p>Here is the look at the final code <a href=\"https://github.com/alamgirqazi/simplest-nodejs-auth/tree/part3\">Link to code of part 3</a></p>\n<p>There are still some things we can improve in this workflow. First of all, one index.js with all the code is not a good approach at all. We need to split things up. 2. we wrote secret information such as database name, JWT token secret key inside code which is a BAD practice. we never write it in code. we define them in environment variables. In the next post, we will cover that.</p>","frontmatter":{"title":"A very basic introduction to Node.js - Part 3","date":"November 30, 2019"}}},"pageContext":{"slug":"/intro-to-nodejs-part-3/","previous":{"fields":{"slug":"/intro-to-nodejs-part-2/"},"frontmatter":{"title":"A very basic introduction to Node.js - Part 2"}},"next":{"fields":{"slug":"/intro-to-nodejs-part-4/"},"frontmatter":{"title":"A very basic introduction to Node.js - Part 4"}}}},"staticQueryHashes":[]}