<?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 Abhinav Sharma on Medium]]></title>
        <description><![CDATA[Stories by Abhinav Sharma on Medium]]></description>
        <link>https://medium.com/@abhi.sharm.414?source=rss-263cdfb77c8e------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*0ZZ5BKxl9Kw1h6DX.jpg</url>
            <title>Stories by Abhinav Sharma on Medium</title>
            <link>https://medium.com/@abhi.sharm.414?source=rss-263cdfb77c8e------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 03 Dec 2026 09:13:59 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@abhi.sharm.414/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[Deploy your Node.js/Express and React App to Heroku]]></title>
            <link>https://medium.com/@abhi.sharm.414/deploy-your-node-js-express-and-react-app-to-heroku-c89322fb1169?source=rss-263cdfb77c8e------2</link>
            <guid isPermaLink="false">https://medium.com/p/c89322fb1169</guid>
            <dc:creator><![CDATA[Abhinav Sharma]]></dc:creator>
            <pubDate>Sun, 18 Oct 2020 17:07:50 GMT</pubDate>
            <atom:updated>2020-10-18T17:07:50.880Z</atom:updated>
            <content:encoded><![CDATA[<p>I am starting this article with the assumption that your application is already built and runs locally without problems. Also you must make sure that git is initialized for your project. Make sure you have installed the Heroku CLI, and have registered for a Heroku account on the website. If you are ready to deploy, there are two ways go about it using a React frontend. If you used create-react-app to build your frontend, then you know that React runs on it’s own server. This makes it possible to separate your frontend and backend into two separate deployments. However, React can also be served as static pages by your server. In this article, I will show you the latter method of doing so.</p><p>My app is structured such that my Node.js app contains a subdirectory called client which contains my React app. In the Node.js server’s package.json file make sure the following scripts exist (you will probably have others, but I’m showing only those necessary for deployment).</p><pre>&quot;scripts&quot;: {<br>  &quot;start&quot;: &quot;node server.js&quot;,<br>  &quot;heroku-postbuild&quot;: &quot;NPM_CONFIG_PRODUCTION=false &amp;&amp; npm install --prefix client &amp;&amp; npm run build --prefix client&quot;<br>}</pre><p>The heroku-postbuild script will run when we push our code to Heroku. It will install the npm packages for our client(as well as devDependencies), and then build our React app into static pages. In your server file make sure any of your secrets, API keys, and DB URIs are protected. Simply install the dotenv package as a devDependency and put this at the top of your server.js file.</p><pre>const config = require(&#39;dotenv&#39;).config()</pre><p>Now you can access the process object variable locally while testing. Make a file called .env in the root directory of your project, and put all the relevant info in it (example below).</p><pre>prodMongoURI=&#39;mongodb+srv://test:<a href="/service/mailto:test@cluster0-go8ql.mongodb.net">test@cluster0-gc9bl.mongodb.net</a>/prod?retryWrites=true&amp;w=majority&#39;<br>devMongoURI=&#39;mongodb+srv://test:<a href="/service/mailto:test@cluster0-go8ql.mongodb.net">test@cluster0-gc9dl.mongodb.net</a>/test?retryWrites=true&amp;w=majority&#39;<br>SECRET=&#39;secretkey&#39;<br>GMAIL_USER_NAME = test<a href="/service/mailto:itilapplication@gmail.com">@gmail.com</a><br>GMAIL_USER_PASSWORD = password</pre><p>Then in all relevant parts of your app, make changes accordingly so that your app relies on environment variables, not hardcoded information. I’m showing some examples below of how to use the environment variables. These will also have to be configured on your Heroku app, but you will not have to change any code as Heroku uses the process object too.</p><pre>if (process.env.NODE_ENV === &#39;production&#39;) {<br>  db = process.env.prodMongoURI;<br>} else {<br>  db = process.env.devMongoURI;<br>}<br>const port = process.env.PORT || 5000;<br>const key = process.env.SECRET;</pre><pre>.<br>.<br>.<br>.</pre><pre>let transporter = nodeMailer.createTransport({<br>  host: &#39;smtp.gmail.com&#39;,<br>  port: 465,<br>  secure: true,<br>  auth: {<br>    user: process.env.GMAIL_USER_NAME,<br>    pass: process.env.GMAIL_USER_PASSWORD<br>  }<br>});</pre><pre>let mailOptions = {<br>  to: req.body.email,<br>  subject: &quot;Activation email for TestApp&quot;,<br>  html: `&lt;p&gt;Hi! Please click the following link to activate your TestApp account&lt;/p&gt; &lt;a href=&#39;https://testapp.herokuapp.com/verify/${newUser._id}&#39;&gt;Activation Link&lt;/a&gt;`<br>};</pre><pre>transporter.sendMail(mailOptions, (error, info) =&gt; {<br>  if (error) {<br>    console.log(error);<br>  }<br>});</pre><p>Lastly, we need to configure our server to serve our static React app. To do this, in our main server file, add the following code after any api routes that exist for your app.</p><pre>if(process.env.NODE_ENV === &#39;production&#39;) {<br>  // set static folder<br>  app.use(express.static(&#39;client/build&#39;));<br>  app.get(&#39;*&#39;, (req, res) =&gt; {<br>    res.sendFile(path.resolve(__dirname, &#39;client&#39;, &#39;build&#39;, &#39;index.html&#39;));<br>  });<br>}</pre><p>You can use the CLI to create your Heroku deployment, but I prefer to just go to the website.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/508/1*0BhMZbnlQTx79EN4pFk9dA.png" /></figure><p>Go to your Heroku dashboard and click <strong>New </strong>and <strong>Create new app</strong>. Give it a name, select your region, and click <strong>Create app</strong>. Now go back to your dashboard and click on your newly created app and in the Settings tab, make sure to add the heroku/node.js build pack in the Buildpacks section.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CkRF9Cd5PjYSTevf3uK3jQ.png" /></figure><p>In the Config Vars section, add all of your necessary secrets, API keys, and other sensitive information in a key-value pair format. Make sure that they keys are named exactly how you named them in your .env file locally.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9M3U6gYOM95gZFX9Zjte9g.png" /></figure><p>Now we should be ready to deploy. First run the following command to login to Heroku.</p><pre>$ heroku login -i</pre><p>This will prompt you for your Heroku email and password. Open a terminal and navigate to the root directory of your project. To link this git repository to the repository for your Heroku app, use the following command (where ‘name-of-your-app’ is your Heroku app’s exact name).</p><pre>$ heroku git:remote -a name-of-your-app</pre><p>This added the Heroku app’s git repository as a remote origin for our local git repo. To push our code up run the following set of commands.</p><pre>$ git add .<br>$ git commit -am &quot;make it better&quot;<br>$ git push heroku master</pre><p>A lot of things will happen in the terminal, which is basically a log of your app being deployed. Cross your fingers! I have given an example terminal out of the command (not my app’s output below).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/617/1*2Jpqfe6VDmYAheZs7sW91w.png" /></figure><p>Once the git push command finishes running, you should be able to visit the website at the indicated URL (.com not .git) at the end of the output.</p><p>There we have it! That is how you deploy a Node.js/Express and React app to Heroku without having to separate them into separate servers. The Node.js app will serve the React app as static files to any requests that aren’t API routes.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c89322fb1169" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Live Whiteboard with Django, React, and WebSockets]]></title>
            <link>https://medium.com/@abhi.sharm.414/live-whiteboard-with-django-react-and-websockets-7cae864ed6c5?source=rss-263cdfb77c8e------2</link>
            <guid isPermaLink="false">https://medium.com/p/7cae864ed6c5</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[websocket]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[django]]></category>
            <category><![CDATA[whiteboards]]></category>
            <dc:creator><![CDATA[Abhinav Sharma]]></dc:creator>
            <pubDate>Sun, 11 Oct 2020 19:36:04 GMT</pubDate>
            <atom:updated>2020-10-11T19:36:18.171Z</atom:updated>
            <content:encoded><![CDATA[<p>Recently, I’ve been learning web development using Python, and wanted to implement real-time client-to-client interactions on an app. I thought a basic live whiteboard would be a good example of this. To do this, either long-polling or WebSockets would have to be implemented. For the purposes of this example, I went with WebSockets.</p><p>To start, we start by making sure Python is installed on our system, and you can do so using Homebrew. We also will need to use Redis to cache WebSocket data being sent to the server. This can also be installed with Homebrew.</p><pre>brew install redis<br>brew services start redis</pre><p>I am using Python3, but this should work with any version that has pip included. Once it is installed, we will use pip to install a package called pipenv.</p><pre>pip install pipenv</pre><p>Once pipenv is installed, create a directory where you want to make your project. In a terminal window, cd to that directory and create a virtual environment by typing:</p><pre>pipenv shell</pre><p>This will create a location where we can install all of our project dependencies without installing them globally, where the Pipfile will keep track of them. Now let’s install Django and Channels (package that will allow us to use WebSockets) in our virtual environment.</p><pre>pipenv install django channels</pre><p>Now we create a Django project, which will create all the folders and files for our web application.</p><pre>django-admin startproject whiteboardmanager</pre><p>In Django, projects and apps are separate, and our project will serve our ‘apps’. We will need one app for our backend server logic and one for our frontend.</p><pre>python manage.py startapp whiteboard<br>python manage.py startapp frontend</pre><p>Lets go to our settings.py file in our whiteboardmanager folder and add these apps and channels to our installed apps. We will also add a line to create routing for our WebSockets.</p><pre>INSTALLED_APPS = [<br>&#39;django.contrib.admin&#39;,<br>&#39;django.contrib.auth&#39;,<br>&#39;django.contrib.contenttypes&#39;,<br>&#39;django.contrib.sessions&#39;,<br>&#39;django.contrib.messages&#39;,<br>&#39;django.contrib.staticfiles&#39;,<br>&#39;whiteboard&#39;,<br>&#39;frontend&#39;,<br>&#39;channels&#39;<br>]</pre><pre>ASGI_APPLICATION = &quot;whiteboardmanager.routing.application&quot;</pre><pre>CHANNEL_LAYERS = {<br>  &quot;default&quot;: {<br>    &quot;BACKEND&quot;: &quot;channels_redis.core.RedisChannelLayer&quot;,<br>    &quot;CONFIG&quot;: {<br>      &quot;hosts&quot;: [(&quot;127.0.0.1&quot;, 6379)],<br>    },<br>  },<br>}</pre><p>Let’s go into our urls.py file in our whiteboardmanager folder and set it as the following. I went ahead and removed the url patterns for the admin path because we will not be using the admin console.</p><pre>from django.contrib import admin<br>from django.urls import path, include<br></pre><pre>urlpatterns = [<br>  path(&#39;&#39;, include(&#39;frontend.urls&#39;)),<br>]</pre><p>In the whiteboard app folder, we need to make a Consumer with Channels which will make constructing our ASGI application easily. Make a file called consumers.py and add the following code.</p><pre>import asyncio<br>import json<br>from channels.consumer import AsyncConsumer</pre><pre>class BoardConsumer(AsyncConsumer):<br>  async def websocket_connect(self, event):<br>    print(&#39;connected&#39;, event)<br>    board_room = &quot;boardroom&quot;<br>    self.board_room = board_room<br>    await self.channel_layer.group_add(<br>      board_room,<br>      self.channel_name<br>    )<br>    await self.send({<br>      &quot;type&quot;: &quot;websocket.accept&quot;<br>    })</pre><pre>  async def websocket_receive(self, event):<br>    drawing_data = event.get(&#39;text&#39;, None)<br>    await self.channel_layer.group_send(<br>      self.board_room,<br>      {<br>        &quot;type&quot;: &quot;board_message&quot;,<br>        &quot;text&quot;: drawing_data<br>      })</pre><pre>  async def board_message(self, event):<br>    await self.send({<br>      &quot;type&quot;: &#39;websocket.send&#39;,<br>      &#39;text&#39;: event[&#39;text&#39;]<br>    })</pre><pre>  async def websocket_disconnect(self, event):<br>    print(&#39;disconnected&#39;, event)</pre><p>This code creates a class which will contain our WebSocket methods, that will be called when when our frontend connects. To finish configuring our backend, we will create a routing file called routing.py in our whiteboardmanager folder.</p><pre>from channels.routing import ProtocolTypeRouter, URLRouter<br>from django.conf.urls import url<br>from channels.security.websocket import AllowedHostsOriginValidator<br>from whiteboard.consumers import BoardConsumer</pre><pre>application = ProtocolTypeRouter({<br>  &#39;websocket&#39;: AllowedHostsOriginValidator(<br>    URLRouter(<br>      [<br>        url(https://medium.com/&quot;&quot;,%20BoardConsumer)<br>      ]<br>    )<br>  )<br>})</pre><p>Now, lets begin work on our frontend. For the client, we will be using React. Start by going to the root folder of our project, and using the npm init -y command to create a package.json file. We will need to install several packages for React.</p><pre>npm i -D @babel/core @babel/preset-env @babel/preset-react babel-loader babel-plugin-transform-class-properties css-loader style-loader webpack webpack-cli</pre><pre>npm i react react-dom</pre><p>Go to the package.json file and make the following scripts:</p><pre>&quot;scripts&quot;: {<br>&quot;dev&quot;: &quot;webpack --mode development ./whiteboardmanager/frontend/src/index.js --output  ./whiteboardmanager/frontend/static/frontend/main.js&quot;,<br>&quot;build&quot;: &quot;webpack --mode production ./whiteboardmanager/frontend/src/index.js --output ./whiteboardmanager/frontend/static/frontend/main.js&quot;<br>}</pre><p>In the root folder of our project, we also need to make a .babelrc and webpack.config.js file.</p><p>Contents of the .babelrc file:</p><pre>{<br>  &quot;presets&quot;: [&quot;@babel/preset-env&quot;, &quot;@babel/preset-react&quot;],<br>  &quot;plugins&quot;: [&quot;transform-class-properties&quot;]<br>}</pre><p>Contents of the webpack.config.js file:</p><pre>module.exports = {<br>  module: {<br>    rules: [<br>      {<br>        test: /\.css$/i,<br>        use: [&#39;style-loader&#39;, &#39;css-loader&#39;],<br>      },<br>      {<br>        test: /\.js$/,<br>        exclude: /node_modules/,<br>        use: {<br>          loader: &#39;babel-loader&#39;<br>        }<br>      }<br>    ]<br>  }<br>}</pre><p>In the frontend app folder make the following folder structure in addition to the existing files:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/222/1*bb9WogQ2SMvX5UB03Qh0tg.png" /><figcaption>We will actually not be using the App.js file in this implementation. You do not need to make the main.js file as it will be automatically created when we run the build script.</figcaption></figure><p>Contents of the index.html file:</p><pre>&lt;!DOCTYPE html&gt;<br>&lt;html lang=&#39;en&#39;&gt;<br>  &lt;head&gt;<br>    &lt;meta charset=&#39;UTF-8&#39;&gt;<br>    &lt;meta name=&#39;viewport&#39; content=&#39;width=device-width, initial-scale=1.0&#39;&gt;<br>    &lt;meta http-equiv=&#39;X-UA-Compatible&#39; content=&#39;ie=edge&#39;&gt;<br>    &lt;title&gt;Whiteboard&lt;/title&gt;<br>  &lt;/head&gt;<br>  &lt;body&gt;<br>    &lt;div id=&#39;app&#39;&gt;&lt;/div&gt;<br>    {% load static %}<br>    &lt;script src=&quot;{% static &quot;frontend/main.js&quot; %}&quot;&gt;&lt;/script&gt;<br>  &lt;/body&gt;<br>&lt;/html&gt;</pre><p>Contents of the index.js file:</p><pre>import React, { Component } from &#39;React&#39;;<br>import ReactDOM from &#39;react-dom&#39;;<br>import Board from &#39;./components/Board&#39;</pre><pre>ReactDOM.render(<br>  &lt;React.StrictMode&gt;<br>    &lt;Board /&gt;<br>  &lt;/React.StrictMode&gt;,<br>  document.getElementById(&#39;app&#39;));</pre><p>For the purposes of this article, I will not go into detail about the Board component’s drawing functionality. You can find guides online for making HTML canvases with event listeners that draw paths with mouse events. I will, however, show the code below, and talk about the WebSocket connection.</p><pre>import React, { useRef, useEffect } from &#39;react&#39;;<br>import &#39;./styles/board.css&#39;;</pre><pre>const Board = () =&gt; {</pre><pre>  const canvasRef = useRef(null);<br>  const colorsRef = useRef(null);<br>  const socketRef = useRef();</pre><pre>  useEffect(() =&gt; {<br>    const canvas = canvasRef.current;<br>    const test = colorsRef.current;<br>    const context = canvas.getContext(&#39;2d&#39;);<br>    let dataURL = &#39;&#39;;<br>    const colors = document.getElementsByClassName(&#39;color&#39;);<br>    const current = {<br>      color: &#39;black&#39;,<br>    };</pre><pre>    const onColorUpdate = (e) =&gt; {<br>      current.color = e.target.className.split(&#39; &#39;)[1];<br>    };</pre><pre>    for (let i = 0; i &lt; colors.length; i++) {<br>      colors[i].addEventListener(&#39;click&#39;, onColorUpdate, false);<br>    }<br>    <br>    let drawing = false;<br>    const drawLine = (x0, y0, x1, y1, color, send) =&gt; {<br>      context.beginPath();<br>      context.moveTo(x0, y0);<br>      context.lineTo(x1, y1);<br>      context.strokeStyle = color;<br>      context.lineWidth = 2;<br>      context.stroke();<br>      context.closePath();<br>      context.save();<br>      dataURL = canvasRef.current.toDataURL(&#39;image/png&#39;);<br>      if (!send) { return; }<br>      const w = canvas.width;<br>      const h = canvas.height;<br>      socketRef.current.send(JSON.stringify({<br>        x0: x0 / w,<br>        y0: y0 / h,<br>        x1: x1 / w,<br>        y1: y1 / h,<br>        color,<br>      }));<br>    };</pre><pre>    const onMouseDown = (e) =&gt; {<br>      drawing = true;<br>      current.x = e.clientX || e.touches[0].clientX;<br>      current.y = e.clientY || e.touches[0].clientY;<br>    };<br>    <br>    const onMouseMove = (e) =&gt; {<br>      if (!drawing) { return; }<br>      drawLine(current.x, current.y, e.clientX ||<br>      e.touches[0].clientX, e.clientY || e.touches[0].clientY, current.color, true);<br>      current.x = e.clientX || e.touches[0].clientX;<br>      current.y = e.clientY || e.touches[0].clientY;<br>    };<br>    <br>    const onMouseUp = (e) =&gt; {<br>      if (!drawing) { return; }<br>      drawing = false;<br>      drawLine(current.x, current.y, e.clientX || e.touches[0].clientX, e.clientY || e.touches[0].clientY,<br>current.color, true);<br>    };</pre><pre>    const throttle = (callback, delay) =&gt; {<br>      let previousCall = new Date().getTime();<br>      return function() {<br>        const time = new Date().getTime();<br>        if ((time - previousCall) &gt;= delay) {<br>          previousCall = time;<br>          callback.apply(null, arguments);<br>        }<br>      };<br>    };</pre><pre>    canvas.addEventListener(&#39;mousedown&#39;, onMouseDown, false);<br>    canvas.addEventListener(&#39;mouseup&#39;, onMouseUp, false);<br>    canvas.addEventListener(&#39;mouseout&#39;, onMouseUp, false);<br>    canvas.addEventListener(&#39;mousemove&#39;, throttle(onMouseMove, 10), false);<br>    canvas.addEventListener(&#39;touchstart&#39;, onMouseDown, false);<br>    canvas.addEventListener(&#39;touchend&#39;, onMouseUp, false);<br>    canvas.addEventListener(&#39;touchcancel&#39;, onMouseUp, false);<br>    canvas.addEventListener(&#39;touchmove&#39;, throttle(onMouseMove, 10), false);</pre><pre>    const onResize = () =&gt; {<br>      canvas.width = window.innerWidth;<br>      canvas.height = window.innerHeight;<br>      let img = document.createElement(&#39;img&#39;);<br>      img.src = dataURL;<br>      context.drawImage(img, 0,0);<br>      context.restore();<br>    };</pre><pre>    window.addEventListener(&#39;resize&#39;, onResize, false);<br>    onResize();</pre><pre>    const onDrawingEvent = (data) =&gt; {<br>      const w = canvas.width;<br>      const h = canvas.height;<br>      drawLine(data.x0 * w, data.y0 * h, data.x1 * w, data.y1 * h, data.color);<br>    }</pre><pre>    socketRef.current = new WebSocket(&#39;ws://&#39;+ window.location.host)<br>    socketRef.current.onopen = e =&gt; {<br>      console.log(&#39;open&#39;, e)<br>    }<br>    socketRef.current.onmessage = e =&gt; {<br>      onDrawingEvent(JSON.parse(e.data))<br>    }<br>    socketRef.current.onerror = e =&gt; {<br>      console.log(&#39;error&#39;, e)<br>    }<br>  }, []);</pre><pre>  return (<br>    &lt;div&gt;<br>      &lt;canvas ref={canvasRef} className=&quot;whiteboard&quot; /&gt;<br>      &lt;div ref={colorsRef} className=&quot;colors&quot;&gt;<br>        &lt;div className=&quot;color black&quot; /&gt;<br>        &lt;div className=&quot;color red&quot; /&gt;<br>        &lt;div className=&quot;color green&quot; /&gt;<br>        &lt;div className=&quot;color blue&quot; /&gt;<br>        &lt;div className=&quot;color yellow&quot; /&gt;<br>      &lt;/div&gt;<br>    &lt;/div&gt;<br>  );<br>};</pre><pre>export default Board;</pre><p>Here are the contents of the stylesheet.</p><pre>* {<br>  box-sizing: border-box;<br>  }</pre><pre>.whiteboard {<br>  height: 100%;<br>  width: 100%;<br>  position: absolute;<br>  left: 0;<br>  right: 0;<br>  bottom: 0;<br>  top: 0;<br>}</pre><pre>.colors {<br>  position: fixed;<br>}</pre><pre>.color {<br>  display: inline-block;<br>  height: 48px;<br>  width: 48px;<br>}</pre><pre>.color.black { background-color: black; }<br>.color.red { background-color: red; }<br>.color.green { background-color: green; }<br>.color.blue { background-color: blue; }<br>.color.yellow { background-color: yellow; }</pre><p>This code is still a work in progress, and will be part of a bigger overall application with a database. However, what we have here is sufficient to demonstrate the concept of WebSockets and a live whiteboard. To create the WebSocket connection, we use the WebSocket class to instantiate an object, passing in the host URL. However, we are not using HTTP, so the path must be started with a ‘ws://’ not ‘http://’. This creates a connection to our ASGI application. Once it is open, we can call the send method of our WebSocket when our drawLine function is called by our event listeners. This will draw the line to the HTML canvas and only send the data if it being drawn by the current browser. The canvas data is also being saved and re-rendered if the window is resized. This prevents the canvas from being cleared if a user resized the window. The ‘onmessage’ method gets called when, the WebSocket object receives data from our backend. This calls the onDrawingEvent function which will call drawLine to render drawings received from other connected browsers. Our Redis server will ensure that the drawing data is preserved to be sent to multiple connections.</p><p>To bring it all together, run npm run build in the root directory of the project. This will build our React project and create our main.js file. Now, in the whiteboardmanager directory, we can start our server using the following command.</p><pre>pipenv run python manage.py run server</pre><p>This will start up our application on port 8000. Open up two web browser windows and navigate to localhost:8000. Your server will indicate two websocket connections have been opened. To draw, select a color, then click, hold, and drag to write on the whiteboard. Watch as the drawings appear on both browser windows. Feel free to resize, and notice how the drawing does not disappear.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7gHfTJskWQ4aYduZJlFqqg.png" /></figure><p>Thats it! This is a very basic live whiteboard app that can keep track of multiple websocket connections and use them to transmit drawing data between all connections. Check out my code at <a href="https://github.com/asharma414/whiteboard">https://github.com/asharma414/whiteboard</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7cae864ed6c5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Creating a Basic Chart in D3.js]]></title>
            <link>https://medium.com/@abhi.sharm.414/creating-a-basic-chart-in-d3-js-4853e6df7d6e?source=rss-263cdfb77c8e------2</link>
            <guid isPermaLink="false">https://medium.com/p/4853e6df7d6e</guid>
            <dc:creator><![CDATA[Abhinav Sharma]]></dc:creator>
            <pubDate>Sun, 04 Oct 2020 05:06:17 GMT</pubDate>
            <atom:updated>2020-10-04T05:06:17.043Z</atom:updated>
            <content:encoded><![CDATA[<p>In my journey to learn web development, I wanted to expand my knowledge of HTML, SVG, and CSS to create visualizations. D3 or Data Driven Documents is a Javascript library for data visualization, and I will be using it to create a line chart. There are many other options to make basic charts and graphs, but I chose D3 because it is low level and allows for extreme vertatility when creating visualizations. I also thought it would be a good exercise because many other tools like Vega and Power BI integrate D3.js in their tools.</p><p>To start, I found a dataset to visualize, and I chose to create a graph of Bitcoin price over the years. To do this, I went to <a href="http://www.cryptodatadownload.com/">www.cryptodatadownload.com</a>, which is a website has historical data from many different crypto currency exchanges. I was able to download a CSV file of Coinbase’s daily BTC data from 2014 onwards.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*S6YQoPD84LPylfU-SHEbYg.png" /><figcaption>CSV stands for comma separated values and the files have a structure where the first row are the names of the columns separated by commas. All subsequent rows are the actual data corresponding to each respective column, separated by commas too.</figcaption></figure><p>To format the data for D3, I removed the first line (referencing the data source) and renamed some of the column names and removed spacing for convenience. Our data is now ready, so I uploaded the data to GitHub Gist for easy access.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tcvpZ1P9yr_7e_80xTa9WA.png" /><figcaption>The CSV data uploaded to GitHub Gist. I can easily access the raw data by clicking the Raw button.</figcaption></figure><p>Now we are ready to begin our D3 project. I start by making a our HTML, JS, and CSS files. I’ll name them all index for the purposes of this example. To start I put in my boilerplate HTML, with script tags for my JS file and the D3.js library and a link tag for my stylesheet. You can easily find a CDN link for the minified D3.js library on the D3 website. I also added an svg tag with a fixed size in my HTML body. This is the tag where we will insert our chart.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FlrEDqULpDvddxHmwGKNKQ.png" /></figure><p>Now we will move to our index.js file, and begin creating our chart. To begin we select our svg using the D3’s select function, and get the svg’s dimensions using D3’s attr function to create height and witdh constants which we will use to render data in the proper location.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/644/1*tGMeY8mwCyoKdQyFnkZUXQ.png" /><figcaption>Selecting the svg on the HTML page and creating height and width constants using the svg’s dimensions, making sure to typecast to numbers.</figcaption></figure><p>Next we will fetch our data from my GitHub Gist using D3’s csv function, with Promise syntax. This function will turn the CSV data into an array of objects. We will then make sure our chart data is properly typed for D3 to use. In this case we will have a line chart that is shows the closing price on the Y-axis and the date on the X-axis. I can use Javascripts built-in Date class to create date objects from the string dates we receive, and use the + operator turn the string value of the closing price to numbers. To do this for all the data received, I use the forEach method. Lastly, we will send this data to a render function which we haven’t created yet to render the data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*73lIXW0zUDUzVLqoNtbnzg.png" /></figure><p>Now we will create our render function, that takes in our data. To begin this function, we will define preliminary information about our chart including the title, axis labels, chart dimensions, etc. I’m also adding the xValue and yValue helper methods to represent the x and y coordinates as well as a circleRadius variable to help plot data points.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/994/1*Yoq6qWsHSn6yQRDGXdg2ow.png" /></figure><p>To plot the data relative to the size of the chart we need to utilize D3’s scaling functions, one for each axis. Our y-axis, being price, will use the scaleLinear function and our x-axis, being date, will use the scaleTime function. We will specify the domain and range using the data passed into render with the respective functions. The domain functions will utilize D3’s extent function to find the breadth of the x and y data. The range will then scale this data to fit the SVG using the chart dimensions variables we defined above. We will also create an SVG group using D3’s append function to allow us to easily translate multiple items together. I added a translation to make room for the chart title and y-axis label.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/952/1*gYPdKgMd_-djQmG9LAp2Uw.png" /></figure><p>To render the axes, we will utilize code shown below. I won’t go line by line, but I will explain generally what is going on. We create the axes by using D3’s axisBottom and axisLeft functions (D3 has one for top, bottom, left, and right). I’m using the tickSize and tickPadding to add additional styling that adjusts spacing and creates grid lines through the chart. I created and subgroups for both axes and appended them to the main group we appended to the svg above. The attr function was used many times here to adjust the positioning of elements being rendered to the page and to add CSS classes which we will use to create additional styling. Lastly, we append the title of the chart to the top of the main svg group.</p><pre>const xAxis = d3.axisBottom(xScale)</pre><pre>.tickSize(-innerHeight)</pre><pre>.tickPadding(15);</pre><pre>const yAxis = d3.axisLeft(yScale)</pre><pre>.tickSize(-innerWidth)</pre><pre>.tickPadding(10);</pre><pre>const yAxisG = g.append(&#39;g&#39;).call(yAxis);</pre><pre>yAxisG.selectAll(&#39;.domain&#39;).remove();</pre><pre>yAxisG.append(&#39;text&#39;)</pre><pre>.attr(&#39;class&#39;, &#39;axis-label&#39;)</pre><pre>.attr(&#39;y&#39;, -100)</pre><pre>.attr(&#39;x&#39;, -innerHeight / 2)</pre><pre>.attr(&#39;fill&#39;, &#39;black&#39;)</pre><pre>.attr(&#39;transform&#39;, `rotate(-90)`)</pre><pre>.attr(&#39;text-anchor&#39;, &#39;middle&#39;)</pre><pre>.text(yAxisLabel);</pre><pre>const xAxisG = g.append(&#39;g&#39;).call(xAxis)</pre><pre>.attr(&#39;transform&#39;, `translate(0,${innerHeight})`);</pre><pre>xAxisG.select(&#39;.domain&#39;).remove();</pre><pre>xAxisG.append(&#39;text&#39;)</pre><pre>.attr(&#39;class&#39;, &#39;axis-label&#39;)</pre><pre>.attr(&#39;y&#39;, 80)</pre><pre>.attr(&#39;x&#39;, innerWidth / 2)</pre><pre>.attr(&#39;fill&#39;, &#39;black&#39;)</pre><pre>.text(xAxisLabel);</pre><pre>g.append(&#39;text&#39;)</pre><pre>.attr(&#39;class&#39;, &#39;title&#39;)</pre><pre>.attr(&#39;y&#39;, -10)</pre><pre>.text(title);</pre><p>Phew! That was a lot, but now if you open the index.html file in your browser (You have to disable CORS restrictions in your browser temporarily), you should now see the chart below. You can see that our axes span the full breadth of our data points. Our axis labels, chart title, and grid lines are also visible.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/864/1*-QlpZ8-sx7mhhoMDksOePg.png" /></figure><p>To generate our line of data, we will generate a line using D3’s line function, and then append an SVG path to the chart using our function. This function will use our previously generated scales and data generators. I will also add a class using attr to allow for CSS styling.</p><pre>const lineGenerator = d3.line()</pre><pre>.x(d =&gt; xScale(xValue(d)))</pre><pre>.y(d =&gt; yScale(yValue(d)))</pre><pre>g.append(&#39;path&#39;)</pre><pre>.attr(&#39;class&#39;, &#39;line-path&#39;)</pre><pre>.attr(&#39;d&#39;, lineGenerator(data));</pre><p>Now I will add the following to my index CSS file. Notice the fill property is set to none, otherwise the SVG path will not appear like a line.</p><pre>.line-path {</pre><pre>fill: none;</pre><pre>stroke: steelblue;</pre><pre>stroke-width: 7;</pre><pre>stroke-linejoin: round;</pre><pre>}</pre><p>Now we have a basic line chart!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/819/1*llCxM04BbcgXZxkm4lItpg.png" /></figure><p>To add additional data and interactivity, let’s also plot points for all the data, and add tooltips that will provide additional details on hovering. We will start by appending circles for each data point. This will involve the use of D3’s enter function to represent the data to be rendered, which will be followed by an append to add the points to the DOM. We will use the attr function again to define the point locations with the help of our defined x and y scales. Then we will give each point a radius using the circleRadius variable defined earlier.</p><pre>g.selectAll(&#39;circle&#39;).data(data)</pre><pre>.enter().append(&#39;circle&#39;)</pre><pre>.attr(&#39;cy&#39;, d =&gt; yScale(yValue(d)))</pre><pre>.attr(&#39;cx&#39;, d =&gt; xScale(xValue(d)))</pre><pre>.attr(&#39;r&#39;, circleRadius)</pre><p>Now the chart will have black points plotted.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/833/1*MTMjPnnZoKaQkykhMvKGAQ.png" /></figure><p>To add our tooltips, we will create a div and append it to our HTML body. Then we will give it a class to allow for styling and set the initial opacity to 0.</p><pre>const div = d3.select(&quot;body&quot;).append(&quot;div&quot;)</pre><pre>.attr(&quot;class&quot;, &quot;tooltip&quot;)</pre><pre>.style(&quot;opacity&quot;, 0);</pre><p>Now we must go back to the circle plotting function and add event listeners that will detect when we hover on a data point and to make the tooltip visible and render additional data. We will make use of D3’s on function with the mouseover and mouseout events. This will be added to the end of the circle plotting function. Our code looks as follows.</p><pre>g.selectAll(&#39;circle&#39;).data(data)</pre><pre>.enter().append(&#39;circle&#39;)</pre><pre>.attr(&#39;cy&#39;, d =&gt; yScale(yValue(d)))</pre><pre>.attr(&#39;cx&#39;, d =&gt; xScale(xValue(d)))</pre><pre>.attr(&#39;r&#39;, circleRadius)</pre><pre>.on(&quot;mouseover&quot;, d =&gt; {</pre><pre>div.transition()</pre><pre>.duration(200)</pre><pre>.style(&quot;opacity&quot;, .9);</pre><pre>div.html(d.date.toLocaleString(&#39;en-US&#39;) + &quot;&lt;br/&gt;&lt;br/&gt; Open: $&quot; + d.open + &quot;&lt;br/&gt;&lt;br/&gt; Close: $&quot; + d.close + &quot;&lt;br/&gt;&lt;br/&gt; Volume(USD): $&quot; + d.volumeUSD)</pre><pre>.style(&quot;left&quot;, (d3.event.pageX) + &quot;px&quot;)</pre><pre>.style(&quot;top&quot;, (d3.event.pageY - 28) + &quot;px&quot;);</pre><pre>})</pre><pre>.on(&quot;mouseout&quot;, function (d) {</pre><pre>div.transition()</pre><pre>.duration(500)</pre><pre>.style(&quot;opacity&quot;, 0);</pre><pre>});</pre><p>This alone will not make the tooltips work properly, so we will add additional CSS styling as follows by using the ‘tooltip’ class we assigned to the div above.</p><pre>div.tooltip {</pre><pre>position: absolute;</pre><pre>text-align: center;</pre><pre>width: 150px;</pre><pre>height: 125px;</pre><pre>padding: 2px;</pre><pre>font: 12px sans-serif;</pre><pre>background: lightsteelblue;</pre><pre>border: 0px;</pre><pre>border-radius: 8px;</pre><pre>pointer-events: none;</pre><pre>}</pre><p>Now when we hover our mouse over the data points, a tooltip appears giving additional information.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/855/1*bDI-e6e9NYhMN-lnLYuTcQ.png" /></figure><p>I finish by adding additional CSS to make the chart look better.</p><pre>text {</pre><pre>font-family: sans-serif;</pre><pre>}</pre><pre>.tick text {</pre><pre>font-size: 2.7em;</pre><pre>fill: #635F5D;</pre><pre>}</pre><pre>.tick line {</pre><pre>stroke: #C0C0BB;</pre><pre>}</pre><pre>.axis-label {</pre><pre>font-size: 5em;</pre><pre>fill: #8E8883;</pre><pre>}</pre><pre>.title {</pre><pre>font-size: 3.7em;</pre><pre>fill: #635F5D;</pre><pre>}</pre><p>Here is our final chart!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/864/1*-zf7zuns_FBxrLbZvUCB8w.png" /></figure><p>And there we have it! This was a basic line chart created using D3.js. This may have seemed like a lot of work to create a basic graph, and you would be right. There are many easier frameworks to use to create graphs, but D3 is a complete data visualization library that allows much flexibilty. In the process of learning, there is nothing wrong with starting from the basics, and that is exactly what I did. Please check out my code at <a href="https://github.com/asharma414/d3practice">https://github.com/asharma414/d3practice</a>. Thank you for reading!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4853e6df7d6e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[React State + Lifecycle and Lesser Used Methods]]></title>
            <link>https://medium.com/@abhi.sharm.414/react-state-lifecycle-and-lesser-used-methods-4aedf4252e?source=rss-263cdfb77c8e------2</link>
            <guid isPermaLink="false">https://medium.com/p/4aedf4252e</guid>
            <category><![CDATA[lifecycle]]></category>
            <category><![CDATA[state]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Abhinav Sharma]]></dc:creator>
            <pubDate>Thu, 09 Jul 2020 19:11:42 GMT</pubDate>
            <atom:updated>2020-07-09T19:26:55.939Z</atom:updated>
            <content:encoded><![CDATA[<p>Anyone who has regularly practiced software development knows:</p><ol><li>The field is a moving target. While some paradigms have stood the test of time, most have been replaced or at least updated to keep up. This also means if you as a developer don’t keep up with the latest technologies, and trends, you will get left behind.</li><li>While we have reached an age where programming languages, libraries, and frameworks are so high level, there are still many situations that don’t abide by one size fits all situations.</li></ol><p>React is an example of a development technology that demonstrates these concepts pretty well. Foundational knowledge of React includes the component lifecycle and its relation to state and props. Most React developers know of lifecycle methods like componentDidMount, componentDidUpdate, and of course render (which is the only required lifecycle method).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hSO--5BPT1K_YK6VqRy4vg.png" /></figure><p>For most situations, only using these will suffice, but in real world situations there are many edge cases. For this reason, developers of React have created numerous lesser used lifecycle methods. If you follow React documentation, then you will see that many methods have been introduced, and some are even deprecated as new releases come. I will talk about some of these, as well as some use cases.</p><ol><li><strong>constructor(<em>props</em>)</strong>- An overlooked method because it is actually part of vanilla JS, but it can also be used in React class components. When called in a React component, super(props) must also be invoked. If the constructor is invoked, the state object must be set inside of it. Using constructor is actually optional, and the state object can be set right inside of the class.</li><li><strong><em>static</em> getDerivedStateFromProps(<em>props</em>, <em>state</em>)</strong>- This is a static method that is essentially used to map props received by a component to that component’s state. This method is called just before render(). Because this method is static, you do not have access to ‘this’, meaning state isn’t set using the setState method. It simply returns an object that is appended to the component’s state. It is rarely used but useful when you want to set a piece of state based on a change to received props.</li><li><strong>shouldComponentUpdate(<em>nextProps</em>, <em>nextState</em>)</strong>- This lifecycle method can be used to control when the component re-renders. It gets called before render upon receipt of new props or state, and returns a boolean indicating wether to re-render. This should strictly be used for performance reasons and not to prevent renders.</li><li><strong>getSnapshotBeforeUpdate(<em>prevProps</em>, <em>prevState</em>)</strong>- This lifecycle method is called right before the render output is being passed to the DOM. It is a way to look at your previous state and props right before the DOM is updated. It returns either null or a value which get passed to componentDidUpdate. Rare use cases like adjusting the window position before updating the DOM.</li><li><strong>forceUpdate(<em>callback</em>)</strong>- Most of the time setState triggers a re-render. However some use cases may call for a re-render without changing state or receiving new props. This method can be used to force a re-render.</li><li><strong>setState(<em>updater</em>, <em>callback</em>)</strong>- This method is ubiquitous in React, but there are many lesser known ways to invoke the function. Most developers are familiar with just passing the updater function as an object. It is important to note that it asynchronous so it will not always execute consistently on time. Therefore it is not wise to use ‘this.state’ immediately after calling setState. For this reason you can also pass a callback function to it.</li><li><strong>componentDidCatch(<em>error</em>, <em>info</em>)</strong>- This lifecycle method gets called when a child component throws an error. It takes in the error as well as an info object containing the stack trace. Keep in mind that this method only tracks errors in the render/lifecycle methods, not for an error in something like a click handler.</li><li><strong><em>static</em> getDerivedStateFromErrors(<em>error</em>)</strong>- Similar to the last method, this receives errors that occur in a child component and can be used to update the state of the parent accordingly.</li><li><strong>UNSAFE_componentWillUpdate(<em>nextProps</em>, <em>nextState</em>)</strong>- As you can see this lifecycle method starts with ‘UNSAFE’ which means the React developers have deprecated it due to security or performance reasons. This method is called right before new state or props are received allowing preparation before an update occurs. With the React 17 release coming up, this method will no longer work. The reason I mention this one is because I have used it in the past, but realized that I needed to refactor before it no longer works.</li></ol><p>I made this blog as a reference for myself and others because there are always edge cases in web development that need specialized solutions. Most of this information is straight from the React documentation, but that is where the lesson lies. I described only some of the methods offered by the React API, and guaranteed to be out of date at some.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4aedf4252e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Ramblings About Authentication]]></title>
            <link>https://medium.com/@abhi.sharm.414/ramblings-about-authentication-775eca62724b?source=rss-263cdfb77c8e------2</link>
            <guid isPermaLink="false">https://medium.com/p/775eca62724b</guid>
            <category><![CDATA[cookies]]></category>
            <category><![CDATA[jwt]]></category>
            <category><![CDATA[authentication]]></category>
            <dc:creator><![CDATA[Abhinav Sharma]]></dc:creator>
            <pubDate>Thu, 28 May 2020 05:49:12 GMT</pubDate>
            <atom:updated>2020-05-28T13:16:18.872Z</atom:updated>
            <content:encoded><![CDATA[<p>Nowawadays the principles of user login are abstracted away, and in most cases, for good reason. Security is of utmost importance, and risking potential slip ups by manually setting up your own authentication system could be a recipe for disaster. However, it’s still a fun exercise to explore the nitty gritty details of such a specialized area of web development.</p><p>This technological age has ushered in a new era of interconnectedness when people, things, and ideas are at the touch of a button. This comes with consequences. Today, we typically say it’s not if your information will get stolen, but simply when. Every precaution is encouraged, but hackers inevitably find a way around. If you don’t believe me, gather all of the email addresses you’ve ever used, and test them at <a href="https://haveibeenpwned.com/">https://haveibeenpwned.com</a>. Chances are that you have been the victim of data leaks at some point (I certainly have). Interestingly, the same website also has an API for checking if your password was ever hacked. You can (at your own risk) enter your password, and the site will tell you, if it was found on the database. Though the site is most likely trustworthy, here is a video link explaining how you can set up some code and poll the website’s password API to check without actually ever sending your whole password: <a href="https://www.youtube.com/watch?v=hhUb5iknVJs">https://www.youtube.com/watch?v=hhUb5iknVJs</a></p><p>Realizing that some of your information has likely already been compromised should enlighten you as to why we need to have proper security measures for authenticated websites. Two of the most popular ways to grant user authentication today are session cookies and bearer tokens. Session cookies grant a state to your web application, while tokens were built to be stateless. Both have their advantages and disadvantages, but security should remain a prime concern when deciding between them.</p><p>The common thread between the two technologies is having to use login credentials. You typically go to a website, enter your username/email and password and login. This seems simple, but there is a lot going on under the hood to keep you safe. For one, a secure website NEVER stores unhashed passwords on its database. It goes without saying that this is a recipe for disaster, as the passwords don’t have to be cracked if they are leaked. Without going too much into the math, think of hashing as a black box computational algorithm that takes in whatever data you are feeding it, and returns you a hash.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TYksd-54nb0Q0cXgu_0gyw.png" /></figure><p>This hash is a scrambled version of the original data, which (in theory) is unique to that piece of data, and can thus represent the original. How does this protect us? Well, it goes back to the algorithm, which is set up to essentially be a one way transformation. Once you encrypt your data by hashing, there is no easy way to reverse that transformation (so called one-way functions). When you register/login on a website entering your plaintext credentials, your password is hashed before any database calls are made. This hashed version of the password is compared to the hashed version stored on the database. If they match, you will be granted access to the website.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*ii2_ZHT8PL0oQ_GNiMMOpw.png" /><figcaption>Written in JavaScript using the Express framework. This is a typical way a website would handle saving your password after you registered.</figcaption></figure><p>The database has verified your identity. Now what? Well this is where we come back to cookies and tokens. For cookies, after the database call verifies the login credentials, a session is created server-side and a cookie with the session’s ID is sent to the client, and put into an object called sessionStorage in your web browser window. This cookie is sent as a header in all of the client’s server requests, which essentially tells the server that the request is coming from a verified user.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/545/1*GuA4KSiYW3-QJJ0j0Li_ZQ.png" /><figcaption>Written in Ruby on the Rails framework.</figcaption></figure><p>In the image above, the login_user function checks the sent credentials, verifies the user exists, and then uses the authenticate method to compare the plaintext password to the database password via hashing. Only if the two mentioned conditions are satisfied does the server start a session pertaining to that particular user. When you call session[:logged_in_user_id] = user_to_login.id Rails will create a new record in thesessions table with a random session ID (say, 09497d46978bf6f32265fefb5cc52264), store {logged_in_user_id: user_to_login.id} (Base64-encoded) in the data attribute of that record, and return the generated session ID, 09497d46978bf6f32265fefb5cc52264, to the browser using Set-Cookie. When you logout, the session is terminated by the server. Thus, session cookies are what we call “stateful”, which is in contrast to the stateless architecture of HTTP. Because the session has to be maintained on the server, this creates more load server-side. Cookies in general can also be vulnerable to cross-site request forgery (XSRF) attacks. This happens when an attacker takes advantage of your session cookie and an insecure website to submit a form on your behalf. For this reason, CSRF tokens were created, and are embedded in forms to mitigate problems. When a CSRF token is generated, it’s stored server-side within the user’s session data and attached as a hidden field to any forms sent to the client. This means that even if a hacker steals your session cookie, they don’t also have your session specific CSRF token needed to complete submission of the form.</p><p>The other primary way to authenticate users is bearer tokens, primarily seen in the form of JSON Web Tokens (JWTs). A JWT is created in the code below in response to the user’s credentials being verified on the database. This JWT is then signed using a secret, to prevent tampering, and sent to the client (see below).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/528/1*Km7AdePWkEAji31JjzkLew.png" /></figure><p>On the client side, we can save the token to the web browser’s localStorage, and then set the Authorization header in all HTTP requests to our protected routes to the value of this token.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/468/1*1urCB_21jdMfYdycB4QocA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/464/1*T6Q632UCK6V3yTdb6ukD8Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/337/1*F_EO1UBDdleikN6yUrVOhQ.png" /></figure><p>Once this is done, I am considered authenticated. As long as all of the HTTP requests coming from my computer to that website have the token I was given in the Authorization header, they will be permitted.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/546/1*4u-XfQbAgHtEzULWi6wLiQ.png" /></figure><p>Notice a difference between this and cookies? I didn’t mention anything about sessions. The JWT was put on the localStorage object and is self contained, meaning it has all the necessary pieces to verify the legitimacy of an HTTP request. As long as I have an unexpired token and don’t logout/(clear my web browser’s cache), I will be able to access the website without restriction. This is what makes JWTs stateless. The burden is shifted to the client whose computer stores signed tokens. JWTs have become very popular these days because they are an open standard which are highly scalable, flexible, and stateless. They however, take up much more space than cookies, so storing a lot of information in them can slow down transmission of HTTP requests because the token has to be put on the Authorization header of each one. Also, because JWT are typically put on localStorage, they are vulnerable to cross-site scripting (XSS) attacks. This happens when a hacker is able to inject executable javascript code onto your website. When another client visits that page, the potentially malicious script is automatically executed by the web browser. This script has full access to the browser’s localStorage object, which means that your JWTs can be stolen and used by a hacker to make AJAX requests on your behalf. For this reason, among others, user inputs should be “sanitized” to prevent the inclusion of any scripts.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/283/1*PkPm6oOKQ8j2Ja7CQM9-jw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/496/1*_dTod_7UY9RP3UKFHaLyIw.png" /><figcaption>The two images here show two lines of code where I include an HTML sanitizer tool in my web page. The third line shows me using that tool to sanitize comment.text before rendering to the page.</figcaption></figure><p>Overall, session cookies with proper protection are probably still more secure than JWTs due to their stateful nature and lack of any meaningful information on the session cookie. However, tokens are becoming more widespread and are more scalable and flexible than cookies. As long as proper security measures are taken, and your website isn’t vulnerable to XSS attacks, tokens have their place. Of course, there is no ultimate solution, and the field of security in the tech world is a moving target. Hackers are always finding new ways to break code and that is the way it will always be. This is why authentication is its own subfield in the software engineering field, and most people rely on prepackaged password encryption solutions like bcrypt. And if you’re at the enterprise level, your organization may even hand-off authentication entirely to a third-party like Okta.</p><p>Even though our data can’t be perfectly secure, there are relatively good solutions out there that work most of the time if properly implemented. This is why it’s important to understand the underlying concepts of authentication, even if you won’t build it from scratch yourself. Obviously I barely scratched the surface of this topic, but I wanted to give a more in depth perspective than most beginner web developers may be exposed to. Thank you!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=775eca62724b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Throwing myself into the fire from the frying pan… my first full-stack project.]]></title>
            <link>https://medium.com/@abhi.sharm.414/throwing-myself-into-the-fire-from-the-frying-pan-my-first-full-stack-project-815d942a4d07?source=rss-263cdfb77c8e------2</link>
            <guid isPermaLink="false">https://medium.com/p/815d942a4d07</guid>
            <dc:creator><![CDATA[Abhinav Sharma]]></dc:creator>
            <pubDate>Thu, 07 May 2020 13:55:38 GMT</pubDate>
            <atom:updated>2020-05-07T14:11:17.948Z</atom:updated>
            <content:encoded><![CDATA[<p>I began my journey as a software developer about six months ago by self teaching. Being self-taught can be rewarding, but only if you remain disciplined. In my case, I was able to pick up basic concepts easily by referencing online tutorials primarily using small examples (i.e. we’ve all seen the classic Hello World), but had a hard time translating this foundational knowledge to build complex functionality. To clarify, I had taken a web development course and completed one guided full-stack project by this time. However, I needed the motivation to keep me focused, and found that I learned so much more by, for lack of a better phrase, “throwing myself into the deep end.”</p><p>At a certain point in my learning, even though I had severe imposter syndrome, and incomplete knowledge, I decided to start my first, original full stack project. I took some of the knowledge I had already acquired (Node.js, Express, MongoDB), but also wanted to learn and include additional technologies like a frontend framework, a state management tool, and microservices. Based on my research of popular technology stacks, I finally decided on the MERN stack (MongoDB Atlas, Express, React/Redux, Node.js). After I chose which technologies I wanted to implement, I would then come up with an idea to create a web app utilizing them.</p><p>Coming up with an idea for a project can be difficult because you may feel like you have to create the next Google to impress employers. But in my opinion, you shouldn’t feel that way, as long as the idea is something you like. I say this because the idea I went with isn’t particularly flashy or original.</p><p>My idea was for an IT ticket management system (YAWN…. I know). However, I came from a healthcare IT background, and ticket management systems are a standard in the IT and help desk world. Any time, a client/end-user encounters a technical problem and contacts a help desk, those help desk employees create a “ticket” (sometimes called a case) with all of the details of the call so that issues can be easily logged and tracked. In my head, this seemed like a great candidate for a full-stack application. For one, this is already an idea thats been implemented so I know I’m not attempting something no one has ever done before. Second, I already had first hand experience using such a system, and knew generally how it should function. A screenshot might be helpful to visualize this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/814/1*RmsIoj2CB8v6XVygclW_lw.png" /><figcaption>Example image of a ticket from an IT ticket management system. Just by looking at the image, you can get an idea of how the app works. Users can author tickets. A ticket has properties (state, author, timestamps, description, etc), and these properties can be changed. Tickets can also have comments, which can be created using a form.</figcaption></figure><p>I started my idea with OOP in mind. It’s a good idea to diagram your application with your data models and core functionality before you even write a single line of code. In my application, there are three models: users, tickets, and comments. The key step in creating functionality in an application is to see how your different data models relate and interact with each other. All it took was these three models to create the core functionality of a commercial product like ServiceNow (a popular SaaS ITSM system). I just had to create basic functionality to allow users to be created and for users to create/update tickets and comments.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/574/1*vGf7uz03iI8fWwV9NZGTiQ.png" /><figcaption>*FYI* This is somewhat of a simpflication and looks like a SQL ER Diagram, but is actually representing a MongoDB model schemas.*FYI* Relationship diagram for my application’s models.</figcaption></figure><p>After I built the core of my app, I could focus on smaller details, like appearance and especially additional features. Maybe I want to add the ability for users to register/login securely with credentials? Or maybe I want to add pagination to show my tickets/comments on different pages if I have a lot? Or add the ability to auto-close a ticket after a certain period of time when the customer’s issue is resolved? Or maybe… I just want to fix some quirky bugs! And in fact, I did all of that and more with this application! Even now, I continue to maintain and add features to it. Because, I’ve been working on the project continuously, I know it in and out. When something goes wrong, I already have an idea of where to look to fix it. I can also now say that, even if I step away from the project for a period of time, I’ve solidified my knowledge enough that I could pick up where I left off easily.</p><p>The first image you saw in this blog post was actually a screenshot of my application. Please check out my deployed demo at <a href="https://itilapp.herokuapp.com/">https://itilapp.herokuapp.com</a>. If you are interested in how it actually works, take a look at my source code at <a href="https://github.com/asharma414/itilapp">https://github.com/asharma414/itilapp</a>. The website may take a minute to load initially, but that is normal because I am using Heroku’s free deployment service.</p><p>I know I’m giving a very high level overview of this application, and not really talking about the nitty gritty programming involved. In fact, I didn’t even discuss the struggles of having to learn new technologies while trying to implement them. The reason is, I believe that it was because I took myself out of my comfort zone and attempted a new project with new technologies that ended up learning so much. Of course it was difficult, but it was rewarding, I learned a lot, and I have something to show for it! That is the ultimate point I’m trying to make with this blog post. Even with a basic idea, you can create a very functional and interesting application. Good luck with your projects!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=815d942a4d07" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>