<?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 Leonardo Grade on Medium]]></title>
        <description><![CDATA[Stories by Leonardo Grade on Medium]]></description>
        <link>https://medium.com/@leograde?source=rss-1db23bae54f6------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*vHE4gg7o1b-ADD3GOosuIA.jpeg</url>
            <title>Stories by Leonardo Grade on Medium</title>
            <link>https://medium.com/@leograde?source=rss-1db23bae54f6------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 22 Nov 2026 04:08:00 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@leograde/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[Does JavaScript Pass by Value or Reference?]]></title>
            <link>https://medium.com/codetobits/does-javascript-pass-by-value-or-reference-ab50355ea42e?source=rss-1db23bae54f6------2</link>
            <guid isPermaLink="false">https://medium.com/p/ab50355ea42e</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[en]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Leonardo Grade]]></dc:creator>
            <pubDate>Wed, 04 Jul 2018 01:12:32 GMT</pubDate>
            <atom:updated>2018-07-04T02:05:03.405Z</atom:updated>
            <content:encoded><![CDATA[<h4>This is a common question that I will attempt to answer in a simple manner, with a few examples.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rfqQ0kqqDsibjHJE4bexag.jpeg" /></figure><p>First of all, it&#39;s good to remember that in JavaScript all variables refer to values. These values can be mutable (Objects and Arrays) or immutable (primitives such as booleans, strings and numbers).</p><pre>/* Immutable */<br>let a = 10; // 10 is always 10</pre><pre>a = 8; // this does not change 10 into 8, but instead makes the variable a point to a different primitive, in this case, 8.</pre><pre>/* Mutable */<br>let b = { name: &#39;Mary&#39;, age: 20 }; // b refers to an Object</pre><pre>b.name = &#39;Celine&#39;; // this changes the Object</pre><pre>b = {name: &#39;Russ&#39;, age: 70}; // this makes the variable b point to a new object</pre><p>When a variable that points to a primitive such as &quot;La La Land&quot; is passed into a function, the actual value &quot;La La Land&quot; is copied and associated with a local variable inside the function.</p><pre>let movie = &#39;La La Land&#39;;</pre><pre>function changeMovie(mov) {<br>  /* var mov = &#39;La La Land&#39;; (this is the equivalent of what happens behind the scenes) */<br>  mov = &#39;Moonlight&#39;; <br>}<br>console.log(movie); // prints &#39;La La Land&#39;</pre><p>In the example above, we can see how we don&#39;t have access to the variable movie, but instead to the primitive value &#39;La La Land&#39; that is copied into a new local variable inside the function. When we reassign the variable mov with mov = &#39;Moonlight&#39;; we are only changing the value of mov, not movie.</p><pre>let actress = {<br>  name: &#39;Emma Stone&#39;<br>};</pre><pre>function changeActress(act) {<br>  /* creates a local variable act that points to the same object that the variable actress points to. */<br>  act.city = &#39;Arizona&#39;;<br>}<br>changeActress(actress);<br>console.log(actress); // { name: &#39;Emma Stone&#39;, city: &#39;Arizona&#39; }</pre><p>In the script above, the local variable act inside the function points to the exact same object as actress . This happens because mutable objects are passed by reference. Therefore, adding a property city does indeed reflect on the same Object actress refers to. However, as we can see in the example below, we cannot change what the variable actress points to.</p><pre>let actress = {<br>  name: &#39;Emma Stone&#39;<br>};</pre><pre>function changeActress(act) {<br>  act = { name: &#39;Jennifer Lawrence&#39; }<br>}<br>changeActress(act);<br>console.log(actress); // { name: &#39;Emma Stone&#39; }</pre><p>It doesn&#39; matter whether the variable points to a primitive or an object, when you pass it into a function, the function can&#39;t make it point to a new primitive or object.</p><p>To sum it up:</p><ul><li>JavaScript values can be mutable (objects and arrays) or immutable (strings, booleans or numbers);</li><li>When you pass a variable that points to a primitive such as &#39;hi&#39;, the value is copied into a new local variable inside the function.</li><li>When you pass a variable that points to an object, the reference to the object is passed into the function so a new local variable points to the same object.</li><li>You can&#39;t, using only the argument, change what the external variable that was passed in points to.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ab50355ea42e" width="1" height="1" alt=""><hr><p><a href="https://medium.com/codetobits/does-javascript-pass-by-value-or-reference-ab50355ea42e">Does JavaScript Pass by Value or Reference?</a> was originally published in <a href="https://medium.com/codetobits">codetobits</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Dealing with NaN in JavaScript]]></title>
            <link>https://medium.com/codetobits/dealing-with-nan-in-javascript-320e3eca9a1a?source=rss-1db23bae54f6------2</link>
            <guid isPermaLink="false">https://medium.com/p/320e3eca9a1a</guid>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[en]]></category>
            <category><![CDATA[javascript-tips]]></category>
            <dc:creator><![CDATA[Leonardo Grade]]></dc:creator>
            <pubDate>Mon, 18 Jun 2018 21:25:09 GMT</pubDate>
            <atom:updated>2018-06-21T20:10:36.734Z</atom:updated>
            <content:encoded><![CDATA[<p>I believe we, developers, have all experienced a few confusing moments while developing in JavaScript. Dealing with <em>NaN</em> seems to be one of them.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1hq-jtWGmL7mNMXEXDfvSw.jpeg" /><figcaption>Trying to hide from weird JS concepts</figcaption></figure><p><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/NaN">MDN</a> defines <em>NaN</em> as being a global property that represents <em>Not-a-Number. </em>With the <em>typeof </em>operator, we can check that <em>NaN </em>is of the primitive Data Type <em>Number</em>.</p><pre>typeof NaN; //&quot;number&quot;<br>typeof 0; //&quot;number&quot;</pre><p>Usually, we have to deal with <em>NaN</em> when <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math">Math</a> functions fail or when trying to parse a number fails, like shown below.</p><pre>Math.round(&#39;a&#39;); //NaN<br>parseInt(&#39;b&#39;); //NaN</pre><p>Well, so far everything seems ok. However, how do we know if a returned value is <em>NaN</em>? As we saw previously, <em>typeof NaN </em>is of<em> </em>Number<em>, </em>but <em>typeof 0 </em>is also of Number. This means that the operator <em>typeof </em>won&#39;t tell us specifically if the value we&#39;re checking is <em>NaN.</em></p><pre>typeof NaN === &quot;number&quot;; //true<br>typeof 0 === &quot;number&quot;; //true</pre><p>So, if we can&#39;t use the operator <em>typeof, </em>what can we do to check if a value is <em>NaN</em>? The answer to this question may seem very simple. Why don&#39;t we compare the returned value to <em>NaN</em>. If it is <em>NaN</em> we&#39;ll get <em>true</em>, otherwise we&#39;ll get <em>false</em> and know that it isn&#39;t <em>NaN</em>. Let&#39;s try:</p><pre>Math.round(&#39;a&#39;) == NaN; // false</pre><p>Wait. What? But… we know that <em>Math.round(&#39;a&#39;)</em> results in <em>NaN</em>. How can <em>NaN == NaN</em> return <em>false</em>?</p><p><em>NaN</em> is the only value in JavaScript that when compared to itself returns <em>false</em>. As weird as it seems, at least now we have a way to identify when a value is <em>NaN</em>.</p><pre>let roundNum = Math.round(&#39;a&#39;); // roundNum is assigned NaN<br>roundNum == roundNum; // false</pre><pre>let roundNum2 = Math.round(1.3); // roundNum2 is assigned 1<br>roundNum2 == roundNum2; // true</pre><p>Yes, I know this is very confusing, but bare with me. In the example above, <em>roundNum</em> is <em>NaN </em>because when we compare roundNum for equality with itself, the result is <em>false</em>. As we learned before, that only happens with <em>NaN</em>. In the second case, <em>roundNum2</em> isn&#39;t <em>NaN</em>, because when compared to itself the result was <em>true</em>.</p><h3>isNaN()</h3><p>As it turns out, JavaScript has a function that helps us identify when a value is <em>NaN</em>. Well, let&#39;s try it out!</p><pre>isNaN(&#39;lalala&#39;); // true<br>isNaN(&#39; &#39;); // false</pre><p>You may be confused again. &#39;lalala&#39; and &#39; &#39; are both strings. Why is the former considered <em>NaN</em> and the latter not? One thing to pay attention to is that, depending on the input type, the function will try to use coercion and then check if the coerced value is <em>NaN. </em>It sort of looks like this:</p><pre>function isNaN(arg) {<br>  let coercedValue = Number(arg);<br>  return coercedValue != coercedValue;<br>}</pre><pre>// This is what really happens under the hood<br>// isNaN(&#39;lalala&#39;) -&gt; Number(&#39;lalala&#39;) -&gt; NaN =&gt; (NaN != NaN) -&gt;true<br>// isNaN(&#39; &#39;) -&gt; Number(&#39; &#39;) -&gt; 0 -&gt; (0 != 0) -&gt; false</pre><p>Also, remember that you are checking if a certain value is <em>NaN,</em> <a href="https://stackoverflow.com/a/25176685/5959721">which does not simply mean “this value is not a number”. It specifically means “this value is a <em>numeric</em> Not-a-Number value according to IEEE-754”</a>.</p><h3>Number.isNaN()</h3><p>This is a relatively new feature specified in ECMAScript 2015 (ES6) and brings one major difference from the regular <em>isNaN(): </em><strong>the argument doesn&#39;t get forcefully coerced</strong><em>. </em>This means that this function now compares if the value passed (as is) is <em>NaN</em>.</p><pre>isNaN(&#39;lalala&#39;); // true<br>Number.isNaN(&#39;lalala&#39;); // false</pre><p>What happens here is that in the first case, the function <em>isNaN()</em> tries to forcefully coerce &#39;lalala&#39; into a number. As a result of a failed calculation, <em>NaN</em> is returned and then it is checked against <em>NaN, </em>returning true.</p><p>However, in the second case, the function Number.isNaN() doesn&#39;t try to forcefully convert the parameter to a number. Instead, it simply checks whether the input value is <em>NaN</em> or not.</p><h3>Conclusion</h3><p>This topic can get very confusing, but overall remember that <em>NaN</em> is a value of type <em>Number;</em> it usually appears when a Math method calculation fails, and its comparison to itself is false (<em>NaN == NaN</em> = <em>false</em>). There&#39;s a function called <em>isNaN()</em> that coerces the parameter to a number before comparing against <em>NaN. </em>To have a more robust solution, ES6 brought in <em>Number.isNaN(</em>) that returns whether a parameter is <em>NaN</em> without going through any forceful coercion.</p><p>Finally, if you&#39;d like to check if a certain value &quot;is not a number&quot; instead of <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/NaN"><em>NaN</em></a>, don&#39;t use isNaN()<em>, </em>simply use<em> typeof variable !== &#39;number&#39;.</em></p><p>Hope this was useful. Happy coding! :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=320e3eca9a1a" width="1" height="1" alt=""><hr><p><a href="https://medium.com/codetobits/dealing-with-nan-in-javascript-320e3eca9a1a">Dealing with NaN in JavaScript</a> was originally published in <a href="https://medium.com/codetobits">codetobits</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Is React Native even worth it?]]></title>
            <link>https://medium.com/codetobits/is-react-native-even-worth-it-89ee12fb6e2d?source=rss-1db23bae54f6------2</link>
            <guid isPermaLink="false">https://medium.com/p/89ee12fb6e2d</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[react-native]]></category>
            <category><![CDATA[en]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <dc:creator><![CDATA[Leonardo Grade]]></dc:creator>
            <pubDate>Thu, 05 Apr 2018 15:37:09 GMT</pubDate>
            <atom:updated>2018-04-23T16:59:13.010Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/796/1*7k2S0DFJalxTFU0S_-u0CQ.png" /></figure><p>Recently, I was presented with quite a challenge. The company I work for let go our Senior Mobile Developer and now needed me to develop a new mobile app with resources similar to <a href="https://play.google.com/store/apps/details?id=com.ubercab.driver&amp;hl=en">Uber Driver</a>. The most important feature was tracking the users even when they decided to leave the app in background.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/650/1*kNLrUZl2VU_w_vZoHTDQFg.jpeg" /><figcaption>When the user decided to go online we needed to track him even in background.</figcaption></figure><p>If you’re a mobile developer, native or not, it probably doesn&#39;t sound too difficult. However, I hadn&#39;t developed any serious mobile app before and didn&#39;t know exactly how to proceed. As I have been creating web apps in JavaScript for the past 3 years and having observed how much React Native has matured over this time, I thought it was time to give it a try.</p><h3>The Basics</h3><p>I started out on <a href="https://facebook.github.io/react-native/">Facebook&#39;s React Native Docs</a> as most people do, but soon realized how difficult it would be to build what I needed at the speed I was required to with the docs alone. The content is perfectly fine, though it&#39;s hard to grow your app out of the basics, specially when you don&#39;t know, for example, how to even structure your folders properly.</p><p><a href="https://facebook.github.io/react-native/docs/getting-started.html">Getting Started · React Native</a></p><h3>What to do now?</h3><p>That’s when I decided to purchase <strong>Maximilian Schwarzmüller&#39;s </strong>React Native - The Practical Guide course.</p><p><a href="https://www.udemy.com/react-native-the-practical-guide/">React Native - The Practical Guide | Udemy</a></p><p>My goal here isn&#39;t to review this course or even go so much in depth about it, but if you&#39;re starting out, I would truly recommend it. The main reason is because it helps you to scaffold a RN app without any templates. I believe that you will have a better understanding of your app if you understand why things are structured the way they are, instead of grabbing something that is already built halfway for you. I&#39;d recommend using a template only after you learned how to build an app without one.</p><p>After having gone through the course, I could finally develop the app my company needed me to. Of course, I still had to read a lot of documentation online for dependencies such as <a href="https://github.com/wix/react-native-navigation">react-native-navigation</a>, <a href="https://github.com/mauron85/react-native-background-geolocation">react-native-background-geolocation</a>, <a href="https://github.com/zo0r/react-native-push-notification">react-native-push-notification</a>, <a href="https://github.com/react-community/react-native-maps">react-native-maps</a> and a few others.</p><p>This relatively small journey allowed me to gain a few insights of how it feels to develop Native apps in RN.</p><h3>A few insights about RN in this experience:</h3><ol><li>React Native is<strong> great for building rich and beautiful UIs</strong>. The Senior Mobile Developer I worked with used to complain a lot about building UIs in Xamarin, for example. It was almost impossible for him to see visual changes quickly. In RN, if you enable hot reloading, you can see visual changes instantaneously on your simulator or even on your physical device.</li><li><strong>It allows you to write JavaScript</strong>. Love it or hate it, JavaScript is here to stay. The amount of tools and libraries out there is immense, and there is a vast community constantly contributing to an already large pool of native modules. Also, because JavaScript is everywhere (Backend, Frontend, Mobile), it allows more people on your team to help out or at least understand a little bit of what&#39;s going on in the code.</li><li><strong>Components everywhere. </strong>What I love about React in general is that nearly everything could become a component. It is great for reusability, even across projects. Therefore, you could also easily bring in third party components like the ones offered by <a href="https://github.com/react-native-training/react-native-elements">react-native-elements</a>. Simply import your component and use it. Awesome!</li><li><strong>It’s constantly evolving. </strong>This is good, but also hard. You’ll probably spend 30% to 40% of your development time keeping up with new versions, reading source code or going through issues in repos. Installing new dependencies becomes a nightmare. It’s almost like you know beforehand that whenever you&#39;re done installing a new library you will run into some sort of problem. In my experience, the conflict among Gradle versions for the android dependencies become a huge headache.</li></ol><p>So it is not without problems, but I would strongly recommend anyone wanting to release apps in a fast manner to use React Native. I had a few headaches with keeping up with the dependencies, but as time passes they all become more and more mature, after all RN is still in version 0.54.</p><p>Good luck, y&#39;all!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=89ee12fb6e2d" width="1" height="1" alt=""><hr><p><a href="https://medium.com/codetobits/is-react-native-even-worth-it-89ee12fb6e2d">Is React Native even worth it?</a> was originally published in <a href="https://medium.com/codetobits">codetobits</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Autenticação e Autorização no LoopBack]]></title>
            <link>https://medium.com/codetobits/autentica%C3%A7%C3%A3o-e-autoriza%C3%A7%C3%A3o-no-loopback-9e2bed2072c8?source=rss-1db23bae54f6------2</link>
            <guid isPermaLink="false">https://medium.com/p/9e2bed2072c8</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[pt]]></category>
            <category><![CDATA[authorization]]></category>
            <category><![CDATA[loopback]]></category>
            <dc:creator><![CDATA[Leonardo Grade]]></dc:creator>
            <pubDate>Wed, 04 Apr 2018 20:54:03 GMT</pubDate>
            <atom:updated>2018-05-30T16:13:15.438Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oNAGHnNLS2WGELQVptBdbw.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/photos/FqaybX9ZiOU?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">James Sutton</a> on <a href="https://unsplash.com/search/photos/security?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>O objetivo desse artigo é auxiliar quem (ou o quê) consegue acessar determinados serviços/recursos através do framework <a href="https://loopback.io/doc/index.html">LoopBack</a>.</p><p>O principal funcionamento do LoopBack é através da criação de modelos. A maneira mais simples de se criar um modelo ocorre através do comando <strong>lb model nomeDoModelo</strong>. Para isso é necessário instalar o <a href="https://github.com/strongloop/loopback-cli">LoopBack Cli</a>. Após definir o <strong><em>DataSource</em></strong> (onde os dados do modelo serão persistidos) e as <strong><em>properties</em></strong><em>, </em>cria-se um arquivo <em>nomeDoModelo.json</em> e outro <em>nomeDoModelo.js</em>.</p><p>Logo em seguida, inicie o servidor com <strong><em>node . </em></strong>e visualize as rotas HTTP disponíveis através do <a href="http://localhost:3000/explorer.">http://localhost:3000/explorer.</a> Perceba que o LoopBack criou automaticamente as rotas CRUD daquele modelo. O que faremos a partir daqui é restringir o acesso de determinadas rotas dependendo de quem ou o quê as esteja utilizando.</p><h3>Habilitar Autenticação</h3><p>Antes de mais nada, é preciso ter certeza que a autenticação do seu servidor está habilitada. Para isso, verifique se já possui um arquivo chamado <em>authentication.js </em>dentro do diretório <em>/server/boot</em>. Caso esse arquivo não exista, crie-o com um <strong>script abaixo </strong>que chama o método <strong>enableAuth()</strong> do <strong>server</strong>.</p><pre>// authentication.js</pre><pre>module.exports = function enableAuthentication(server) {</pre><pre>  server.enableAuth();</pre><pre>};</pre><h3>Conceitos de Controle de Acesso</h3><p>O LoopBack possui quatro conceitos para lidar com ACL. São eles <strong><em>Principal</em>, <em>Role</em>, <em>RoleMapping</em> e <em>ACL</em>. </strong><a href="https://loopback.io/doc/en/lb2/Authentication-authorization-and-permissions.html">Leia mais</a>.</p><h3>Principal</h3><p>Simplesmente identifica uma entidade que faz alguma requisição para acessar recursos. Na prática, um <strong><em>Principal</em></strong> pode ser um <strong>usuário</strong> ou uma <strong>aplicação </strong>tentando acessar os recursos oferecidos pelo seu servidor.</p><h3>Role</h3><p>Já a <strong><em>Role</em></strong>, identifica um grupo de <strong><em>Principals</em></strong> com as mesmas permissões. Uma <strong><em>Role</em></strong> pode ser estática, sendo criada no Banco de Dados e associada a determinados usuários, ou dinâmica, sendo avaliada de acordo com a situação durante o acesso ao recurso. Por padrão, o LoopBack possui as seguintes <strong>roles</strong> dinâmicas:</p><ul><li><strong>$everyone</strong> — representa todos os usuários</li><li><strong>$authenticated</strong> — representa apenas os usuários que possuem um AccessToken válido</li><li><strong>$unauthenticated</strong> — representa apenas os usuários que não possuem um AccessToken válido</li><li><strong>$owner</strong> — representa usuários que são donos daquele determinado recurso</li></ul><h3>RoleMapping</h3><p>O <strong><em>RoleMapping</em></strong> é uma tabela no BD responsável pela associação entre Roles estáticas (criadas na tabela Role do BD) e Usuários/Principals (também em uma tabela no BD).</p><h3>ACL</h3><p>Por último, a <strong><em>ACL</em></strong> controla o que determinadas <strong><em>Roles</em></strong> conseguem fazer com os recursos daquele <strong><em>Model</em></strong>. Existe uma lista de <strong><em>acls </em></strong>declarada dentro do arquivo do (seu modelo).json. Lá é possível declarar o que cada <strong><em>Role</em></strong> consegue fazer naquele <strong><em>Model</em></strong>.</p><h3>Saindo da Teoria</h3><p>Vamos dizer que precisamos de uma aplicação onde os usuários consigam criar e visualizar o nome de suas músicas favoritas.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*x-d5cuKYe_f8BVSmSYiawA.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/photos/PDX_a_82obo?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Malte Wingen</a> on <a href="https://unsplash.com/search/photos/music?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>É possível identificar dois modelos: <strong>Usuário</strong> e <strong>Música</strong>.</p><p>Os dados de um <strong>Usuário</strong> são privados e apenas ele deve conseguir ler, alterar e deletar suas informações.</p><p>Para atingir esse objetivo, no arquivo <strong><em>Usuario.json</em></strong> criamos um objeto com as definições de autorização dentro da lista de <strong><em>acls</em></strong>, como no exemplo a seguir.</p><pre>// Usuario.json<br>{<br>   &quot;acls&quot;: [</pre><pre>    {<br>       &quot;accessType&quot;: &quot;*&quot;,<br>       &quot;principalType&quot;: &quot;ROLE&quot;,<br>       &quot;principalId&quot;: &quot;$everyone&quot;,<br>       &quot;permission&quot;: &quot;DENY&quot;<br>     }<br>   ]<br>}</pre><p>Quando algum <strong>Principal </strong>realiza uma requisição em uma rota pertencente ao modelo <strong>Usuario</strong>, o LoopBack percorre a lista de <strong>acls </strong>e verifica em cada iteração se esse <strong>Principal </strong>participa da <strong>Role</strong> declarada. Caso ele participe, o LoopBack verifica o tipo de acesso e a permissão.</p><p>Por exemplo, ao percorrer o primeiro item da lista de <strong>acls</strong>, o LoopBack verifica se o <strong>Principal</strong> pertence a role dinâmica <strong>$everyone</strong>. Como todos os principals pertencem automaticamente a essa role, ele vai em frente e verifica o tipo de acesso (*) que significa todos os recursos e verifica a permissão (DENY) que nega o acesso. Assim, primeiro recusamos o acesso de todos os recursos para todos os usuários para logo em seguida declarar os usuários que podem acessar quais recursos do modelo. Essa política é chamada de <a href="https://en.wikipedia.org/wiki/Whitelisting"><strong><em>Whitelist</em></strong></a>.</p><pre>{<br>   &quot;acls&quot;: [</pre><pre>{<br>       &quot;accessType&quot;: &quot;*&quot;,<br>       &quot;principalType&quot;: &quot;ROLE&quot;,<br>       &quot;principalId&quot;: &quot;$everyone&quot;,<br>       &quot;permission&quot;: &quot;DENY&quot;<br>     },<br><strong>     {<br>       &quot;accessType&quot;: &quot;*&quot;,<br>       &quot;principalType&quot;: &quot;ROLE&quot;,<br>       &quot;principalId&quot;: &quot;$owner&quot;,<br>       &quot;permission&quot;: &quot;ALLOW&quot;<br>     }</strong><br>   ]<br>}</pre><p>Seguindo o exemplo anterior, no segundo objeto, dizemos que apenas os usuários que são donos daquele recurso - representados pela role dinâmica <strong>$owner </strong>-<strong> </strong>possuem permissão (ALLOW) em todos os tipos de acesso(*).</p><p>No entanto, existe um problema nessa situação. Vamos dizer que você possui um formulário de cadastro e após o usuário preenchê-lo, realiza-se uma requisição POST na rota /usuários. Você deverá receber uma resposta com status 401 — UNAUTHORIZED. Isso ocorre porque todos os tipos de acesso estão bloqueados caso você não seja o dono do recurso. No entanto, como você pode ser o dono de um recurso a ser criado (que ainda não existe)?</p><p>Para resolver esse problema, adicionamos um <strong>outro objeto acl </strong>na lista, permitindo a escrita no modelo <strong>Usuário</strong> por todos. A lista de <strong><em>acls</em></strong> fica assim:</p><pre>// Usuario.json<br>{<br>   &quot;acls&quot;: [<br>     {<br>       &quot;accessType&quot;: &quot;*&quot;,<br>       &quot;principalType&quot;: &quot;ROLE&quot;,<br>       &quot;principalId&quot;: &quot;$everyone&quot;,<br>       &quot;permission&quot;: &quot;DENY&quot;<br>     },<br>     {<br>       &quot;accessType&quot;: &quot;*&quot;,<br>       &quot;principalType&quot;: &quot;ROLE&quot;,<br>       &quot;principalId&quot;: &quot;$owner&quot;,<br>       &quot;permission&quot;: &quot;ALLOW&quot;<br>     },<br><strong>     {<br>       &quot;accessType&quot;: &quot;WRITE&quot;,<br>       &quot;principalType&quot;: &quot;ROLE&quot;,<br>       &quot;principalId&quot;: &quot;$everyone&quot;,<br>       &quot;permission&quot;: &quot;ALLOW&quot;<br>     }   </strong><br>   ]<br>}</pre><p>Vamos dizer que o relacionamento entre Usuário e Música é <a href="https://loopback.io/doc/en/lb2/HasMany-relations.html"><strong>hasMany</strong></a><em>. </em>Um usuário consegue criar várias músicas, só ele consegue edita-las, mas todos os usuários conseguem visualizar todas as músicas (inclusive as de outros usuários).</p><p>A lista de acls no arquivo <strong><em>Musica.json</em></strong><em> </em>ficaria assim:</p><pre>// Musica.json<br>{<br>   &quot;acls&quot;: [<br>     {<br>       &quot;accessType&quot;: &quot;*&quot;,<br>       &quot;principalType&quot;: &quot;ROLE&quot;,<br>       &quot;principalId&quot;: &quot;$everyone&quot;,<br>       &quot;permission&quot;: &quot;DENY&quot;<br>     },<br>     {<br>       &quot;accessType&quot;: &quot;*&quot;,<br>       &quot;principalType&quot;: &quot;ROLE&quot;,<br>       &quot;principalId&quot;: &quot;$owner&quot;,<br>       &quot;permission&quot;: &quot;ALLOW&quot;<br>     },<br>     {<br>       &quot;accessType&quot;: &quot;WRITE&quot;,<br>       &quot;principalType&quot;: &quot;ROLE&quot;,<br>       &quot;principalId&quot;: &quot;$everyone&quot;,<br>       &quot;permission&quot;: &quot;ALLOW&quot;<br>     },<br>     {<br>       &quot;accessType&quot;: &quot;READ&quot;,<br>       &quot;principalType&quot;: &quot;ROLE&quot;,<br>       &quot;principalId&quot;: &quot;$everyone&quot;,<br>       &quot;permission&quot;: &quot;ALLOW&quot;<br>     }<br>   ]<br>}</pre><p>Novamente, negamos (“permission”: “DENY”) todo tipo de acesso (“accessType”: “*”) para todos os usuários (“principalId”: “$everyone”), depois permitimos todo tipo de acesso para o dono, e também permitimos a escrita por todos os usuários, como também fizemos no <strong><em>Usuário.json</em></strong>. A única diferença é que agora também permitimos a leitura por todos usuários. Desse modo, um usuário consegue criar e visualizar todas as músicas disponíveis no sistema, mas apenas editar as músicas que ele criou.</p><p>Assim, concluímos esse artigo sabendo como configurar uma aplicação básica, controlando a autorização nos modelos. Em cada modelo, definimos quais <strong><em>accessTypes </em></strong>determinadas <strong><em>Roles </em></strong>possuem. No próximo artigo veremos como criar <strong><em>Roles </em></strong>estáticas<strong><em> </em></strong>customizadas e associá-las a usuários e também como configurar a autorização de <a href="https://loopback.io/doc/en/lb3/Remote-methods.html">métodos remotos</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9e2bed2072c8" width="1" height="1" alt=""><hr><p><a href="https://medium.com/codetobits/autentica%C3%A7%C3%A3o-e-autoriza%C3%A7%C3%A3o-no-loopback-9e2bed2072c8">Autenticação e Autorização no LoopBack</a> was originally published in <a href="https://medium.com/codetobits">codetobits</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Welcome to lifeandjourneys]]></title>
            <link>https://medium.com/lifeandjourneys/welcome-to-lifeandjourneys-776adadb3639?source=rss-1db23bae54f6------2</link>
            <guid isPermaLink="false">https://medium.com/p/776adadb3639</guid>
            <category><![CDATA[travel]]></category>
            <category><![CDATA[relationships]]></category>
            <category><![CDATA[life]]></category>
            <dc:creator><![CDATA[Leonardo Grade]]></dc:creator>
            <pubDate>Sat, 02 Dec 2017 20:38:48 GMT</pubDate>
            <atom:updated>2017-12-02T20:48:12.497Z</atom:updated>
            <content:encoded><![CDATA[<p>Hi everyone! We’re excited to have finally built up ourselves a little space here on medium. We hope to share some of our experiences with you that might help planning a trip, building up a relationship, finding new places to eat, and other things that we feel like are worth sharing.</p><p>Our intention is not to be that perfect couple whose goals are to “make your lives better” by sharing how “perfect” ours is. Neither are we here to pretend that you’ll be a different person after reading our stories.</p><p>It would be nice, however, if we could entertain, inform and end up helping you in any way. :)</p><p>If you enjoy travelling, here&#39;s our YouTube channel with some nice landscapes we&#39;ve been lucky enough to see: <a href="https://www.youtube.com/channel/UCxmh_RZ0F2EBWUbTnHIwdCw">https://www.youtube.com/channel/UCxmh_RZ0F2EBWUbTnHIwdCw</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KwWnzZ8jXvyhjmnIXO3Kuw.jpeg" /><figcaption>That&#39;s us: Jenny &amp; Leo walking down the streets of Nuremberg</figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=776adadb3639" width="1" height="1" alt=""><hr><p><a href="https://medium.com/lifeandjourneys/welcome-to-lifeandjourneys-776adadb3639">Welcome to lifeandjourneys</a> was originally published in <a href="https://medium.com/lifeandjourneys">lifeandjourneys</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>