<?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 Dinushanka on Medium]]></title>
        <description><![CDATA[Stories by Dinushanka on Medium]]></description>
        <link>https://medium.com/@rama41222?source=rss-addd29877f03------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*R5OHKxDB0jWuyfU4He7BtA.jpeg</url>
            <title>Stories by Dinushanka on Medium</title>
            <link>https://medium.com/@rama41222?source=rss-addd29877f03------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 14:10:08 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@rama41222/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[NestJS Project Starter with Multiple Database Connections using TypeORM and MySQL]]></title>
            <link>https://itnext.io/nestjs-project-starter-with-multiple-database-connection-using-typeorm-and-mysql-47150e282ed5?source=rss-addd29877f03------2</link>
            <guid isPermaLink="false">https://medium.com/p/47150e282ed5</guid>
            <category><![CDATA[mysql]]></category>
            <category><![CDATA[nestjs-tutorial]]></category>
            <category><![CDATA[multiconnection]]></category>
            <category><![CDATA[docker-compose]]></category>
            <category><![CDATA[nestjs]]></category>
            <dc:creator><![CDATA[Dinushanka]]></dc:creator>
            <pubDate>Thu, 26 Aug 2021 12:09:10 GMT</pubDate>
            <atom:updated>2021-08-28T14:46:14.397Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/879/1*zjbQKzeIt3UM1ezHkDvHNw.png" /></figure><p>I’ll be using MySQL for this short tutorial. The first step would be to create a new Nestjs project. You can either follow the official <a href="https://docs.nestjs.com/">documentation</a> or use the following command.</p><h4>Setting up NestJS</h4><p>First, let’s install the nest CLI tool.</p><pre>$ npm i -g @nestjs/cli</pre><p>Next, let’s initialize an empty project using the CLI</p><pre>$ nest new project-name</pre><p>Next, install the required npm packages</p><pre>$ npm i --save @nestjs/core @nestjs/common rxjs reflect-metadata</pre><h4>Let’s Generate a module using the Nest CLI</h4><p>To do this, we can use the built-in CLI. It will be much easier to generate rather than creating your own controllers and services. Use the following commands to generate the required module, service, and controller. I’m going to generate a new module called power-search inside the <em>src/modules/power-search </em>folder</p><pre>$ nest g module modules/power-search<br>$ nest g controller modules/power-search<br>$ nest g service modules/power-search</pre><p>After creating the module, The next step is to set up the dev environment and the database connections.</p><h4>MySQL Setup</h4><p>Let’s set up our dev environment first. We’ll be using Docker to install MySQL and run it on the local machine. Copy the following docker file and run it using docker-compose up . If you want to know more about docker, please refer to <a href="https://itnext.io/lets-dockerize-a-nodejs-express-api-22700b4105e4">this article</a>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ed612108dda029fa9b19b275cedb9162/href">https://medium.com/media/ed612108dda029fa9b19b275cedb9162/href</a></iframe><p><em>Since we’ll need another database, I have created it using the init.sql script. Copy the script into the docker-compose location.</em></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7face890d23d4327911ed73ff6562146/href">https://medium.com/media/7face890d23d4327911ed73ff6562146/href</a></iframe><p>Now run the docker-compose using;</p><pre>docker-compose up</pre><p>Some important docker commands</p><pre>docker-compose down # Removes the container<br>docker-compose down -v # Remove the created volumes as well<br>docker-compose up -d # -d will run the compose file in background<br>docker-compose build # This will just build an image</pre><p>Since we are done with setting up the local environment. Let’s install TypeORM and the relevant packages.</p><h4>Mysql on NestJs</h4><p>For this, you can also refer to the official <a href="https://docs.nestjs.com/techniques/database">documentation</a>.</p><pre>$ npm install --save @nestjs/typeorm typeorm mysql2</pre><p>We’ll use a straightforward approach. First, let’s create the connection string as defaultOptions variable in the app.module.ts file.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cae1ee906e21bd219b3a045fbee0e5d7/href">https://medium.com/media/cae1ee906e21bd219b3a045fbee0e5d7/href</a></iframe><p>I know that hardcoding passwords or any type of credentions inside an API is not a good practice. So to get rid of this, use a <strong>dotenv</strong> file. NestJS has a built-in package for configuration management.</p><p>If you check the above code, There are 2 connection objects. If the connection is not provided with a name, therefore the name will default to ‘<em>default</em>’. <strong>If we are using multiple connections, providing a name to the secondary connections is a must!</strong></p><h4>Less Messy Approach</h4><p>We can use the ormconfig.json and specify all the connections as an array and use the name to import each config. But as of now,<strong> this doesn&#39;t work. </strong>Hopefully, it will be fixed in a future version.</p><h4>NestJS App setup</h4><p>Next, we have to set up the power search module. To do that use the following code sample.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/93d1576ad86637b396cc3ddb446d0951/href">https://medium.com/media/93d1576ad86637b396cc3ddb446d0951/href</a></iframe><p>Note that, you must provide the connection name with import. There’s no need to specify the name if you are using the default connection.</p><pre>imports: [TypeOrmModule.forFeature([power_search], &#39;w&#39;)]</pre><p>Still, we are <strong>NOT</strong> done. If we are utilizing this, we have to specify the name in the power-search.service.ts. Otherwise, it will not recognize that the power_search model is a part of ‘<strong>w</strong>’ connection.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f89cca2c13675e3d8eea90c0aba4f339/href">https://medium.com/media/f89cca2c13675e3d8eea90c0aba4f339/href</a></iframe><p>Now we are done. Happy Coding and Than you for reading this article ❤</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=47150e282ed5" width="1" height="1" alt=""><hr><p><a href="https://itnext.io/nestjs-project-starter-with-multiple-database-connection-using-typeorm-and-mysql-47150e282ed5">NestJS Project Starter with Multiple Database Connections using TypeORM and MySQL</a> was originally published in <a href="https://itnext.io/">ITNEXT</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Socket.io insights]]></title>
            <link>https://medium.com/hackernoon/socket-io-insights-a59d4612fa23?source=rss-addd29877f03------2</link>
            <guid isPermaLink="false">https://medium.com/p/a59d4612fa23</guid>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[sockets]]></category>
            <category><![CDATA[socketio]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[socket-programming]]></category>
            <dc:creator><![CDATA[Dinushanka]]></dc:creator>
            <pubDate>Sat, 28 Sep 2019 02:58:13 GMT</pubDate>
            <atom:updated>2019-09-28T02:58:13.575Z</atom:updated>
            <content:encoded><![CDATA[<p>What I have learnt so far…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*H04a4fbD6GvDDYF8wPqPCw.png" /></figure><ul><li>SocketIO is a libraby to enable realtime bidirectional event based communication between a client and a server by establishing a persistant connection.</li><li>SocketIO has a client library and a server librabry.</li></ul><h4><strong>This is how you can initialize a socket.io server</strong></h4><pre>const app = require(&#39;express&#39;)(); <br>const http = require(&#39;http&#39;).Server(app); <br>const io = require(&#39;socket.io&#39;)(http);</pre><p><strong>io</strong> is a object which outputs new socket.io instance.</p><pre>io.on(&#39;eventname&#39;, callback function);</pre><ul><li>Using this io object we can listen to certain events.</li><li>Socket.IO connection is made using a handshake. the handshake occurs over http post request using a handshake URI.</li><li>When a client connects it will emit connection event which will call the callback with a socket when the connection has been established. then using the socket we can send client messages, broadcast events etc.</li><li>Socketio uses <em>websocket programming model</em> under the hood.</li><li>Socketio supports serialization and deserialiation of data.</li><li>Socketio maintains a socket pool. Using this data, socket io can broadcast a message.</li></ul><h4>Namespaces</h4><ul><li>There’s always a default path for each communication to happen. usually it’s the root path ‘/’ which is a namespace itself.</li><li>Clients will connect to root if it’s not specificed by the client when connecting to server.</li><li>But if you want to have different channels, you can use different namespaces.</li><li>Namespaces are only created in server side. For example given below are examples. Basically you can have any name.</li></ul><pre>/general<br>/randoms<br>/myprivatechannel</pre><ul><li>If you are broadcasting a message to a certain namespace, then all the subscribers of that namespace will receive the message. Following is a basic implementation of a namespace in socket io. Refer the below github links for full implementation.</li></ul><pre>const nsp = io.of(&#39;/my-namespace&#39;);<br>nsp.on(&#39;connection&#39;, function(socket) {<br>    console.log(&#39;someone connected&#39;);<br>    nsp.emit(&#39;hi&#39;, &#39;Hello everyone!&#39;); <br>});</pre><ul><li>socket io maintain a pool of connected or alive connections and these sockets are shared between these namespaces. Therefore client doesn’t need to create new TCP connection to connect to each channel. Rather the io will share the socket.</li></ul><h4>Rooms</h4><ul><li>They are arbitary channels with in a namespace.</li><li>Rooms are used to further division.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/657/1*qb90jITB_fK68tA7cUqngQ.png" /><figcaption>Basic implementation of rooms</figcaption></figure><ul><li>To leave a room you can use io.leave</li><li>The other notable events are;</li></ul><pre>1. close (this happens only once hence io.once)<br>2. error (Error event)<br>3. data (when the client sends data - this can be a custom event   also. the user can use any name)<br>4. Connect<br>5. Message<br>6. Reconnect<br>7. Ping<br>8. Join and Leave (namespaces)</pre><ul><li>Broadcasting is used when the server needs to send message to all the connected clients. you can use io.sockets.emit(‘message’) to send data to all connected clients.</li></ul><pre>io.sockets.emit(‘message’)</pre><ul><li>when it comes to the client, client has to first connect to the socket io server on a specific address and a port. after that client and server can use the opened tcp connection to transmit data bidirectionally until the client closes the connection.</li></ul><h4><strong>Fallbacks</strong></h4><p>Socket.io has lot of transport mechanisms</p><pre>1. WebSockets<br>2. FlashSocket<br>3. XHR long polling<br>4. XHR multipart streaming<br>5. XHR polling<br>6. JSONP polling<br>7. iframes</pre><p>I want to learn socket.io library in depth and this is the summary of my attempt to do so. Improvements are always welcome</p><p>For the fine implementation details, go through my sample chat application created using Vue.JS and Nodejs.</p><pre><a href="https://github.com/rama41222/chat">https://github.com/rama41222/chat</a></pre><p>Java developers can <a href="https://github.com/rama41222/Soc_App_V1.0">refer here for the java implementation</a> and the <a href="https://rama41222.blogspot.com/2017/03/java-sockets-lets-build-chat-application.html">old blogspot article</a></p><p>Thank you ❤</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a59d4612fa23" width="1" height="1" alt=""><hr><p><a href="https://medium.com/hackernoon/socket-io-insights-a59d4612fa23">Socket.io insights</a> was originally published in <a href="https://medium.com/hackernoon">HackerNoon.com</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Let’s Dockerize a Nodejs Express API]]></title>
            <link>https://itnext.io/lets-dockerize-a-nodejs-express-api-22700b4105e4?source=rss-addd29877f03------2</link>
            <guid isPermaLink="false">https://medium.com/p/22700b4105e4</guid>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[docker-compose]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[devops]]></category>
            <dc:creator><![CDATA[Dinushanka]]></dc:creator>
            <pubDate>Wed, 27 Mar 2019 16:24:59 GMT</pubDate>
            <atom:updated>2019-04-12T18:44:50.756Z</atom:updated>
            <content:encoded><![CDATA[<h4>From Hello World to Continous Development.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*W4DwYGZCe2tMlcUIdDF0Sg.jpeg" /></figure><h4>NodeJS Hello World!</h4><p>To start with, let’s create a minimal nodejs api consisiting a simple GET route. For this example i’ll be using expressjs which is a popular framework for nodejs.</p><ol><li>Initialize a new npm project</li></ol><pre>npm init</pre><p>2. Create required files</p><pre>touch .gitignore<br>touch .dockerignore<br>touch server.js</pre><p>3. Ignore your .env and secrets from commiting accidently into git using <strong>.gitignore</strong> Similarly, use .dockeringore to prevent files from packaging into a docker image.</p><p>4. Let’s create a simple server using expressjs. For this we’ll be needing the following packages</p><pre>npm install --save express cors body-parser @rama41222/node-logger</pre><p>6. For continuous development, you’ll need nodemon. Install nodemon as a dev dependancy.</p><pre>npm install --save-dev nodemon</pre><p>5. After installing these packages, create the server.js as follows.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/df100d1494d3ecb14df4a13bd27e7d9b/href">https://medium.com/media/df100d1494d3ecb14df4a13bd27e7d9b/href</a></iframe><p>6. Goto the package.json and under scripts, create the following commands</p><pre>&quot;scripts&quot;: {<br>  &quot;start&quot;: &quot;node server.js&quot;,<br>  &quot;dev&quot;: &quot;nodemon server.js&quot;<br>}</pre><p>7. Let’s run it</p><pre>npm run dev</pre><p>8. You should see the following log if your api is running well.</p><pre><em>2019–03–27 00:25:56 info: sample-express-app running on 0.0.0.0:3000</em></pre><p>We are almost done with nodejs coding. Now let’s get into docker.</p><h4>Docker File</h4><ol><li>First create a <strong>Dockerfile </strong>and a<strong> docker-compose.yml </strong>to run the nodejs api using docker.</li></ol><pre>touch Dockerfile<br>touch docker-compose.yml</pre><p>2. Let’s creat the Dockerfile and docker-compose.yml as follows</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8cd19bfd7f528e49a14e312a5ecf9fa1/href">https://medium.com/media/8cd19bfd7f528e49a14e312a5ecf9fa1/href</a></iframe><h4>Let’s quickly walk through the Dockerfile</h4><p>So in the docker file, we are using the <strong>alpine</strong> image since it’s very simple, light weight and more secure. Alpine Linux is based on <em>musl libc </em>and<em> busybox.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/763/1*DmFpyNq__ebT3MFE_ud-uw.png" /><figcaption><strong>alpine</strong> linux image sizes</figcaption></figure><pre><strong>FROM </strong>node:11-alpine</pre><p><a href="https://docs.docker.com/engine/reference/builder/#run">RUN</a> is an image build step, the state of the container after a RUN command will be committed to the docker image. A Dockerfile can have many RUN steps that layer on top of one another to build the image.</p><pre><strong>RUN </strong>mkdir <strong>-</strong>p <strong>/</strong>usr<strong>/</strong>src<strong>/</strong>app</pre><p>Then we set the default working directory by follwing command</p><pre><strong>WORKDIR /</strong>usr<strong>/</strong>src<strong>/</strong>app</pre><p>Copy all files to the image</p><pre><strong>COPY </strong>. .</pre><p>Install the packages</p><pre><strong>RUN </strong>npm install</pre><p>Now we must expose the API running port to the outside world inorder to recieve requests.</p><pre><strong>EXPOSE </strong>3000</pre><p><a href="https://docs.docker.com/engine/reference/builder/#cmd">CMD</a> is the command the container executes by default when you launch the built image. A Dockerfile can only have one CMD. The CMD can be overridden when starting a container with docker run $image $other_command.</p><p><a href="https://docs.docker.com/engine/reference/builder/#entrypoint">ENTRYPOINT</a> is also closely related to CMD and can modify the way a container starts an image</p><pre><strong>CMD </strong>[&quot;npm&quot;, &quot;run&quot;, &quot;start&quot;]</pre><h4>Let’s run the API using docker</h4><ol><li>Let’s build the docker image</li></ol><pre>docker-compose build</pre><p>2. Let’s run the container.</p><pre>docker-compose up</pre><p>3. Let’s run the above command in the background</p><pre>docker-compose up -d</pre><p>Take a look at the following commands. They are very useful</p><pre>docker-compose stop<br>docker-compose start<br>docker-compose run &lt;custom service&gt;</pre><ul><li><strong><em>When you are running a docker container in background and still if you want to see the console outputs, use the below command.</em></strong></li></ul><pre>docker logs $(sudo docker ps -aq --filter name=&lt;&gt;</pre><ul><li><strong><em>For live console output</em></strong></li></ul><pre>docker logs -f &lt;CONTAINER&gt;</pre><h3>Dynamically Change the Contents of the Running Container using Nodemon.</h3><p>For this, we need to implement something called volume mapping, for this to happen , you must map the volumes using docker-compose.</p><p>Add volume mapping to the docker-compose.yml</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5f1f7e88e17d775aea61aad3bd8beaba/href">https://medium.com/media/5f1f7e88e17d775aea61aad3bd8beaba/href</a></iframe><p>Now if we change a file in the local machine, it must be reflected on the docker containrer as well. This happens because we are mapping the volumes.</p><pre>volumes:<br> hostDir:WorkDir</pre><p>Now try chaning something in the server.js file and check whether your server.js restarts. If you are following this tutorial so far, it shouldn&#39;t restart the server yet since we didn’t use nodemon in the Dockerfile CMD. Let’s use it now.</p><pre><strong>CMD </strong>[&quot;npm&quot;, &quot;run&quot;, &quot;dev&quot;]</pre><p>After changing this. Once build the image using docker compose and then run it.</p><pre>docker-compose down<br>docker-compose build<br>docker-compose up</pre><p>Now change the server.js file and check if the server restarts. So if it’s restarting, you have successfully completed this tutorials.</p><p>So using this method, we can use docker for continuous development also. I have created a repository on <a href="https://github.com/rama41222/nodejs-docker-medium">github</a>. You may refer it.</p><p>Finally!!!! Go containers!!!. Ciaoo.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=22700b4105e4" width="1" height="1" alt=""><hr><p><a href="https://itnext.io/lets-dockerize-a-nodejs-express-api-22700b4105e4">Let’s Dockerize a Nodejs Express API</a> was originally published in <a href="https://itnext.io/">ITNEXT</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Let’s Create a Personalized Dashboard for GitHub]]></title>
            <link>https://medium.com/@rama41222/lets-create-a-personalized-dashboard-for-github-75b6f38c2c23?source=rss-addd29877f03------2</link>
            <guid isPermaLink="false">https://medium.com/p/75b6f38c2c23</guid>
            <category><![CDATA[authentication]]></category>
            <category><![CDATA[git]]></category>
            <category><![CDATA[data-visualization]]></category>
            <category><![CDATA[data-analysis]]></category>
            <category><![CDATA[oauth]]></category>
            <dc:creator><![CDATA[Dinushanka]]></dc:creator>
            <pubDate>Tue, 09 Oct 2018 17:58:36 GMT</pubDate>
            <atom:updated>2018-10-27T15:39:17.018Z</atom:updated>
            <content:encoded><![CDATA[<h3>Let’s Create a Personalized Dashboard for GitHub using Nodejs and NuxtJs</h3><h4>What is Authentication ?</h4><p>It’s a process of unique identifying a user. Here a user is verified through a trusted credential which determines whether they are authentic or not.</p><h4>What is Authorization ?</h4><p>It’s a way of declaring access to a certain protected resource.</p><h4>What is oAuth ?</h4><p>oAuth — which stands for Open Authorization is a framework to delegate authorization which helps to eliminate the need to provide the user credentials for 3rd party applications. This article is focused more on oAuth 2. OAuth 2 provides authorization flows for web and desktop applications, and mobile devices.</p><h4>OAuth Roles</h4><p>OAuth has 4 roles:</p><ul><li>Resource Owner</li><li>Client</li><li>Resource Server</li><li>Authorization Server</li></ul><p><strong>Resource owner — User</strong></p><p>The resource owner is the <em>user</em> who authorizes an <em>application</em> to access their account.</p><p><strong>Authorization Server</strong></p><p>This verifies the identity of the <em>user</em> then issues access tokens to the <em>application</em>.</p><p><strong>Resource Server</strong></p><p>This server hosts the protected resources. The basic idea is to gain access to the<em> protected resources</em> using the <em>permissions grated by a user</em> through a <em>client such as the github app </em>using an <em>Authorization server</em></p><p><strong>Client — Web app, mobile app etc.</strong></p><p>The client is the <em>application</em> that wants to access the <em>user</em>’s account.</p><p>The oAuth 2.0 is well defined in <a href="https://tools.ietf.org/html/rfc6749">RFC6749</a> Spec. If anyone wants to get a detailed understanding of oAuth 2.0, It’s better to go through this <a href="https://tools.ietf.org/html/rfc6749">specification</a></p><h4>Abstract Auth 2.0 Protocol Flow</h4><pre>     +--------+                               +---------------+<br>     |        |--(A)- Authorization Request -&gt;|   Resource    |<br>     |        |                               |     Owner     |<br>     |        |&lt;-(B)-- Authorization Grant ---|               |<br>     |        |                               +---------------+<br>     |        |<br>     |        |                               +---------------+<br>     |        |--(C)-- Authorization Grant --&gt;| Authorization |<br>     | Client |                               |     Server    |<br>     |        |&lt;-(D)----- Access Token -------|               |<br>     |        |                               +---------------+<br>     |        |<br>     |        |                               +---------------+<br>     |        |--(E)----- Access Token ------&gt;|    Resource   |<br>     |        |                               |     Server    |<br>     |        |&lt;-(F)--- Protected Resource ---|               |<br>     +--------+                               +---------------+</pre><p>The steps mentioned in the diagram is as follows</p><ol><li>The <em>application</em> requests authorization to gain access to the procected resources in the resource server from the user. WRT this application, the resource server is the GitHub API, the authorization server is the Nodejs API and the client is the Frontend created using NuxtJs.</li><li>If the <em>user</em> authorized the request, the <em>application</em> receives an authorization grant. In the case of this application, the app receives a code and a random string which should be sent to the authorization server to get an access token.</li><li>The <em>application</em> requests an access token from the <em>authorization server</em> (API) by presenting authentication of its own identity, and the authorization grant</li><li>If the application identity is authenticated and the authorization grant is valid, the <em>authorization server</em> (API) issues an access token to the application. Authorization is complete.</li><li>The <em>application</em> requests the resource from the <em>resource server</em> (API) and presents the access token for authentication.</li><li>If the access token is valid, the <em>resource server</em> (API) serves the resource to the <em>application.</em></li></ol><h4>What is a Authorization Grant</h4><p>Authorization grant is actually a way of obtaining authorization. In oAuth 2.0, there are 4 types of authorization grants suited for different situations. In our scenario we will be using the Authorization code grant type.</p><ul><li>Authorization Code: used with server-side Applications</li><li>Implicit: used with Mobile Apps or Web Applications (applications that run on the user’s device)</li><li>Resource Owner Password Credentials: used with trusted Applications, such as those owned by the service itself</li><li>Client Credentials: used with Applications API access</li></ul><p>So if you are interested in oAuth 2.0, go through the spec. it’s the best way to learn about it.</p><h4>Here’s the flow.</h4><p>There will be a login page. When the user clicks on the login button. it will redirect the user to the following endpoint</p><pre>http://localhost:3001/auth/github</pre><p>Then the request will go through passportjs middleware where the user is redirected to github from the authorization server. We will be using the passport-github strategy.</p><pre>passport.use(<strong>new </strong>GitHubStrategy({<br>    clientID: GITHUB_CLIENT_ID,<br>    clientSecret: GITHUB_CLIENT_SECRET,<br>    callbackURL: &quot;http://localhost:3001/auth/github/callback&quot;<br>  }, <strong>function </strong>(accessToken, refreshToken, profile, cb) {<br>    <strong>const </strong>user = {<br>      profile: profile,<br>      accessToken: accessToken,<br>      refreshToken: refreshToken<br>    };<br>    <strong>return </strong>cb(<strong>null</strong>, user);<br>  }<br>));</pre><p>When the request arrives at github along with the client secret and id, the Github will generate a access token, a refresh token and it will redirect the request to the callback url mentioned in the github app.</p><p>The sent access token can be used to acesss any resource in the github server. As for the sample app, we will use the access token provided by github directly. but in production apps, normally it’s good to exchange the github access token with a local access token rather than using the github access token.</p><p>Then this request will be redirected to the client side along with the access token.</p><pre>app.get(&#39;/auth/github/callback&#39;, passport.authenticate(&#39;github&#39;, { session: <strong>false </strong>,failureRedirect: &#39;/login&#39;}), (req, res) =&gt; {<br>  res.redirect(&#39;http://localhost:3000/callback?access_token=&#39;+ req.user.accessToken);<br>});</pre><p>The front end is using a middleware called “@nuxtjs/auth” to provide authenticatoin. The authtoken provided by the api will be saved in the froned end. and it will be used along with every service call which requests protected resources from github through the Nodejs API.</p><h4>Let’s start by creating a github oAuth App</h4><p>The goal of this article is to use the concepts of oAuth 2.0 and create a sample application to retrieve information from github. For this we’ll be needing a github application, a frontend to display the informaton retrieved from github and and a backend. since this is a sample application, I have followed some basic steps to create a sample API in a short time. The practices followed in the sample app shouldn’t be used in a production environment.</p><ol><li>In the upper-right corner of any page, click your profile photo, then click Settings.</li><li>In the left sidebar, click Developer settings.</li><li>In the left sidebar, click OAuth Apps.</li><li>Click New OAuth App.</li><li>In “Application name”, type the name of your app.</li><li>In “Homepage URL”, type the full URL to your app’s website. In my case it’s the <a href="http://localhost:3001/">http://localhost:3001</a> which is the address of my API</li><li>Optionally, in “Application description”, type a description of your app that users will see.</li><li>In “Authorization callback URL”, type the callback URL of your app. Callback url is where the authorization grant is returend. In this application it’s <a href="http://localhost:3001/callback.">http://localhost:3001/auth/github/callback.</a></li><li>Click Register application.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/575/1*2cl5t_5c3d-uD1PtOPQlRw.png" /><figcaption>The GitHub app I created for this project</figcaption></figure><p>Now we are done with the oAuth Application setup. Let’s create the frontend, backend and implement the required endpoints to retrieve data from github.</p><h4>Frontend</h4><p>Here’s how the ui should be.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xat0-lpoAGTRFeGMV87Xzw.png" /><figcaption>The Front page. (index.vue)</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7-CIleAshLkaK7UojYgWWg.png" /><figcaption>The Dashboard</figcaption></figure><p>You’ll need an extra page called callback.vue to receive the auth token from the authorization server. So the overall file structure should look like the following.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/331/1*iFr4IOtiEqWfE9SFtOjUbA.png" /></figure><p>To create this file structure easily i’ve used the quick starter guide given by NuxtJS. You can follow this tutorial to create a project like this easily using few commands. <a href="https://nuxtjs.org/guide/installation"><strong>[Nuxtjs Starter]</strong></a><strong>.</strong></p><p>Let’s create the index.vue page.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bf9025369de351817987353539030b7d/href">https://medium.com/media/bf9025369de351817987353539030b7d/href</a></iframe><p>Let’s create the dashboard.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/482497733b77becee679afc47714ba64/href">https://medium.com/media/482497733b77becee679afc47714ba64/href</a></iframe><p>And finally the callback.vue page</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3770f2a236bc081dd7e72869b3cd554e/href">https://medium.com/media/3770f2a236bc081dd7e72869b3cd554e/href</a></iframe><p>I have moved all the service calls to the nuxt store. To create the store, goto the folder store and create an index.js.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b6807f244f03fc3d9c0f5be6cf7b93a5/href">https://medium.com/media/b6807f244f03fc3d9c0f5be6cf7b93a5/href</a></iframe><p>These are the main files that’s necessary for you to create a dashboard as given in the above image. Now we are pretty much done with the frontend setup. Please refer the github repo if you fail to follow the tutorial. I’ve commited all the code.</p><p>Now we are done with the front end. Let’s move to the backend and implement the API endpoints necessary for authorizartion.</p><h4>Backend</h4><ol><li>Create a folder called server inside the vuejs project</li><li>Create an index js</li></ol><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3192371d5d18a00eecc2299256f5961f/href">https://medium.com/media/3192371d5d18a00eecc2299256f5961f/href</a></iframe><p>Yay! Finally we have create a simple application to authorize using githhub and retrieve protected resources.</p><h4>Let’s Finalize</h4><p>This is an example of how to use github api to delegate authorization using oAuth 2.0. You can clone this repo and further develop this into showing different data extracted from github. Download the sample <a href="https://github.com/rama41222/GithubStats">github repo</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=75b6f38c2c23" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Deep dive into CSRF Protection]]></title>
            <link>https://medium.com/@rama41222/a-deep-dive-into-csrf-protection-c7783d170357?source=rss-addd29877f03------2</link>
            <guid isPermaLink="false">https://medium.com/p/c7783d170357</guid>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[security]]></category>
            <category><![CDATA[csrf]]></category>
            <category><![CDATA[cookies]]></category>
            <category><![CDATA[sessions]]></category>
            <dc:creator><![CDATA[Dinushanka]]></dc:creator>
            <pubDate>Thu, 04 Oct 2018 18:00:32 GMT</pubDate>
            <atom:updated>2018-10-26T20:32:20.661Z</atom:updated>
            <content:encoded><![CDATA[<h4>Introduction</h4><p>A8 — Cross-Site Request Forgery (CSRF) was in OWASP top 10 back in 2013 but now it’s merged into A5- Broken access control. It’s a well known vulnerability that existed for years. The vulnerability is seen only in 3–4% of the applications as of today (2018) and it’s disappearing with the arrival of modern application frameworks. But the knowledge about CSRF vulnerability is vital when implementing modern day applications. CSRF protection is built into most of the modern day frameworks such as spring boot but some are using frameworks that has no built in csrf protection. That’s why we should deep dive into this vulnerability.</p><h4>How it works</h4><p>This attack happens in the client side. The user is lured to click a url or do some activity by an attacker where a request is triggered without the consent of the user. This can happen during a page load to user engaging with some element in a forged website. The client must have an <strong>active session</strong> within the browser for this to happen. The triggering request is sent to a server along with the active session, where the server thinks that this client is valid and executes the request. For example, an attacker can lure a user to rob the bank account.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PYmRxifPlT6_mFNoh5myZA.png" /></figure><ol><li>Client Clicks a link sent by the attacker.</li><li>Sends a request to the bank along with the session details.</li><li>bank server validates the request and executes it since the session is active.</li><li>Fund transfer takes place without the users consent.</li></ol><p>As mentioned above a browser typically sends the active sessions along with a request for a specific domain. This is one of the inherent properties of the browser which allows the CSRF vulnerability. Also the incorrect use of HTTP verbs leads to this problem.</p><p>[<strong> GET, HEAD, OPTIONS</strong> ] — Should be only used to read some resource but not to change the state of the resource.</p><p>[<strong> POST, PUT, PATCH, DELETE</strong> ] — Should be used to change the state of the server but not to read resources.</p><p>Since HTTP protocol is stateless, the application should store the user state to keep the user logged in. This information can be stored in local storage, in the session storage or as cookies. [ screenshot here ].</p><p><strong>LocalStorage:</strong></p><ol><li>Provides a great storage capacity.</li><li>The data is not sent back to the server for every HTTP request for a domain.</li><li>The data stored in localStorage persists until explicitly deleted.</li><li>Changes made are saved and available for all current and future visits to the site.</li><li>Data stored will only be available on the same origin.</li></ol><p><strong>Cookie storage:</strong></p><ol><li>Limited Storage, including name, value, expiry date etc.</li><li>Valid only for a certain period of time</li><li>The data is sent back to the server for every HTTP request according to the domain</li></ol><p><strong>SessionStorage:</strong></p><ol><li>It is similar to localStorage.</li><li>Changes are only available per window and tabs.</li><li>Once the window/tab is closed, the storage is deleted.</li><li>The data is available only inside the window/tab in which it was set.</li><li>The data is not persistent — Will be deleted when refreshed.</li><li>It’s available on the same origin.</li></ol><p>Out of these storages, cookie storage is the one which is normally used to store the session IDs. Cookie is automatically created in the client side when the request header is set as “Set-Cookie”.</p><pre>Set-Cookie: &lt;cookie-name&gt;=&lt;cookie-value&gt;</pre><p>There are 2 types of cookies.</p><ol><li>Session cookie — This cookie doesn’t specify a expiry time. These are deleted when the client closes the browser</li><li>Permanent cookie — Specifies a expiry time and is not deleted until expired</li></ol><p>These cookies have certain flags associated with them.</p><p>Httponly — The scripts can’t modify or access the cookies with this flag ( used to prevent xss attacks )</p><pre>console.log(Document.cookie);</pre><p>Secure — this cookies are sent only with https requests</p><p>SameSite — cookies let servers require that a cookie shouldn’t be sent with cross-site requests, which somewhat protects against cross-site request forgery attacks (<a href="https://developer.mozilla.org/en-US/docs/Glossary/CSRF">CSRF</a>). SameSite cookies are still experimental and not yet supported by all browsers.</p><p>Now, with every new request to the server, the browser will send back all previously stored cookies to the server using the <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Cookie">Cookie</a> header. Therefore an attacker and set up a malicious form in the background to do some malicious activity using this inherent feature of the browser.</p><pre>GET /sample_page.html HTTP/1.1<br>Host: <a href="http://www.example.org/">www.example.org</a><br>Cookie: x=abc</pre><p>Synchronizer token pattern — Allows user to submit the form over and over gain with the same csrf token. back button prompts user to resubmit the form. Cookie per browser. Token per tab</p><p>Double submit cookie pattern — Allows users to submit the form once.</p><p>You can download the sample project using the following github link.</p><pre>git clone <a href="https://github.com/rama41222/csrf">https://github.com/rama41222/csrf</a></pre><h4>to be continued…</h4><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c7783d170357" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Custom Social Auth flow with auth.nuxtjs.org]]></title>
            <link>https://itnext.io/custom-social-auth-flow-with-auth-nuxtjs-org-daa836676587?source=rss-addd29877f03------2</link>
            <guid isPermaLink="false">https://medium.com/p/daa836676587</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[vuejs]]></category>
            <category><![CDATA[nuxtjs]]></category>
            <category><![CDATA[nuxt]]></category>
            <category><![CDATA[authentication]]></category>
            <dc:creator><![CDATA[Dinushanka]]></dc:creator>
            <pubDate>Fri, 25 May 2018 18:48:55 GMT</pubDate>
            <atom:updated>2018-05-26T09:22:23.931Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/900/1*-lIXGHKlXNI-x4ECuQSFzw.png" /><figcaption><a href="https://entwickler.de/wp-content/uploads/2018/01/nuxt-900x450.png">source</a></figcaption></figure><p>The nuxt-auth module works great with local and social media logins but things get messay when you try to exchange social login tokens with your local API token. The nuxt auth module doesn’t support custom auth flows with social logins. Actually, what nuxt-auth does is, it logs you in with a social network but it doesn’t allow you to exchange the social token with your own token. Therefore I’ve created this tutorial to make things easy for you.</p><p>So here’s how to keep it clean. First, clone the base app from my github. This is from my previous tutorial on nuxt-auth module. <a href="https://medium.com/@rama41222/basic-authentication-using-auth-nuxt-js-e140859ab4c3">Check my ealier article on nuxt-auth for a detailed walk through on the downloaded project.</a></p><p>I have used epic-spinners for loading animations. You can install epic spinners using the following command.</p><pre>npm install --save epic-spinners</pre><p>Then create a plugin called spinners.js in the plugins folder to include epic spinners into your project.</p><pre>import Vue from &#39;vue&#39;<br>import { SemipolarSpinner } from &#39;epic-spinners&#39;</pre><pre>Vue.component(&#39;semipolar-spinner&#39;, SemipolarSpinner)</pre><p>Then include the plugin into nuxt.config.js</p><pre>plugins: [&#39;~plugins/spinners.js&#39;],</pre><h4>Let’s get Started with the auth flow</h4><p>Here’s what we are going to do. First we’ll let nuxt-auth plugin, login with a social network. Then we’ll obtain the token received with the callback from facebook, google or any other platform. Then we’ll send that token to our own server and exchange the social login token with a local token. Then we’ll forcefully set the local authtoken in nuxt-auth module. After doing so, we’ll have to change the strategy to local and finally you can fetch the local user from your own API. To make things clean, we’ll create a plugin for axios and include all the headers in the axios plugin. Then we’ll include the plugin ino the project.</p><h4>First</h4><p>You should change the nuxt.auth config to suite your auth flow. Here’s how I did it.</p><pre>auth: {<br>  strategies: {<br>    local: {<br>      endpoints: {<br>        login: {url: &#39;/user/login&#39;, method: &#39;post&#39;, propertyName:      &#39;token&#39; },<br>        logout: <strong>false</strong>,<br>        user: {url: &#39;/user/user&#39;, method: &#39;get&#39;, propertyName: &#39;data&#39;},<br>      },<br>      tokenRequired: <strong>true</strong>,<br>      tokenType: &#39;Bearer&#39;<br>    },<br>    facebook: {<br>      client_id: &#39;&#39;,<br>      userinfo_endpoint: <strong>false</strong>,<br>      scope: [&#39;public_profile&#39;, &#39;email&#39;],<br>      redirect_uri:&#39;http://localhost:3000/callback&#39;<br>    },<br>    google: {<br>      client_id: &#39;&#39;,<br>      user:<strong>false</strong>,<br>      redirect_uri:&#39;http://localhost:3000/callback&#39;<br><br>    },<br>  },<br>  redirect: {<br>    login: &#39;/?login=1&#39;,<br>    logout: &#39;/&#39;,<br>  }<br>},</pre><p>Then add your API endpoint to work as the base</p><pre>axios: {<br>     baseURL:&#39;<a href="https://aaa.com/api/v1&#39;">https://aaa.com/api/v1&#39;</a><br>  },</pre><p>I have purposefully removed the rest of the configuration. Refer the given github for complete configuration.</p><h4>Second</h4><p>Let’s setup axios. Here, i’ll create a plugin to keep all the headers in one place. To get started, create a file named axios.js in plugins and include it in the nuxt.config.js Here’s a look of the minimal nuxt config after including the relevent plugins.</p><pre>plugins: [‘~plugins/axios.js’,’~plugins/spinners.js’]</pre><p>Then put the following code into the axios.js in plugins folder.</p><pre>export default function ({$axios, redirect}) {<br>    $axios.onRequest(config =&gt; {<br>        config.headers[&#39;Content-Type&#39;] = &#39;application/json&#39;;<br>        config.headers[&#39;Access-Control-Allow-Origin&#39;] = &quot;*&quot;;<br>    })<br>}</pre><p>If you need more headers, just include them in the axios plugin and axios will automatically inject the headers when sending a request.</p><p>Now that we have setup axios. Let’s create the custom auth plugin. Create a new file called auth.js in the plugins folder and type the following code.</p><pre>export default async function ({ app }) {<br>    if (!app.$auth.loggedIn) {<br>        return<br>    }</pre><pre>const auth = app.$auth;</pre><pre>const authStrategy = auth.strategy.name;<br>    if(authStrategy === &#39;facebook&#39; || authStrategy === &#39;google&#39;){<br>        const token = auth.getToken(authStrategy).substr(7)<br>        const authStrategyConverted = authStrategy === &#39;facebook&#39; ? &#39;fb&#39; : &#39;google&#39;;<br>        const url = `/user/signup/${authStrategyConverted}?token=${token}`;</pre><pre>try {<br>            const {data} = await app.$axios.$post(url, null);<br>            auth.setToken(&#39;local&#39;, &quot;Bearer &quot;+ data.access_token);<br>            setTimeout( async () =&gt; {<br>                auth.setStrategy(&#39;local&#39;);<br>                setTimeout( async () =&gt; {<br>                    await auth.fetchUser();<br>                })<br>            });<br>        } catch (e) {<br>            console.log(e);<br>        }<br>    }<br>}</pre><p>As you know, the nuxt-auth module keeps the login state in $auth.loggedIn variable. Therefore, at first we have to check whether the user is already logged in. If not logged in, this method should exit. Remember what I told you earlier, We should let the nuxt-auth module login before we intervene. Then we’ll copy the logged status to a variable so that we don’t have to repeat $nuxt.auth around the code.</p><p>Then i’m accessing the strategy. This is important since we are customizing the social media auth flow. You can access the currently logged strategy from nuxt-auth via auth.strategy.name (app.$auth.strategy.name). We are doing this, only to allow social logins. Then get the saved social login access token from nuxt-auth via auth.getToken(authStrategy).substr(7). Here auth.getToken(‘strategy name’) is a default method built into nuxt-auth. Refer the documentation for more information.</p><pre>const authStrategyConverted = authStrategy === &#39;facebook&#39; ? &#39;fb&#39; : &#39;google&#39;;<br>const url = `/user/signup/${authStrategyConverted}?token=${token}`;</pre><p>Using the above code, I’m creating the url based on the strategy. Then send a post call to your endpoint to retrive a custom token and set the local token to Vuex via auth.setToken(‘strategy’, token) method. Your API must get the social token, retrive the relevent user information and issue a access token.<br>The strategy should be local here. Then change the strategy to local using auth.setStrategy(‘ strategy ‘) method.</p><p>Finally include this plugin to nuxtjs globally.</p><pre>plugins: [&#39;~plugins/auth.js&#39;,&#39;~plugins/axios.js&#39;,&#39;~plugins/spinners.js&#39;]</pre><p>Here is the github link of the repo. This is the end of this tutorial ❤</p><p><a href="https://github.com/rama41222/NuxtMedium.git">GITHUB REPO</a></p><pre>git clone <a href="https://github.com/rama41222/NuxtMedium.git">https://github.com/rama41222/NuxtMedium.git</a></pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=daa836676587" width="1" height="1" alt=""><hr><p><a href="https://itnext.io/custom-social-auth-flow-with-auth-nuxtjs-org-daa836676587">Custom Social Auth flow with auth.nuxtjs.org</a> was originally published in <a href="https://itnext.io/">ITNEXT</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Basic Authentication using auth.nuxt.js]]></title>
            <link>https://itnext.io/basic-authentication-using-auth-nuxt-js-e140859ab4c3?source=rss-addd29877f03------2</link>
            <guid isPermaLink="false">https://medium.com/p/e140859ab4c3</guid>
            <category><![CDATA[nuxtjs]]></category>
            <category><![CDATA[vuejs]]></category>
            <category><![CDATA[login]]></category>
            <category><![CDATA[authentication]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Dinushanka]]></dc:creator>
            <pubDate>Wed, 09 May 2018 17:55:49 GMT</pubDate>
            <atom:updated>2018-09-17T05:11:49.983Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yFoiGYKkJAzD7CewduwUVw.jpeg" /><figcaption><a href="https://cdn.scotch.io/38945/g8Bvdn8RQDxUZ2YTTZwC_Build%20a%20Server-Side%20Rendered%20Vue%20App%20with%20Nuxt.js.png.jpg">Souce</a></figcaption></figure><h3>Introduction</h3><p>Recently, I got to know an easy way to get through the authentication using the “auth-module” provided by nuxt js. You can have a look at the module at <a href="https://auth.nuxtjs.org/">https://auth.nuxtjs.org</a> .They’ve provided with some examples but this is how I implemented.</p><p>To get started, you have to install few modules including the vue-cli module.</p><pre>npm install -g vue-cli</pre><p>After installing the vue-cli you can start off with the boilerplate code provided by nuxtjs. Just input the below command and change the name of the project.</p><pre>vue init nuxt-community/starter-template &lt;project-name&gt;</pre><p>CD into the project directory and then do a npm install or yarn install. To start off the project you can do a npm run dev. All the commands that can be used is clearly given in the package.json file under “scripts”</p><pre>{<br> &quot;scripts&quot;: {<br>     &quot;dev&quot;: &quot;nuxt&quot;,<br>     &quot;build&quot;: &quot;nuxt build&quot;,<br>     &quot;start&quot;: &quot;nuxt start&quot;,<br>     &quot;generate&quot;: &quot;nuxt generate&quot;,<br>     &quot;lint&quot;: &quot;eslint --ext .js,.vue --ignore-path .gitignore .&quot;,<br>     &quot;precommit&quot;: &quot;npm run lint&quot;<br>  }<br>}</pre><p>Now our base project setup is completed.</p><h4>Getting Started with auth.nuxtjs</h4><p>To get started, you’ll need to install the following packages.</p><pre>npm install --save <a href="http://twitter.com/nuxtjs/auth">@nuxtjs/auth</a> <a href="http://twitter.com/nuxtjs/axios">@nuxtjs/axios</a> <a href="http://twitter.com/nuxtjs/toast">@nuxtjs/toast</a> bootstrap-vue</pre><p>I have selected<a href="https://bootstrap-vue.js.org/"> boostrap-vue </a>( ) for this tutorial. If you need you can use <a href="https://vuetifyjs.com/en/">vuetify</a> or any other UI framework. Remember to use the <a href="http://twitter.com/nuxtjs">@nuxtjs</a> based version of axios.</p><p>OK. Now we have to configure each package to work with nuxt js. So let’s get started with auth. Goto nuxt.config.js at the root of the project.</p><ol><li>Add the relevant modules</li></ol><pre>modules: [<br>    &#39;<a href="http://twitter.com/nuxtjs/axios">@nuxtjs/axios</a>&#39;,<br>    &#39;<a href="http://twitter.com/nuxtjs/auth">@nuxtjs/auth</a>&#39;,<br>    &#39;<a href="http://twitter.com/nuxtjs/toast">@nuxtjs/toast</a>&#39;,<br>    &#39;bootstrap-vue/nuxt&#39;<br>],</pre><p>2. Add the toast message Configurations</p><pre>toast: {<br>    position: &#39;top-right&#39;,<br>    duration: 2000<br>  }</pre><p>3. Add the axios baseURL. This will be your APIs base url</p><pre>axios: {<br> baseURL: ‘<a href="http://192.168.8.141:5000/api/v1&#39;">http://192.168.8.141:5000/api/v1&#39;</a><br> },</pre><p>4. Let’s setup the loading</p><pre>loading: {<br>    name: &#39;chasing-dots&#39;,<br>    color: &#39;#ff5638&#39;,<br>    background: &#39;white&#39;,<br>    height: &#39;4px&#39;<br> },</pre><p>5. Finally add the most important auth module configurations</p><pre>auth: {<br>    strategies: {<br>      local: {<br>        endpoints: {<br>          login: {url: &#39;/user/login&#39;, method: &#39;post&#39;, propertyName:    &#39;token&#39; },<br>          logout: false,<br>          user: {url: &#39;/user/user&#39;, method: &#39;get&#39;, propertyName: &#39;data&#39;},<br>        },<br>        tokenRequired: true,<br>        tokenType: &#39;Bearer&#39;<br>      },<br>      facebook: {<br>        client_id: &#39;your facebook app id&#39;,<br>        userinfo_endpoint: &#39;<a href="https://graph.facebook.com/v2.12/me?fields=about,name,picture{url},email&#39;">https://graph.facebook.com/v2.12/me?fields=about,name,picture{url},email&#39;</a>,<br>        scope: [&#39;public_profile&#39;, &#39;email&#39;]<br>      },<br>      google: {<br>        client_id: &#39;your gcloud oauth app client id&#39;<br>      },<br>    },<br>    redirect: {<br>      login: &#39;/?login=1&#39;,<br>      logout: &#39;/&#39;,<br>      user: &#39;/profile&#39;,<br>      callback:&#39;/&#39;<br>    }</pre><p>OK, Let’s go through the above configuration one by one. [ local, facebook, google, twitter, github oAuth ] are the authentication strategies included with the auth.nuxtjs module. Other than that you also can add custom stategies to the configuration. Refer the <a href="http://auth.nuxtjs.org/"><em>auth.nuxtjs</em></a> configuration for that.</p><p>If you take a look at the <em>local strategy,</em> there is a field called <strong>endpoints</strong>. The <strong>login</strong> endpoint refers to your API’s authentication route. <strong>Method</strong> parameter is a POST and the <strong>propertyName</strong> means where the access token is present in the response. For your reference, this is how the <strong>propertyName</strong> is set inside the auth.nuxtjs module.</p><pre>// Taken from the nuxt-auth</pre><pre>return this.ctx.app.$axios<br>      .request(_endpoint)<br>      .then(response =&gt; {<br>        if (_endpoint.propertyName) {<br>          return getProp(response.data, _endpoint.propertyName)<br>        } else {<br>          return response.data<br>        }<br>      })</pre><p>I got into a problem here. The auth token came as a header parameter and I couldn’t figure out a way to resolve this issue. So I changed the API. If you find a way to get through this issue, please mention in the comments.</p><p>Then you can use the <strong>logout</strong> field to define the logout url of your API. Since REST is stateless we wont need this. The <strong>user</strong> parameter helps to retrive the user information when logged in. You also can define the <strong>tokenType</strong> “Bearer”, then it will be prepend to the auth token.</p><p>Then let’s go through the <strong>facebook</strong> auth strategy. Here you only have to define the <strong>scope</strong>, <strong>clientId</strong> and the <strong>loginurl</strong>. I’ve used the facebook API version 2.12 but it will be deprecated soon. Same goes with google, twitter and github.</p><p>Then you have to specify the <em>redirect</em> urls. So in there, you can speficy the logout page url, user profile url and the callback url which will be used in social logins. So If you are having your own authflow, callback url will help you to exchange a social login token with an API generated token. Nuxt can listen to the url params using the following code.</p><pre>watch: {<br>    $route() {<br>      //do something with the url params set<br>    }<br>  },</pre><p>I’ll include the soucecode in my github at the end, So that you’ll see what I have done with the url params. Oh! and one last thing, don’t forget to create the index.js file under <strong><em>/store</em></strong> director to activate the Vuex store.</p><h3>Sample UI</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Q21hkOZvX4OyghPPtMLItA.png" /><figcaption>What we are making</figcaption></figure><p>Let’s build up a sample ui to test out the configuration. Delete all the default code in<em> index.vue</em> inside pages and now your<em> index.vue</em> should look like this.</p><pre>&lt;template&gt;<br>  &lt;section class=&quot;container&quot;&gt;<br>    &lt;div&gt;&lt;/div&gt;<br>  &lt;/section&gt;<br>&lt;/template&gt;</pre><p>Then lets create a <strong>beautiful</strong> <strong><em>form</em></strong>. Just <em>copy and paste</em> the given below code.</p><pre>&lt;template&gt;<br> &lt;section class=&quot;container&quot;&gt;<br>     &lt;div&gt;<br>       &lt;b-form&gt;<br>         &lt;b-form-group  description=&quot;Let us know your Email.&quot; label=&quot;Enter your Email&quot; label-for=&quot;username&quot;&gt;<br>           &lt;b-form-input id=&quot;username&quot; v-model=&quot;email&quot; type=&quot;email&quot; required&gt;&lt;/b-form-input&gt;<br>         &lt;/b-form-group&gt;<br>         &lt;b-form-group  description=&quot;Let us know your Password.&quot; label=&quot;Enter your Password&quot; label-for=&quot;pw&quot;&gt;<br>           &lt;b-form-input id=&quot;pw&quot; v-model=&quot;password&quot; type=&quot;password&quot;&gt; &lt;/b-form-input&gt;<br>         &lt;/b-form-group&gt;<br>         &lt;b-button-group size=&quot;sm&quot;&gt;<br>             &lt;b-button <a href="http://twitter.com/click">@click</a>=&quot;facebook&quot; variant=&quot;outline-success&quot;&gt;Facebook&lt;/b-button&gt;<br>             &lt;b-button <a href="http://twitter.com/click">@click</a>=&quot;login&quot; variant=&quot;outline-success&quot;&gt;Login&lt;/b-button&gt;<br>             &lt;b-button <a href="http://twitter.com/click">@click</a>=&quot;google&quot; variant=&quot;outline-success&quot;&gt;Google&lt;/b-button&gt;<br>             &lt;b-button <a href="http://twitter.com/click">@click</a>=&quot;logout&quot; variant=&quot;outline-success&quot;&gt;Logout&lt;/b-button&gt;<br>             &lt;b-button <a href="http://twitter.com/click">@click</a>=&quot;check&quot; variant=&quot;outline-success&quot;&gt;Check&lt;/b-button&gt;<br>             &lt;b-button to=&quot;/callback&quot; variant=&quot;outline-success&quot;&gt;Callback&lt;/b-button&gt;<br>           &lt;/b-button-group&gt;<br>       &lt;/b-form&gt;<br>     &lt;/div&gt;<br>    &lt;/section&gt;<br>&lt;/template&gt;</pre><pre>&lt;script&gt;</pre><pre>export default {<br> data() {<br>     return {<br>       email:&#39;&#39;,<br>       password:&#39;&#39;<br>     }<br>   },<br>  mounted() {},<br>  watch: {},<br>  components: {},<br>  methods: {<br>   google(){},<br>   facebook(){},<br>   login(){},<br>   logout(){},<br>   check(){},<br>  } <br>}</pre><pre>&lt;/script&gt;</pre><pre>&lt;style&gt;</pre><pre>.container {<br>   min-height: 100vh;<br>   display: flex;<br>   justify-content: center;<br>   align-items: center;<br>   text-align: center;<br> }</pre><pre>&lt;/style&gt;</pre><p>Given below are the method definitions</p><pre>google()- Google Login<br>facebook()- Facebook Login<br>login()- Local Authentication<br>logout() — Logout function<br>check() — Check whether the user is logged in or now. Check the console for the output</pre><p>Note that I’ve used bootstrap-vue to build the form. Now we are at the final step. Let’s create the methods required to login.</p><pre>async google(){<br>      await this.$auth.loginWith(&#39;google&#39;).catch(e =&gt; {<br>        this.$toast.show(&#39;Error&#39;, {icon: &quot;fingerprint&quot;});<br>      })<br>    },<br>    async facebook(){<br>       await this.$auth.loginWith(&#39;facebook&#39;).catch(e =&gt; {<br>        this.$toast.show(&#39;Error&#39;, {icon: &quot;fingerprint&quot;});<br>      })</pre><pre>},<br>    async login() {<br>      try {<br>        this.$toast.show(&#39;Logging in...&#39;, {icon: &quot;fingerprint&quot;});<br>        await this.$auth.loginWith(&#39;local&#39;, {<br>          data: {<br>            &quot;email&quot;: this.email,<br>            &quot;password&quot;: this.password<br>          }<br>        }).catch(e =&gt; {<br>          this.$toast.error(&#39;Failed Logging In&#39;, {icon: &quot;error_outline&quot;});<br>        });</pre><pre>if (this.$auth.loggedIn) {<br>          this.$toast.success(&#39;Successfully Logged In&#39;, {icon: &quot;done&quot;});<br>        }<br>      } catch (e) {        <br>          this.$toast.error(&#39;Username or Password wrong&#39;, {icon: &quot;error&quot;});<br>      }<br>    },<br>    check(){<br>      console.log(this.$auth.loggedIn)<br>    },<br>    logout() {<br>      this.$toast.show(&#39;Logging out...&#39;, {icon: &quot;fingerprint&quot;});<br>      this.$auth.logout()<br>    },</pre><p>I have used Google Material Icons as toast icons. You just have to put the material icons cdn under the <strong>links</strong> of the header field. Now we are almost done. To check wheter you have logged in or not, use the console. Check for the <strong>cookies</strong>, <strong>localStorage</strong>. Setting up all these things are done automatically by the nuxt-auth module itself.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XNuUixzpsPMoOMlWi94Gyw.png" /><figcaption>Vuex store after logging in with Gmail</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LIrzLMCgqWWGy99bOp0veg.png" /><figcaption>Cookies</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bt1eolR_mEYF6SFyZH88bQ.png" /><figcaption>localStorage after logging with Gmail</figcaption></figure><p>Create a page called <strong>callback.vue</strong> inside the pages and add the following code.</p><pre>&lt;template&gt;<br>  &lt;div&gt;<br>    &lt;h1&gt;You are Secure&lt;/h1&gt;<br>    &lt;b-button to=&quot;/&quot; variant=&quot;success&quot;&gt;Callback&lt;/b-button&gt;<br>  &lt;/div&gt;<br>&lt;/template&gt;<br>&lt;script&gt;</pre><pre>export default {<br>    middleware: [&#39;auth&#39;]<br>  }</pre><pre>&lt;/script&gt;</pre><pre>&lt;style scoped&gt;</pre><pre>&lt;/style&gt;</pre><p>Note that I have added a new middleware called [‘auth’]. Nuxt-auth module will automatically create a middleware for you, so that you don’t have to write your own middleware to check whether you are authenticated before redirecting to the page. This is the end of this tutorial. I’ll be doing more nuxt tutorials as I get time. Stay in touch ❤ . Special thanks goes to <a href="https://medium.com/u/e226e30be934">Rooshan Akthar</a> for introducing me to auth.nuxt.js</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e140859ab4c3" width="1" height="1" alt=""><hr><p><a href="https://itnext.io/basic-authentication-using-auth-nuxt-js-e140859ab4c3">Basic Authentication using auth.nuxt.js</a> was originally published in <a href="https://itnext.io/">ITNEXT</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Next-Gen Javascript]]></title>
            <link>https://itnext.io/next-gen-javascript-2697ab934ffd?source=rss-addd29877f03------2</link>
            <guid isPermaLink="false">https://medium.com/p/2697ab934ffd</guid>
            <category><![CDATA[generator]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[es6]]></category>
            <category><![CDATA[babel]]></category>
            <category><![CDATA[es7]]></category>
            <dc:creator><![CDATA[Dinushanka]]></dc:creator>
            <pubDate>Thu, 28 Dec 2017 19:27:49 GMT</pubDate>
            <atom:updated>2018-05-30T07:55:03.323Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/900/1*IC0WTFi9hrUW2XL-LxHO1w.jpeg" /><figcaption>ECMAScript is a standard which defines the featues of JS</figcaption></figure><h3>let and const over var</h3><p>let keyword allows you to define variables considering the block scope.</p><pre><strong>const </strong>letFunc = () =&gt; {<br>    <strong>let </strong>myLet = 1<br>    <strong>if</strong>(<strong>true</strong>) {<br>        <strong>let  </strong>myLet = 2<br>        console.log(myLet)<br>    }<br>    console.log(myLet)<br>}</pre><pre>letFunc()</pre><pre>// 2<br>// 1</pre><p>const keyword acts like final keyword in java. It tells you that the variable that is defined as const will not be changed again in the entire code.</p><pre>const myConst = &#39;I\&#39;m not gonna change&#39;</pre><p>var keyword on the otherhand considers the functional scope and it doesn’t care about the block scope. That means you can use var keyword to define global variables.</p><pre><strong>const </strong>varFunc = () =&gt; {<br>    <strong>var </strong>myVar = 1<br>    <strong>if</strong>(<strong>true</strong>) {<br>        <strong>var  </strong>myVar = 2<br>        console.log(myVar)<br>    }<br>    console.log(myVar)<br>}<br><br>varFunc()</pre><pre>// 2<br>// 2</pre><h3>Arrow Functions</h3><p>Arrow functions doesn’t replace the functions in js for few reasons</p><blockquote>Arrow functions don’t have their own this</blockquote><ol><li>this keyword always refers to something defined in the enviromnent that the arrow function is defined</li><li>Can’t use with new keyword</li></ol><pre><strong>function </strong>testScopeFunc() {<br>    console.log(<strong>this</strong>.amt)<br>    <strong>return </strong>{<br>        amt: 10,<br>        getAmt: () =&gt; console.log(<strong>this</strong>.amt)<br>    }<br>}<br><br>testScopeFunc.call({ amt: 2 }).getAmt()</pre><pre>// 2<br>// 2</pre><p>But when we use a ordinary function</p><pre><strong>function </strong>testScopeFuncNormal() {<br>    console.log(<strong>this</strong>.amt)<br>    <strong>return </strong>{<br>        amt: 10,<br>        getAmt: <strong>function</strong>() {<br>            &quot;use strict&quot;;<br>            console.log(<strong>this</strong>.amt)<br>        }<br>    }<br>}<br><br>testScopeFuncNormal.call({amt: 2}).getAmt()</pre><pre>// 2<br>// 10</pre><p>As you can see, the arrow function always refers to a fixed scope. Someting like when we use ‘this’ in java.</p><h4>How to use Arrow Functions</h4><ol><li>Single line</li></ol><pre>const myFunc = () =&gt; console.log(&#39;My Function&#39;)</pre><p>Here you don’t need the return keyword</p><p>2. Multi line</p><pre>const myFunc = () =&gt; { //Your Function body }</pre><p>3. Single argument</p><pre>const myFunc = arg =&gt; { // your func body}</pre><p>If you have more than one parameter or no paramets at all, you must use brackets () =&gt; {} syntax</p><h3>Export and Import</h3><p>When you write code in multiple files, you’ll have to import the function/functions written in one file to another. That’s where you need this.</p><h4>Export</h4><p>If you want to expose a single function from your file you can use the default export as given below</p><pre>export default myfunc</pre><p>But when you have multiple functions you may use the below syntax. We call this as a named export</p><pre>export const func1<br>export const func2</pre><h4>Import</h4><p>if you are using the default export as given above, you may use the below syntax</p><pre>import myfunc from &#39;./somefile&#39;<br>import person from &#39;./somefile&#39;</pre><p>If you are importing multiple functions you can use the below syntax</p><pre>import { func1 } from &#39;./somefile&#39;<br>import { func1, func2 } from &#39;./somefile&#39;<br>import { func1 as f1, func2 as f2 } from &#39;./somefile&#39;</pre><p>Or you can import all at one and use them as below</p><pre>import * as myFunctionPool from &#39;./somefile&#39;</pre><pre>// call seperate functions as <br>myFunctionPool.func1()<br>myFunctionPool.func2()</pre><h3>Classes</h3><p>Classes are blueprints for objects. They can have both properties and methods.</p><pre><strong>class </strong>Planet {<br>    constructor(){<br>        <strong>this</strong>.name = &#39;Earth&#39;<br>        <strong>this</strong>.age = 2300<br>    }<br>    getName() { console.log(<strong>this</strong>.name) }<br>}<br><strong>const </strong>earth = <strong>new </strong>Planet()<br>earth.getName()Spread and Rest Operators</pre><p>Classes supports inheritance</p><pre><strong>class </strong>SolarSystem {<br>    constructor(){<br>        <strong>this</strong>.galaxy = &#39;Milky way&#39;<br>    }<br>    getGalaxy() { console.log(<strong>this</strong>.galaxy)}<br>}<br><br><strong>class </strong>Planet <strong>extends </strong>SolarSystem{<br>    constructor(){<br>        <strong>super</strong>() // Have to call the super class in derived class    which executes the parent constructor<br>        <strong>this</strong>.name = &#39;Earth&#39;<br>        <strong>this</strong>.age = 2300<br>    }<br>    getName() { console.log(<strong>this</strong>.name) }<br><br>}<br><br><strong>const </strong>earth = <strong>new </strong>Planet()<br>earth.getName()<br>earth.getGalaxy()</pre><p>In<strong> ES7 </strong>you can skip the constructor function call and directly devrieve the properties within the class. Also you dont have to call the constructor of the superclass using <strong>super()</strong>.</p><pre><strong>class </strong>Water {<br>    ph = 6.97<br>    o2 = 22<br>}</pre><h3>Rest and Spread operators</h3><p>Rest and spread are denoted only by using 3 consecutive dots (…)</p><pre>... // This is basically the spread and rest operator</pre><ul><li>Spread — Used to split up array or object properties to make new arrays or objects</li><li>Rest — Used to aggregate multiple arguments of a function to an array</li></ul><h4>Spread operator uses</h4><pre><strong>let </strong>myArr = [1,2,3]<br><strong>let </strong>myNewArray = [...myArr, 4, 5]<br>console.log(myNewArray) // [ 1, 2, 3, 4, 5 ]</pre><p>The spread operator also can be used with objects</p><pre><strong>const </strong>leaf = {<br>    color:&#39;green&#39;,<br>}<br><br><strong>const </strong>tree = {<br>    ...leaf,<br>    leaves: 23,<br>}</pre><pre>console.log(tree)</pre><p>Rest operator uses</p><pre><strong>function </strong>arguments(...args) {<br>    <strong>for</strong>(<strong>let </strong>arg <strong>of </strong>args){<br>        console.log(arg)<br>    }<br>}<br><br>arguments(1,2,3,4,5,6)</pre><p>Here the arguments we pass to the function will be push to an array which can be accessible using the index</p><h3>Destructuring</h3><p>Used to extract properties or elements from objects and arrays respectively.</p><p>In arrays, the order of the elements define the object we extract and in objects the property name defines what we extract</p><pre>{ name, age } = { name: &#39;me&#39;, age:22 }<br>console.log(name) // me</pre><p>For arrays</p><pre>[x,,z] = [1, 2, 3]<br>console.log(x) // 1<br>console.log(z) //3</pre><p>Well these are some few newly introduced things to the lastest version of js. But there are other important features such as the <strong>for — of loops</strong>, <strong>generator functions</strong> which stores an state within the function when yeild (pause)<strong>, async await </strong>which replaced the use of promises and callbacks etc. Finally clap if you like this article.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2697ab934ffd" width="1" height="1" alt=""><hr><p><a href="https://itnext.io/next-gen-javascript-2697ab934ffd">Next-Gen Javascript</a> was originally published in <a href="https://itnext.io/">ITNEXT</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Javascript closures —An Angular approach]]></title>
            <link>https://medium.com/@rama41222/javascript-closures-an-angular-approach-3764d13ca21b?source=rss-addd29877f03------2</link>
            <guid isPermaLink="false">https://medium.com/p/3764d13ca21b</guid>
            <category><![CDATA[modular]]></category>
            <category><![CDATA[angularjs]]></category>
            <category><![CDATA[closure]]></category>
            <category><![CDATA[folder-structure]]></category>
            <category><![CDATA[best-practices]]></category>
            <dc:creator><![CDATA[Dinushanka]]></dc:creator>
            <pubDate>Sun, 26 Nov 2017 18:07:14 GMT</pubDate>
            <atom:updated>2017-11-26T18:18:13.445Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/677/1*lhvYafVsaf4hEObCYY6IYA.png" /></figure><blockquote>A <strong>closure</strong> is the combination of a function enclosed with references to its surrounding state . In other words, a closure gives you access to an outer function’s scope from an inner function. In JavaScript, closures are created every time a function is created, at function creation time.</blockquote><h3>One big monolithic app</h3><p>Let’s create a module in angular</p><pre>// Below code is a setter which instantiate an angular module</pre><pre>angular.module(‘app’, [‘ui.router’,’toaster’,’ngAnimate’,’chart.js’]);</pre><p>The above approach is used best when you are creating a monolithic angular application where your application consists only a one big module and all the controllers, configurations, the routes, directives, factories, and the services are linked together.</p><p>but if you wish to create an angular app where there’s separation of concerns. You’ll definitely have to breakdown your application into reusable modules.</p><h3>The modular way of doing things</h3><pre>(function () {</pre><pre>‘use strict’ <br> angular.module(‘app’, [‘ui.router’,’toaster’,’ngAnimate’])</pre><pre>})();</pre><p>but wait. when you do it like this your app can’t be accessed from the global scope. Then you’ll have to turn the whole app into a collection of modules.</p><pre>(function () {</pre><pre>‘use strict’;</pre><pre>var app = angular.module(‘justforfunApp’, [“ui.router”,”toaster”,”ngAnimate”,”chart.js” ])</pre><pre>})()</pre><pre><em>//Below code won’t execute since the app can’t be accessible from the global scope</em></pre><pre><em>app.run(function ($window) {</em></pre><pre><em>// some operations here</em></pre><pre><em>})</em></pre><h3>But why ?</h3><p>If you declare the app variable as a global then your variable maybe conflict with other javascript variable with the similar name. So if you are making the application as reusable components. Probably your components should’t be conflicting with the rest of the code. That’s why we use this kinda approach</p><p>There are few good examples <a href="https://www.w3schools.com/js/js_function_closures.asp">here</a></p><h3>The better way</h3><p>To show how its done, I’ve created a sample angular application. The modules are categorized based on the features/functionality (customer, administrator) rather than the type (models, views and controllers)</p><p>I followed the LIFT principle</p><p>L — Locating your code</p><p>I — Identifying the code at a glance</p><p>F — Flat file structure</p><p>T — Try to stay dry (Don’t repeat yourself)</p><p>Sample code @ <a href="https://github.com/rama41222/AngularModularSampleApp">https://github.com/rama41222/AngularModularSampleApp</a></p><h3>Finally, there are no rules</h3><p>There are no hard and fast rules of coding. The best way is the way you feel more comfortable.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3764d13ca21b" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>