<?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 Mike North on Medium]]></title>
        <description><![CDATA[Stories by Mike North on Medium]]></description>
        <link>https://medium.com/@mikenorth?source=rss-b031920804e8------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*H17wus1HNhfwmw8CjGKgsg.png</url>
            <title>Stories by Mike North on Medium</title>
            <link>https://medium.com/@mikenorth?source=rss-b031920804e8------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 19 Nov 2026 02:00:26 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@mikenorth/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[ember-cli-typescript v2 release candidate]]></title>
            <link>https://medium.com/@mikenorth/ember-cli-typescript-v2-release-candidate-3d1f72876ea4?source=rss-b031920804e8------2</link>
            <guid isPermaLink="false">https://medium.com/p/3d1f72876ea4</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[ember]]></category>
            <category><![CDATA[emberjs]]></category>
            <dc:creator><![CDATA[Mike North]]></dc:creator>
            <pubDate>Fri, 14 Dec 2018 18:01:00 GMT</pubDate>
            <atom:updated>2018-12-14T18:01:00.801Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ez5pW7ClSpCWMLFMay1-vg.png" /></figure><p>I and the rest of the “typed-ember” team are pleased to announce the first release candidate of the next version of <a href="https://github.com/typed-ember/ember-cli-typescript/tree/v2">TypeScript support in Ember.js apps</a> and addons.</p><blockquote>We’re very interested in your feedback. Please read this thoroughly, try out the release candidate and let us know if you run into any issues</blockquote><p>Here’s what you need to know:</p><h3>It relies on the new <a href="https://blogs.msdn.microsoft.com/typescript/2018/08/27/typescript-and-babel-7/">babel7 support for handling ts files</a></h3><p>In ember-cli-typescript v1, we rely on the typescript compiler to turn typescript into JavaScript. This presents a few challenges:</p><p>Ember apps are transpiled with babel, and integrating an additional compiler (tsc) required some significant asset pipeline backflips. This never worked perfectly and resulted in some serious limitations around the use of other addons, as well as build performance penalties</p><p>With more than one compiler emitting JavaScript, great care must be taken in order to ensure that there’s consistency in how language features are treated. In particular, there are differences in how decorators are compiled in typescript, babel 6 and babel 7.</p><p>Babel 7 doesn’t really do TypeScript compilation, it just knows the subset of typescript code that can be stripped away in order to get valid JavaScript. It doesn’t in any way do type-checking, but rest easy…</p><h3>You still get type-checking from TypeScript</h3><p>In ember-cli-typescriptv2, although the TypeScript compiler is in no way responsible for generating JavaScript files, it still performs type-checking, and it’s still responsible for generating the appropriate output.d.tsfiles when precompiling addons for publishing.</p><h3>One thing you should know: for projects that use decorators, the transpiled output files will be unnecessarily large</h3><p>This is one last thing that’s being worked on is <a href="https://github.com/typed-ember/ember-cli-typescript/issues/461">a build output size bloat</a>, relative to the same project compiled with ember-cli-typescript v1. This is due to repeated babel helpers for decorators — <a href="https://medium.com/u/25e7fb8a78bb">pzuraq</a> (you may know him as the <a href="https://ember-decorators.github.io/ember-decorators/latest/">ember-decorators</a> maintainer) is working on a fix for this, which we hope will land next week.</p><h3>How do I try this out?</h3><p>Check out the installation <a href="https://github.com/typed-ember/ember-cli-typescript/tree/v2#setup-and-configuration">instructions on our v2 branch</a>.</p><h3>Special thanks to Dan Freeman</h3><p>He did the lion’s share of the work getting the project aligned with Ember’s babel conventions</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3d1f72876ea4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Ember Community, meet CodeSandbox!]]></title>
            <link>https://medium.com/@mikenorth/ember-community-meet-codesandbox-10a43076b3fa?source=rss-b031920804e8------2</link>
            <guid isPermaLink="false">https://medium.com/p/10a43076b3fa</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[ember]]></category>
            <dc:creator><![CDATA[Mike North]]></dc:creator>
            <pubDate>Tue, 02 Oct 2018 21:04:12 GMT</pubDate>
            <atom:updated>2018-10-02T21:04:12.267Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FkiFDTs4ycb1q_cxXWVw5A.png" /></figure><p>Last week, codesandbox.io released server-side evaluated sandboxes, opening the door for web application development driven by a true node-driven build process instead of browser-based hacks that aim to approximate similar results.</p><h3>Ives van Hoorne on Twitter</h3><p>Very proud to announce CodeSandbox Containers! 🚀 We can now run code on servers, so anything that works locally will run on CodeSandbox! With this we get first-class support for: - @gatsbyjs - Next.js - @nuxt_js - @apollographql - @reasonml - @nodejs https://t.co/w3dBPqx8Ta https://t.co/ftlu82UiRM</p><p>CSB’s interface, leverages the power of Microsoft’s <a href="https://github.com/Microsoft/monaco-editor">Monaco editor</a>, which you may be familiar with as the text editing component of visual studio code. Without further ado, here’s an example of CSB running ember-cli to serve an ember app</p><iframe src="https://cdn.embedly.com/widgets/media.html?url=https%3A%2F%2Fcodesandbox.io%2Fs%2Fgithub%2Fmike-north%2Fember-new-output%2Ftree%2Fsuperrentals%2F%3Fhidenavigation%3D1%26module%3D%252Fapp%252Ftemplates%252Fapplication.hbs&amp;src=https%3A%2F%2Fcodesandbox.io%2Fembed%2Fgithub%2Fmike-north%2Fember-new-output%2Ftree%2Fsuperrentals%2F%3Fhidenavigation%3D1%26module%3D%252Fapp%252Ftemplates%252Fapplication.hbs&amp;type=text%2Fhtml&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;schema=codesandbox" width="1000" height="500" frameborder="0" scrolling="no"><a href="https://medium.com/media/a5a0997c07da5e56a7584810b198f8d7/href">https://medium.com/media/a5a0997c07da5e56a7584810b198f8d7/href</a></iframe><h3>How is this different, compared to ember-twiddle?</h3><p>First, it’s important to recognize that ember-twiddle has helped our community share examples, teach and learn, explore and reproduce bugs and more! We owe <a href="https://medium.com/u/2a73db34e492">Gaurav</a> and everyone who has contributed to this project our gratitude.</p><p>With codesandbox containers, what you’re dealing with is not the usual <a href="https://github.com/ember-cli/ember-twiddle/blob/ac116eb20d1e6c2152313f865159c443a9e2bd6f/app/services/ember-cli.js#L261-L295">browser-only trickery</a> that’s used to imitate the work ember-cli does in a real development environment — it’s the real deal. You can view the app without the development tools <a href="https://40m9qvjn0w.sse.codesandbox.io/">here</a>, and examine it with the <a href="https://github.com/emberjs/ember-inspector">ember-inspector</a>.</p><p>Because this is a true Node.js environment, running the real ember-cli, we can do things in codesandbox that were never possible with twiddle, such as create programs that use fastboot for server-side rendering, make use of PWA technologies like Service Workers and more!</p><h3>Git Integration</h3><p>Here’s the URL for the example above</p><pre><a href="https://codesandbox.io/s/github/mike-north/ember-new-output/tree/superrentals">https://codesandbox.io/s/github/mike-north/ember-new-output/tree/superrentals</a></pre><p>CSB pulls code from public git repos with ease, You can even <a href="https://codesandbox.io/docs/importing#import-from-github">create sandboxes from branches, tags or even subfolders</a> (i.e., a single package within a monorepo project). The git integration doesn’t stop there — you can fork sandboxes, make changes, and then generate a pull request back into the original repo! Look here for more info:</p><p><a href="https://codesandbox.io/docs/git">Git Committing and PRs - CodeSandbox</a></p><h3>How do I create my own ember-cli sandbox?</h3><p>While we wait on the official Ember.js support to be added to the codesandbox-client app</p><p><a href="https://github.com/CompuIves/codesandbox-client/pull/1113">Ember.js support by mike-north · Pull Request #1113 · CompuIves/codesandbox-client</a></p><p>You can start with this sandbox in the mean time</p><p><a href="https://codesandbox.io/s/github/mike-north/ember-new-output">https://codesandbox.io/s/github/mike-north/ember-new-output</a></p><p>This will give you <em>almost</em> the equivalent output of ember new my-app . Soon®, the hope is to use <a href="https://github.com/ember-cli/ember-new-output/">https://github.com/ember-cli/ember-new-output/</a> for this instead — since this repo is updated with every ember-cli release.</p><p>If you’re interested in using bleeding edge parts of the ember ecosystem like TypeScript support, ember-decorators and sparkles-components, here’s another starter project</p><p><a href="https://codesandbox.io/s/github/mike-north/ember-new-output/tree/typescript">https://codesandbox.io/s/github/mike-north/ember-new-output/tree/typescript</a></p><h3>Known Limitations</h3><p>The following are limitations, some of which apply to codesandbox, some to ember and ember-cli. Keep an eye on these, so you’ll know when the editing experience becomes even more refined than it already is</p><ul><li>Creating new files through the terminal won’t work <a href="https://github.com/CompuIves/codesandbox-client/issues/1137">https://github.com/CompuIves/codesandbox-client/issues/1137</a></li><li>Empty files are pruned <a href="https://github.com/CompuIves/codesandbox-client/issues/1136">https://github.com/CompuIves/codesandbox-client/issues/1136</a>, potentially resulting in ember-cli blowing up on initial build <a href="https://github.com/ember-cli/ember-cli/issues/8081">https://github.com/ember-cli/ember-cli/issues/8081</a></li><li>Many projects will be detected as `create-react-app` projects <a href="https://github.com/codesandbox-app/codesandbox-importers/pull/16">https://github.com/codesandbox-app/codesandbox-importers/pull/16</a></li><li>Transitive dependencies of ambient type packages are ignored <a href="https://github.com/CompuIves/codesandbox-client/issues/1127">https://github.com/CompuIves/codesandbox-client/issues/1127</a></li><li>Only one port is opened, but HTTP and WS are allowed</li><li>`debugger;` w/ live freezes all watchers <a href="https://github.com/CompuIves/codesandbox-client/issues/1128">https://github.com/CompuIves/codesandbox-client/issues/1128</a></li><li>Only a certain number of SSE sandboxes per user allowed — store keep your code in github so you can destroy and re-create whenever you like</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=10a43076b3fa" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Guide to TypeScript Ambient Declarations]]></title>
            <link>https://medium.com/@mikenorth/guide-to-typescript-ambient-declarations-717ef6da6514?source=rss-b031920804e8------2</link>
            <guid isPermaLink="false">https://medium.com/p/717ef6da6514</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[typescript]]></category>
            <dc:creator><![CDATA[Mike North]]></dc:creator>
            <pubDate>Mon, 27 Aug 2018 20:01:01 GMT</pubDate>
            <atom:updated>2018-09-11T19:56:42.877Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ez5pW7ClSpCWMLFMay1-vg.png" /></figure><p>One of my favorite things about <a href="http://typescriptlang.org/">TypeScript</a> is the ability to take full advantage of the entire JavaScript ecosystem. If your TypeScript code needs to use a library that was written in plan JavaScript, you can always write <a href="https://basarat.gitbooks.io/typescript/docs/types/ambient/intro.html">ambient declarations</a> that describe the types that would have been there, had it been written in TypeScript.</p><h3>Ambient Types</h3><p>For example, if you had to use a npm package firetruck that looked like this</p><pre>/**<br> * Orient the water nozzle and spray for 30 seconds<br> * <br> * <a href="http://twitter.com/param">@param</a> theta nozzle horizontal rotation angle<br> * <a href="http://twitter.com/param">@param</a> phi nozzle vertical angle<br> * <a href="http://twitter.com/param">@param</a> pressure water pressure<br> */<br>async function extinguish(theta, phi, pressure) {<br>   await aimHose(theta, phi);<br>   await sprayWater(pressure);<br>}</pre><pre>export default extinguish;</pre><p>in your TypeScript app, you’re likely to get a lot of errors about modules not being found, and “implicit any” types that TypeScript can’t infer without more information.</p><p>The way you’d address this problem is to define some types within your project that describe this code. These types usually live in <strong>declaration files</strong> (*.d.ts) that contain only types — no values at all. Here’s what one might look like in our case</p><pre>// firetruck.d.ts<br>declare function extinguish(theta: number,<br>                            phi: number,<br>                            pressure: number): Promise&lt;void&gt;;<br>export default extinguish;</pre><p>Now, when we try to use the extinguish function from within some TypeScript code, we get type checking on the arguments, and know that the return value is a promise!</p><p>Typically these files get passed around between developers interested in this npm package for a while, and eventually someone decides to publish them on NPM so they can be shared just like other node.js modules. This almost certainly means committing them to the <a href="https://github.com/DefinitelyTyped/DefinitelyTyped">DefinitelyTyped</a> repo, because <a href="https://github.com/Microsoft/TypeScript/blob/969b46e44bcf23b1b5e9a17e6844533b999d979f/src/compiler/moduleNameResolver.ts#L182">TypeScript is explicitly set up to make types from this package very easy for users to consume</a> and <a href="https://code.visualstudio.com/docs/languages/javascript#_intellisense">Visual Studio Code can automatically find and download them on-demand</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/744/1*TMMs3w1hCrWiwJlvbOstAA.png" /></figure><h3>DefinitelyTyped</h3><p>In our case, we’d open up a pull request in <a href="https://github.com/DefinitelyTyped/DefinitelyTyped">DefinitelyTyped</a> creating a new folder like types/firetruck/. We’d take our firetruck.d.ts file, and copy it to types/firetruck/index.d.ts — indicating that we’re describing the <a href="https://docs.npmjs.com/files/package.json#main">primary entry point</a> for the npm package.</p><p>There’s a LOT going on in this one repo — literally thousands of npm packages being worked on by thousands of contributors. You’ll end up interacting with <a href="https://github.com/DefinitelyTyped/dt-review-bot">dt-review-bot</a> to facilitate getting everything ready for merge. Once your work is published, the bot will <a href="https://github.com/DefinitelyTyped/DefinitelyTyped/pull/28264#issuecomment-414805117">notify any contributors</a> listed at the top of the *.d.ts files anytime relevant issues or pull requests are opened.</p><p>The headers for these *.d.ts files follow <a href="https://github.com/DefinitelyTyped/definition-header#format">a specific format</a> that is parsed as part of the type-publishing process. Here, we state a version number (more on this later), the minimum supported TypeScript version and any contributors who should be alerted to PRs/issues.</p><pre>// Type definitions for firetruck 1.3<br>// Project: <a href="https://github.com/firetruck/firetruck#readme">https://github.com/firetruck/firetruck#readme</a><br>// Definitions by: Mike North&lt;<a href="https://github.com/mike-north">https://github.com/mike-north</a>&gt;<br>// TypeScript Version: 2.4</pre><p>Shortly after your code is merged, the <a href="https://github.com/Microsoft/types-publisher">types-publisher</a> will publish any changes to npm as <a href="http://twitter.com/types">@types</a> packages. Ours would end up being called <a href="http://twitter.com/types/firetruck">@types/firetruck</a> v1.3.0. Subsequent changes to the types will automatically increment the patch version number.</p><h3>High-level tips for writing good type declarations</h3><p>Hopefully I’ll find time to write more about this, but at a high level there’s one important principles that will help get newcomers started.</p><blockquote>Inappropriately strict types are more annoying (and more destructive to the code of your users) than inappropriately loose types.</blockquote><p>Let’s look at a very simple example:</p><pre>declare function generateId(): string | number;</pre><p>Consider a situation where the return type of this function is inappropriately wide (i.e., 100% of the time a string is returned). The likely outcome is that users might do something like</p><pre>let id = ‘’ + generateId();</pre><p>or apply a type guard that will never be used</p><pre>let id = generateId();<br>if (typeof id === ‘string’) { // not necessary<br> …<br>}</pre><p>With our knowledge that the type is too wide, we might see this as a tiny bit of <a href="https://en.wikipedia.org/wiki/Defensive_programming">defensive programming</a>, but it’s certainly not going to cause runtime errors.</p><p>Now consider a situation where our generateId sometimes fails and returns null. Our types are not telling consumers anything about this, which could lead to serious problems.</p><pre>let id = generateId();<br>if (typeof id === ‘string’) {<br> id.toLowerCase(); // 💥 Runtime Error<br>}</pre><p>Here’s another example: consider a function that’s meant to disable some text component</p><pre>declare function setDisabled(elem: HTMLInputElement): void;</pre><p>If I wanted to use this with a &lt;textarea&gt;, I’d have to throw away all of my type safety to get things working</p><pre>setDisabled(myTextArea as any);</pre><p>Once these anys get into their code, new versions of the types that fix things are unlikely to do much good. The developer would have to be paying extremely close attention to know they can remove as any. The common outcome of this story is that the type declarations being inappropriately strict results in users punching tons of holes in their type safety.</p><h3>Tests</h3><p>Like any kind of code, ambient types need to have tests to protect against regression. You’ll want to follow the same practices you’re used to following for other types of code, like</p><ul><li>Bug fixes should be accompanied by test cases that prove the effectiveness of the fix, and protect against future regression</li><li>Have positive and negative test cases</li><li>Test that the solution works, not the private internals of how you might have gotten there</li></ul><p>What’s different about testing ambient types is the way you write them. We have no values to assert against, and no functions to call. Thankfully, our testing needs are much simpler! Everything we need to test has to do with the idea of <strong>type equivalence </strong>(i.e., whether values of type T are assignable to a variable of type V).</p><p>Writing a simple positive test case is easy. All you need to do is create a new TypeScript file and attempt an assignment</p><pre>const result: Promise&lt;any&gt; = extinguish(30, 20, 100); // ✅</pre><p>If this successfully compiles, it means that whatever extinguish returns is assignable to a Promise&lt;any&gt;. The extinguish() function really returns Promise&lt;void&gt; , so let’s alter our test</p><pre>const result: Promise&lt;void&gt; = extinguish(30, 20, 100); // ✅</pre><p>Hmm. This passes too. It turns out that Promise&lt;void&gt; and Promise&lt;any&gt; are assignable to each other (because any will match anything).</p><p>If we really want to make sure that the type system yells at anyone attempting to use the value this promise resolves to (this is what we’re saying by returning a Promise&lt;void&gt;) we have to involve another tool.</p><h4>dtslint</h4><p>The <a href="https://github.com/Microsoft/dtslint">dtslint</a> library runs TSLint on your typescript files (including declarations), and compares the list of errors found against comments in your source code. We could assert the type returned by our function using a comment</p><pre>extinguish(30, 20, 100); // $ExpectType Promise&lt;void&gt; ✅</pre><p>Because the type of the value is stringified and compared to our comment, we’re no longer using assignment as the mechanism behind the test — we’re directly comparing strings. If you changed the commented type to Promise&lt;any&gt; this test would fail</p><p>Another kind of test we could write would be an expected error.</p><pre>extinguish(30, 20, 100).then(data =&gt; {<br>  data.abc // $ExpectError ✅<br>});</pre><p>If data is of type void, then attempting to read any property from it will cause a type error. If a line with $ExpectError is found where no type error occurs, dtslint will indicate a test failure. If you’ve ever used something like <a href="https://api.qunitjs.com/assert/throws">QUnit.throws</a> or Chai’s <a href="http://www.chaijs.com/api/assert/#method_throws">throws</a> this behavior will be familiar to you.</p><p><a href="https://github.com/mike-north/ambient-type-testing-examples">Here’s</a> an example repo with a positive and negative test case applied to ambient types.</p><p>The rate at which TypeScript is becoming popular is truly amazing, and supplementing popular libraries with type information is a big part of what makes adoption easy. When done right, consumers will swear that these libraries were written in TypeScript from the start!</p><p>Permalink: <a href="https://mike.works/blog/post/guide-to-typescript-ambient-declarations-13d3c45">https://mike.works/blog/post/guide-to-typescript-ambient-declarations-13d3c45</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=717ef6da6514" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Webpack & Preact-CLI Vulnerability]]></title>
            <link>https://medium.com/@mikenorth/webpack-preact-cli-vulnerability-961572624c54?source=rss-b031920804e8------2</link>
            <guid isPermaLink="false">https://medium.com/p/961572624c54</guid>
            <category><![CDATA[vulnerability]]></category>
            <category><![CDATA[progressive-web-app]]></category>
            <category><![CDATA[security]]></category>
            <category><![CDATA[webpack]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Mike North]]></dc:creator>
            <pubDate>Tue, 20 Jun 2017 16:28:05 GMT</pubDate>
            <atom:updated>2017-06-20T16:28:05.429Z</atom:updated>
            <content:encoded><![CDATA[<h4>Some users susceptible to undetectable man-in-the-middle attacks over HTTPS on public WiFi</h4><h3>🕵️ How it was discovered</h3><p>After live streaming <a href="https://medium.com/u/2508e4c7a8ec">Addy Osmani</a>’s great Google I/O 2017 talk on advances in Progressive Web App tooling and technologies, I was very excited to take <a href="https://github.com/developit/preact-cli">Preact-CLI</a> for a spin.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FaCMbSyngXB4%3Fstart%3D1548%26feature%3Doembed%26start%3D1548&amp;url=http%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DaCMbSyngXB4&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FaCMbSyngXB4%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/bde9e648e0a1e1fcb12512373a7f6306/href">https://medium.com/media/bde9e648e0a1e1fcb12512373a7f6306/href</a></iframe><p>Part of this tool involves serving the app up over HTTP/2. Although <a href="https://http2.github.io/faq/#does-http2-require-encryption">the standard doesn’t truly <em>require</em> encryption</a>, TCP representatives from all major browser vendors <a href="https://daniel.haxx.se/blog/2015/03/06/tls-in-http2/">have stated the intention to only implement HTTP/2 for TLS connections</a>. Effectively, this means you’ll only see it work over https:// URLs in practice.</p><p>Because TLS is required, and because <strong>unlike</strong> service workers, we don’t get special treatment of localhost for development purposes, a certificate (specifically, the private key) must be used to encrypt HTTP responses.</p><p>Once I started Preact-CLI and saw a bunch of security warnings, I started to take a deeper look at what was going on.</p><h3>☠️ What’s the problem?</h3><p>Preact-CLI, perhaps in an effort to save developers from having to generate their own certificate, included a certificate (and corresponding private key) in the project itself. Upon notifying <a href="https://medium.com/u/30b8f5921914">Jason Miller</a> about this problem, he brought to my attention that this same pattern had been followed in <a href="https://github.com/webpack/webpack-dev-server/">webpack-dev-server</a>.</p><p>This would be a serious security issue in and of itself. However, upon closer inspection of the certificates in question, they turned out to be <strong>certificate authority (CA) </strong>certificates (and corresponding private keys). I’m not sure why the choice was made to generate this type of cert, but the end result is that, instead of the vulnerability applying to a particular domain, it applies across <strong>all domains</strong>.</p><h3>🤷‍ Who is affected?</h3><p>Users who trust the certificates built-in to preact-cli and webpack-dev-server</p><h3>⚠️ What could someone do with this, and how easily?</h3><blockquote>As a result of this vulnerability, an attacker could very easily and reliably eavesdrop on, and tamper with HTTPS traffic across <strong><em>ALL DOMAINS</em></strong>, undetected. Essentially HTTPS is completely compromised, and no data is secret or safe anymore.</blockquote><p>To do this, they would need to perform the following sequence of actions:</p><p>1. Use the private key for one of these certificate authorities to sign forged certificates for one or more domains (i.e., *.google.com , *.paypal.com, etc…). For those who trust the CA certificates in question, any certificates that the CA signs, will also be trusted.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/942/1*GfofYM62e9e-rVyj--yfkg.png" /><figcaption>A certificate signed by a trusted certificate authority is also trusted</figcaption></figure><p>2. Audit WiFi traffic to determine public WiFi network names that targets have joined before, and will automatically connect to again. Pick a network name (i.e., <strong>Airport Free WiFi</strong>)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/776/1*lLYd89Gw8D7jCEG5vRjFNg.png" /><figcaption>WiFi devices broadcast networks they’ve joined before. We can collect these in order to stage our attack</figcaption></figure><p>3. Create a WiFi network with this network name, and bridge it with a network that has an internet connection. There’s a high likelihood that the target’s devices will automatically join this network without any action being required on their part (this is the default behavior of most WiFi-enabled devices)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Iwr0uBAM29_RRPBR1KglDQ.png" /><figcaption>WiFi clients will join networks they’ve joined before, with no interaction required on the part of the target</figcaption></figure><p>4. Stage a man-in-the-middle attack, using the generated certificates to provide (apparently) valid HTTPS responses. Software such as <a href="https://github.com/moxie0/sslstrip">SSLstrip</a> or <a href="https://github.com/droe/sslsplit">SSLsplit</a> makes this trivial.</p><blockquote>No action on the part of the target is required. Once we reach step 4, all HTTPS traffic, across all domains can be both observed and/or tampered with.</blockquote><h3>🛡 What defenses do affected users have against this?</h3><p>The defense against this kind of issue would be HPKP (also known as <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Public_Key_Pinning">public key pinning</a>), but for reasons I’ll go into in a moment, it wouldn’t help in this specific case. The idea behind HPKP is that an HTTP response header can inform browsers as to what the expected certificate should look like</p><pre>Public-Key-Pins: pin-sha256=&quot;&lt;pin-value&gt;&quot;; <br>                 max-age=&lt;expire-time&gt;; <br>                 includeSubDomains; <br>                 report-uri=&quot;&lt;uri&gt;&quot;</pre><p>The field that’s most interesting here is pin-value , which can be one or more <a href="https://en.wikipedia.org/wiki/Public_key_fingerprint">public key fingerprints</a>. Modern browsers can use this information to validate whether a certificate is <strong>the right one</strong>, going far beyond the typical stringency (any certificate for the right domain, signed by any trusted authority).</p><p>The important idea here is that the browser remembers these fingerprints for the prescribed amount of time, so it’s not something that can be simply defeated by rewriting headers as part of the MITM attack. Of course, browsers have to get this information in the first place (similar to <a href="https://www.owasp.org/index.php/HTTP_Strict_Transport_Security_Cheat_Sheet">HSTS headers</a>), so users would only be protected for <strong>return visits to HPKP-enabled domains they’ve already seen before.</strong></p><p>HPKP is not widely used. <a href="https://blog.qualys.com/ssllabs/2016/09/06/is-http-public-key-pinning-dead">A survey conducted in August 2016 found that, of the top 1 million sites (by alexa rank), only 375 implemented HPKP headers, with another 76 using it in “report only” mode</a>.</p><p>In this case, however, because the certificate authorities in question are <strong>user-signed</strong>, HPKP validation won’t save us.</p><p>From MDN’s article on <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Public_Key_Pinning">HTTP Public Key Pinning</a> (my emphasis):</p><blockquote>Firefox and Chrome<strong> </strong>disable pin validation for pinned hosts whose validated certificate chain terminates at a user-defined trust anchor (rather than a built-in trust anchor). This means that <strong>for users who imported custom root certificates all pinning violations are ignored</strong>.</blockquote><h3>⚒ If I’m affected, how can I fix it?</h3><p>I’ve made a <a href="http://badcert.mike.works/">DETECTION PAGE</a> you can visit to find out whether you trust any of the bad certs in question.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*R0QycQPSO3VnFF4doZ5Olg.png" /><figcaption>Detection utility</figcaption></figure><p>If it turns out that you’re affected, you’ll be presented with instructions for how to “un-trust” a certificate. You should visit the detection page again after restarting, to ensure you’re no longer affected.</p><h3>👍 What’s a better way to handle certs in tools?</h3><p>Both projects in question have solved this problem in a similar way: certificates are generated on a per-machine and an as-needed basis. This ensures that while individual developers may all share the same tool, they all have their own certificates, with private keys under their own control where nobody can get at them.</p><p>webpack-dev-server took the approach of handling cert generation themselves, while Preact-CLI builds on an approach <a href="https://github.com/ember-cli/rfcs/pull/106">under discussion in the ember-cli project</a>, where a standalone library called <a href="https://github.com/davewasmer/devcert">devcert</a> handles certificate management.</p><p>The advantage of an approach like this is that each project that has a need for TLS doesn’t need to handle cert generation on its own, and managing certificates (i.e., regenerating them when they expire) can be done outside the context of any one tool.</p><h3>⚖️ What are the takeaways we should remember?</h3><ul><li><strong>Never distribute certificate private keys in software projects</strong>, not even for development or internal purposes.</li><li>It’s sometimes difficult to truly understand how a private key could be used by a malicious party, but <strong>the potential for damage is usually far more severe than is initially apparent</strong>.</li><li><strong>Be extremely skeptical when asked to trust certificates</strong>, and flat out paranoid about trusting a certificate authority.</li><li>Essentially, <strong>anyone with a private key to a CA you trust can render HTTPS completely useless for you</strong>, across all domains. The nature of this attack makes it almost impossible to detect until it’s too late.</li></ul><h3>😱 Holy shit, this is scary.</h3><p>If you‘re surprised at how something seemingly benign can be used to do so much damage, you are not alone. Security is one of those things that’s not as directly connected to business value, compared to features, performance, usability bug fixes, speed to market, etc…</p><p>As a group, web developers have far less fluency in security, compared to engineers in other areas (ops, DBAs, infrastructure engineers, etc…). Plenty of really smart people make security mistakes on a regular basis, simply due to lack of knowledge regarding risks, tactics and best practices.</p><p>If you’re interested in learning more about how to keep your users (and your business) safe, <strong>I’m partnering with </strong><a href="https://frontendmasters.com/"><strong>Frontend Masters</strong></a><strong> for an 8-hour hands-on workshop on web security topics.</strong> We’ll learn how to stage attacks that exploit vulnerabilities like the one reported here, and what we can do to defend against them.</p><p><a href="https://frontendmasters.com/workshops/web-security/">Web Security with Mike North</a></p><p>I also am available to meet with your team for <a href="https://mike.works/course/web-security-5c876cc">a personalized training</a> on these same topics, and more!</p><h3>📅 Disclosure Timeline</h3><p>The webpack team and <a href="https://medium.com/u/30b8f5921914">Jason Miller</a> have shown how much they really care about their users, in their swift and direct response to this issue. This kind of problem no doubt exists in other projects, and I’m glad to have worked with this group to get some high-impact fixes in place as an example to follow.</p><ul><li><strong>June 2, 2017:</strong> Notified Jason Miller about the vulnerability in preact-cli via Twitter DM</li><li><strong>June 2, 2017:</strong> Notified Sean Larkin about webpack-dev-server via Twitter DM</li><li><strong>June 13, 2017:</strong> Sean Larkin informs via email that Andrew Powell will begin working on this issue</li><li><strong>June 13, 2017:</strong> Andrew Powell opens <a href="https://github.com/webpack/webpack-dev-server/pull/942">a PR in webpack-dev-server</a> with the fix.</li><li><strong>June 14, 2017:</strong> Andrew’s PR is <a href="https://github.com/webpack/webpack-dev-server/pull/942#event-1123434010">merged into master</a> on webpack-dev-server.</li><li><strong>June 15, 2017:</strong> <a href="https://github.com/developit/preact-cli/releases/tag/1.1.2">Preact-CLI v1.12</a> released with <a href="https://github.com/developit/preact-cli/commit/071a9a559f02942aa595cf5fad22fd929193211c">a fix</a></li><li><strong>June 19, 2017: </strong><a href="https://github.com/webpack/webpack-dev-server/releases/tag/v2.5.0">webpack-dev-sever v2.5.0 released</a> with a fix</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=961572624c54" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Fluent Conf 2017 —Catch some of these fantastic speakers on video!]]></title>
            <link>https://medium.com/@mikenorth/fluent-conf-2017-catch-some-of-these-fantastic-speakers-on-video-b111bc815a62?source=rss-b031920804e8------2</link>
            <guid isPermaLink="false">https://medium.com/p/b111bc815a62</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[conference]]></category>
            <category><![CDATA[angularjs]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Mike North]]></dc:creator>
            <pubDate>Fri, 16 Jun 2017 15:06:23 GMT</pubDate>
            <atom:updated>2017-06-16T15:11:43.659Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wcxSVOfWKJhRTkO9J-hmTA.jpeg" /></figure><p>In any great multi-track conference, I sometimes find it hard to pick which talks to go to, and which to catch up on later. Thankfully, some of these fantastic speakers have presented their talks recently at other conferences, so you don’t have to feel left out!</p><p>Also, <strong>for those of you who couldn’t attend in person</strong>, watching some of these videos this is a great way to participate in this great conference from all around the world!</p><p><em>DISCLAIMER: This is the result of a “best effort” search. Please feel free to let me know if you find any I’ve missed, or if there’s a better representative video for a particular talk.</em></p><h3>Wednesday, June 21</h3><h4>9:00AM</h4><p>Addy Osmani’s talk on the latest fast-loading browser best practices</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2F7vUs5yOuv-o%3Ffeature%3Doembed&amp;url=http%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3D7vUs5yOuv-o&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2F7vUs5yOuv-o%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/b3802e80083b46d53d4797333c212fca/href">https://medium.com/media/b3802e80083b46d53d4797333c212fca/href</a></iframe><p>Max’s talk on using JavaScript to style React components</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FbIK2NwoK9xk%3Ffeature%3Doembed&amp;url=http%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DbIK2NwoK9xk&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FbIK2NwoK9xk%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/63ea84701bd6df215b04f008fa7dd7e7/href">https://medium.com/media/63ea84701bd6df215b04f008fa7dd7e7/href</a></iframe><h4>9:50AM</h4><p>Ilya Nesterov’s fantastic talk from OWSAP on latest Content Security Policy advancements and best practices</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FQHzs7OSRWnY%3Ffeature%3Doembed&amp;url=http%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DQHzs7OSRWnY&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FQHzs7OSRWnY%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/e39de1f2455e90164dd9a00f58d7365c/href">https://medium.com/media/e39de1f2455e90164dd9a00f58d7365c/href</a></iframe><h4>11:00AM</h4><p>Dean Hume’s great talk on Service Workers, HTTP/2 and other PWA technologies</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fplayer.vimeo.com%2Fvideo%2F218434542&amp;url=https%3A%2F%2Fvimeo.com%2F218434542&amp;image=https%3A%2F%2Fi.vimeocdn.com%2Fvideo%2F635903296_1280.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=vimeo" width="1920" height="1080" frameborder="0" scrolling="no"><a href="https://medium.com/media/0310a3449135a5a27ebf9c6c744f5337/href">https://medium.com/media/0310a3449135a5a27ebf9c6c744f5337/href</a></iframe><p>Jeremy Fairbank gives a great introduction to Elm, and provides a guided tour of the the philosophy behind it</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FEDp6UmaA9CM%3Ffeature%3Doembed&amp;url=http%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DEDp6UmaA9CM&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FEDp6UmaA9CM%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/8ac8e124aadaa1d8e4c03395a6feeb45/href">https://medium.com/media/8ac8e124aadaa1d8e4c03395a6feeb45/href</a></iframe><p>TJ VanToll gives a great walkthrough of taking your Angular skills to the iOS and Android world, via NativeScript</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FgFokBgCRm4Y%3Ffeature%3Doembed&amp;url=http%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DgFokBgCRm4Y&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FgFokBgCRm4Y%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/97123be5fa95d05aa8d7648c7ec83444/href">https://medium.com/media/97123be5fa95d05aa8d7648c7ec83444/href</a></iframe><h4>3:35PM</h4><p>I was fortunate enough to watch Anjana Vakil’s talk about immutable data structures in functional JavaScript in person at JSConf EU. She has some remarkably approachable examples!</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FWo0qiGPSV-s%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DWo0qiGPSV-s&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FWo0qiGPSV-s%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/4b261fb2137a0163f23e5a9a5559a83a/href">https://medium.com/media/4b261fb2137a0163f23e5a9a5559a83a/href</a></iframe><p>Elijah Manor has gone totally above and beyond, and has turned his talk on minimalistic JS build tooling into an egghead.io course!</p><figure><a href="https://egghead.io/courses/how-to-use-npm-scripts-as-your-build-tool"><img alt="" src="https://cdn-images-1.medium.com/max/998/1*A7TFAIKZdq7IsumI0lVBUw.png" /></a><figcaption>Click to check this course out!</figcaption></figure><h3>Thursday, June 22</h3><h4>9:00AM</h4><p>Ben Lesh is the authoritative source for all things RxJS, so this talk about the latest major release is a MUST WATCH</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2F3LKMwkuK0ZE%3Ffeature%3Doembed&amp;url=http%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3D3LKMwkuK0ZE&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2F3LKMwkuK0ZE%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/46fcb9d8f6eeaab08a1e5da09db7b8d8/href">https://medium.com/media/46fcb9d8f6eeaab08a1e5da09db7b8d8/href</a></iframe><p>Estelle Weyl’s deep dive into some of the most confusing and perplexing bits of CSS is thoroughly example driven, and delightfully comprehensive. She covers things that veteran developers often misunderstand like quantitative specificity calculations and some non-trivial animation techniques! This video is a bit old, so I can’t wait to hear what she’s got to say about some of the new WTFs.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FIvhIupbJrKc%3Ffeature%3Doembed&amp;url=http%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DIvhIupbJrKc&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FIvhIupbJrKc%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/bdc3cbe093b48e500c3d0f1a73bfbfcc/href">https://medium.com/media/bdc3cbe093b48e500c3d0f1a73bfbfcc/href</a></iframe><h4>9:50am</h4><p>Laura Carvajal from The Financial Times makes an incredibly compelling case for accessibly. Another one of my favorites from JSConf EU 2017</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FH4FzW9oFObs%3Ffeature%3Doembed&amp;url=http%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DH4FzW9oFObs&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FH4FzW9oFObs%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/d6d569f442ce814e63268332e5f0f8bb/href">https://medium.com/media/d6d569f442ce814e63268332e5f0f8bb/href</a></iframe><h4>4:25PM</h4><p>Ben Vinegar’s fantastic deep-dive into JavaScript source map formatting, generation and parsing was truly enlightening for me, even with some specific experience in this area. It’s not often we get conference talks that go so deep into such a specific area!</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FNkVes0UMe9Y%3Ffeature%3Doembed&amp;url=http%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DNkVes0UMe9Y&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FNkVes0UMe9Y%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="640" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/18a1b6236f77e584faf8773e94e550a2/href">https://medium.com/media/18a1b6236f77e584faf8773e94e550a2/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b111bc815a62" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[All-in for Training in 2017]]></title>
            <link>https://medium.com/@mikenorth/all-in-for-training-in-2017-874e9bb76c2?source=rss-b031920804e8------2</link>
            <guid isPermaLink="false">https://medium.com/p/874e9bb76c2</guid>
            <category><![CDATA[careers]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[learning-to-code]]></category>
            <dc:creator><![CDATA[Mike North]]></dc:creator>
            <pubDate>Thu, 05 Jan 2017 04:05:45 GMT</pubDate>
            <atom:updated>2017-01-05T09:22:20.384Z</atom:updated>
            <content:encoded><![CDATA[<blockquote><em>“I can’t believe how much more there is to learn as a web developer these days”</em></blockquote><p>This was the the theme of a conversation I had with <a href="https://twitter.com/1Marc">Marc Grabanski</a> as we filmed the last course of the year on <a href="https://frontendmasters.com/">Front End Masters</a> . We both reflected on our first experiences writing code for the browser (sprinkling a little JavaScript on a very server-oriented app), and reminisced at how easy we had it compared to people beginning to learn today.</p><p>Of course, this is a little misleading. The things we were building back then are no more difficult to make today, but now expectations are much higher, and the “list of standard skills” seems to be ever-growing. Customers demand more, teams expect more, and the modern browser doesn’t let us make as many excuses.</p><p>In particular, to take advantage of some of the most exciting and modern aspects of building a web app, the developer may have to think about</p><ul><li>A rich JavaScript app in the browser</li><li>A REST API, potentially making use of websockets for a real-time connection</li><li>An asset-serving layer that has some server-side rendering capability</li><li>The production environment that the app is running in (i.e., a CDN, server-side caching services, distributed state across a cluster, etc…)</li><li>Service workers of various versions installed across their userbase Those of us who learned to use JavaScript a decade ago or more had far less complexity to wrangle.</li></ul><p>Not only are we building complex systems, but we have many options for tools to aid us in creating our solutions, and they are constantly changing and improving over time.</p><blockquote><em>In a world where everything is continually changing, we must take continual learning seriously.</em></blockquote><p>Last year, through traveling, training teams and speaking at conferences I had the opportunity to to talk to many developers of varied backgrounds about their biggest career pain points. When you get down to it, <strong>the difficulty in learning and staying on top of all there is to know, is a huge barrier that affects both newcomers and experts alike.</strong></p><p>Developers tend to build pockets of expertise, stay there and protect it. This is a natural instinct, but is holding us back as a community. If you’ve ever experienced resistance to adopt something new, because there’s concern over whether developers will “get it”, the pain I’m talking about is at the root of the problem.</p><p>In terms of business value, this has a huge and very tangible cost (the opportunity cost of what we could be doing if everyone knew and was aware of more). Let’s imagine a scenario:</p><ul><li>20 developers</li><li><a href="http://money.usnews.com/careers/best-jobs/software-developer/salary">Average Salary of 100K USD</a></li><li>Increased expertise could improve their productivity by 5% to 20% What we’re seeing here is that lack of expertise, and the struggle of stumbling around with incomplete information (or information packaged in a way that doesn’t make deploying it in a product as intuitive as possible) costs between 1 and 4 developer salaries!</li></ul><p>Although this is a problem that exists at nearly all levels of expertise, the low hanging fruit, in terms of tangible benefit to products and teams, is helping people become get the most value out of the tools they already use. Shortly after that comes elevating teams to a level of proficiency where they can operate broadly over an application, and helping teams feel confident in taking advantage of new things for the benefit of their users.</p><p>In 2017, I’m changing course to do my part in addressing this pain:</p><h4>I will be working with LinkedIn as a consultant</h4><p>My mandates are as follows</p><ul><li>Actively &amp; passively elevate the level of expertise of their front end developers</li><li>Reduce the friction of plugging new hires into fast-moving teams</li><li>Enrich the company’s hiring pool, by reducing friction, evangelizing and increasing adoption of technologies they’re invested in like Ember.js LinkedIn has shown a long-term commitment to wholistic teaching and learning, including the purchase of lynda.com. My motivations and efforts dovetail with theirs almost perfectly, and I’ve been seriously impressed by their willingness to invest in their teams, both directly and indirectly.</li></ul><h4>I will be producing several new video courses</h4><p>Working with Front End Masters has been a fantastic experience, and Marc’s devotion to packaging and polishing fantastic curriculum from devoted teachers is truly inspiring. I’ll be continuing to work with them, and with several other partners, covering topics like</p><ul><li>Modern JavaScript &amp; Progressive Web Apps</li><li>Elixir &amp; Phoenix Framework</li><li>Fast, secure and robust CI/CD pipelines, and production environments</li><li>Harnessing the power of Tools, Text Editors &amp; IDEs</li></ul><h4>I’ll be doing many in-person workshops &amp; trainings throughout the year</h4><p>To start, I’m offering some JavaScript and <a href="https://elixir-phoenix-workshops.simplabs.com/">Elixir/Phoenix Workshops</a> in Europe, through a partnership with <a href="http://simplabs.com/">Simplabs</a>. This is taking the same Elixir training that was a hit at Ericsson HQ in Stockholm, but going far more in-depth than would be possible in a single-day event.</p><p>In short, I believe that to offer the best training I possibly can requires that I have a singular focus on teaching and learning. This is a huge change from the scrappy startup experience of 2016, but I couldn’t be more excited and eager to get started.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jTZlOqmC84HqysfVJ0r4hA.jpeg" /></figure><p><em>Originally published at </em><a href="https://mike.works/blog/post/all-in-for-training-in-2017-28bfc25"><em>mike.works</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=874e9bb76c2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a performant real-time web app with Ember Fastboot and Phoenix (Part 6)]]></title>
            <link>https://medium.com/peep-stack/building-a-performant-real-time-web-app-with-ember-fastboot-and-phoenix-part-6-14f29bf93a25?source=rss-b031920804e8------2</link>
            <guid isPermaLink="false">https://medium.com/p/14f29bf93a25</guid>
            <category><![CDATA[elixir]]></category>
            <category><![CDATA[ember]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Mike North]]></dc:creator>
            <pubDate>Wed, 04 May 2016 16:01:01 GMT</pubDate>
            <atom:updated>2016-05-11T19:32:15.026Z</atom:updated>
            <content:encoded><![CDATA[<h4>Contextual Components &amp; Animating your UI with Liquid Fire</h4><blockquote>This article is part 6 in a series. You should first read the previous parts leading up to this, or it may not make much sense!</blockquote><blockquote><a href="https://medium.com/@mikenorth/building-a-performant-web-app-with-ember-fastboot-and-phoenix-part-1-fa1241654308#.f71xu6y19"><em>Part 1: The meeting of two well-aligned, opinionated frameworks</em></a><em><br></em><a href="https://medium.com/@mikenorth/building-a-performant-real-time-web-app-with-ember-fastboot-and-phoenix-part-2-5dd2f74c7f34#.ceiizi47m"><em>Part 2: Users and Authentication (API)</em></a><em><br></em><a href="https://medium.com/@mikenorth/building-a-performant-real-time-web-app-with-ember-fastboot-and-phoenix-part-2-1-7c98452e19bb#.j04f57sjz"><em>Part 2.1: Some small adjustments to your API</em></a><em><br></em><a href="https://medium.com/@mikenorth/building-a-performant-real-time-web-app-with-ember-fastboot-and-phoenix-part-3-dd0e03232034#.lpj9mg1n3"><em>Part 3: Users and Authentication (UI)</em></a><a href="https://medium.com/@mikenorth/building-a-performant-real-time-web-app-with-ember-fastboot-and-phoenix-part-4-93118e278c68#.bsg5l8imu"><em><br>Part 4: Logging in to our API &amp; ember-simple-auth</em></a><em><br></em><a href="https://medium.com/@mikenorth/building-a-performant-real-time-web-app-with-ember-fastboot-and-phoenix-part-5-817626ca4f5f"><em>Part 5: Building a CRUD resource</em></a><strong><em><br>Part 6: Contextual Components &amp; Animating your UI with liquid-fire<br></em></strong><em>Part 7: Room UI and Messages</em></blockquote><p>One advantage that single page apps have over “old school” server-side rendered web apps is that, because the user’s entire experience consists of a single page load, we have a lot more control over the experience of transitioning from screen to screen.</p><p><a href="https://github.com/ember-animation/liquid-fire"><strong>Liquid Fire</strong></a>, the Ember.js animation library, primarily maintained by core team member <a href="https://medium.com/u/140c2e04954">Edward Faulkner</a>, is a first class citizen in the Ember ecosystem. It’s very easy to use, and provides a high-level declarative API for animating transitions between views, and much more.</p><h4>What do we want to animate?</h4><p>When it comes to animation, a little goes a long way, and too much runs the risk of actually getting in the way of a good user experience rather than enhancing it. Let’s aim for a couple of enhancements, some of which are animation and some of which are not:</p><ul><li>Add a <a href="http://materializecss.com/navbar.html">Navbar</a> for the auth pages, making it easy to navigate from the register page to the login page (hint: any child of the <strong>auth</strong> route)</li><li>Add a Navbar to the “Logged in experience” (hint: any child of the <strong>app</strong> route), with a “User” menu (i.e., the user’s email), and a dropdown containing a “Logout” button.</li><li>Navbars should make use of the <a href="http://materializecss.com/side-nav.html">SideNav</a> materialize feature for mobile, and should have a fixed header that always stays on top.</li><li>Animated transitions between the login and register cards (side-to-side)</li><li>Animated transition as the user logs in (top-to-bottom sliding)</li></ul><p>Logging out will remain un-animated, because ember-simple-auth does a restart of the UI to clear JS memory for security reasons</p><h3>The Navbar Component</h3><p>Requirements above indicate that we need two separate Navbars</p><blockquote>whenever we see a repeated piece of UI, “Component” should jump into your mind.</blockquote><p>In kind with our x-input, x-card and x-toast, let’s plan for an x-nav. These navs will have different content, so we need some sort of way to compose a navbar of various links. Let’s start with the syntax and appearance we’re looking for and work backwards</p><p>Appearance we’re looking for is something like this</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*P1vMdNN4pWTnz5v59Owumg.png" /><figcaption>Appearance we’re looking for from our x-nav component</figcaption></figure><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9bcf0bf8872510940d6b50e540ec6186/href">https://medium.com/media/9bcf0bf8872510940d6b50e540ec6186/href</a></iframe><p>And maybe something like this for the “logged in” navbar</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JNz4PKP8_ozX18D87E9O4w.png" /><figcaption>Apparance we’re looking for from the navbar in the logged-in experience</figcaption></figure><p>From some markup like this</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5693aae6339d837e0fc8c2417a4aec27/href">https://medium.com/media/5693aae6339d837e0fc8c2417a4aec27/href</a></iframe><p>What we’ll be using here is the recently added <a href="http://emberjs.com/blog/2015/11/16/ember-2-2-released.html#toc_contextual-components">contextual component feature</a> and the <a href="http://emberjs.com/blog/2016/01/15/ember-2-3-released.html#toc_hash-helper">hash helper</a>, introduced in Ember v2.3.</p><p>Create three new components called <strong>x-nav</strong>, <strong>x-div</strong>, and <strong>nav-link</strong> using ember-cli</p><pre>ember g component x-nav<br>ember g component x-div<br>ember g component nav-link</pre><p><strong>x-nav</strong> will be the top-level component for a navbar, <strong>x-div</strong> will be a fairly generic component that we’ll use for very simple DOM structure stuff, and <strong>nav-link</strong> will be a component representing a list item. Here’s the basic DOM structure we’re looking for</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d955878e868fdbeda1a6cd52e67c839d/href">https://medium.com/media/d955878e868fdbeda1a6cd52e67c839d/href</a></iframe><p>and here’s how we’re going to represent it in terms of our three components</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_BfzKxOPkLuwYb8-eDT9OA.png" /></figure><p>One thing that we’ll have to be careful of, is that there’s some jQuery-plugin initialization code we have to run as soon as the whole nav is inserted in the DOM, and we need to make sure the data-activates attribute of the mobile collapse button is set properly. This can be done by sharing private state within these components, in a way that’s not seen by the outside world.</p><p>Let’s begin with <strong>x-div</strong>. There is literally nothing that you need to do in the template file, but open up <strong>./app/components/x-div.js</strong>. We need this component to do one thing, and that’s inform a parent element of its ID.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/15001d3e84e201675335d2592fcdc3e8/href">https://medium.com/media/15001d3e84e201675335d2592fcdc3e8/href</a></iframe><p>Basically this means:</p><blockquote>If a property called _parentComponent has been set, and the value of _parentComponent has something on it called _setupChildComponent, assume that it’s a function and invoke it, passing myself as an argument</blockquote><p>I like this pattern because it’s very flexible, and leaves it up to the parent as to what needs to be done. On the receiving side of this (open up <strong>./app/components/x-nav.js</strong>), we will need something like this</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/964b0dbea3a7587d9e1519dbfa4a0387/href">https://medium.com/media/964b0dbea3a7587d9e1519dbfa4a0387/href</a></iframe><p>so now, for a child that has the <em>side-nav</em> class on it, we store its <em>elementId</em>. This will be important when we need to initialize our side-nav.</p><p>The template of <strong>x-nav </strong>(open <strong>./app/templates/components/x-nav.hbs</strong>) looks like this</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f9b1668d756951b9f07ae5ff3edc2a39/href">https://medium.com/media/f9b1668d756951b9f07ae5ff3edc2a39/href</a></iframe><p>Essentially we’re customizing two instances of <strong>x-div</strong> for our two ULs, and then also exporting our <strong>nav-link</strong> component so that users can compose them together freely. Now head over to <strong>./app/components/nav-link.js </strong>and change the base class from <strong>Ember.Component</strong> to <strong>Ember.LinkComponent</strong>. You may be wondering why…</p><p>The styling that comes for free with materialize navs uses an “active” class on the LI (note not on the A tag contained within) to indicate the currently-selected nav item.</p><pre>&lt;li class=”active”&gt;<br>  &lt;a&gt;My menu item&lt;/a&gt;<br>&lt;/li&gt;</pre><p>Ember’s link-to component also has an active class that is added automatically whenever the route that this link points to is the active route. We’re going to try to align these two concepts by using a nested {{link-to}}, the outer being a LI, and the inner being the standard A tag.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ca7ee1f5da843d20036e485bf0c8871c/href">https://medium.com/media/ca7ee1f5da843d20036e485bf0c8871c/href</a></iframe><p>And in the template, the inner {{link-to}} to the same route…</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/56251c87f79ecc1db9c8a7d017fc57e6/href">https://medium.com/media/56251c87f79ecc1db9c8a7d017fc57e6/href</a></iframe><p>Note that there are things that {{link-to}} can do which our new component isn’t prepared to handle yet, but this will work for now.</p><p>Finally, let’s <a href="http://materializecss.com/sass.html">adjust the colors of our theme using SASS variables</a>. Head over to your <strong>./app/styles/app.scss</strong> and make the following change</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ab39a14fd8545b85c47aacbae2852508/href">https://medium.com/media/ab39a14fd8545b85c47aacbae2852508/href</a></iframe><p>You’ll need to make some small updates to your tests, and then they’ll pass</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5b711512b7a24429a8fc4733a14ec205/href">https://medium.com/media/5b711512b7a24429a8fc4733a14ec205/href</a></iframe><p>The last thing we’ll need is to add the jQuery plugin initialization stuff to <strong>./app/components/x-nav.js </strong>— the <em>didInsertElement</em><strong><em> </em></strong>hook is the right place for this kind of thing</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5f11decd90524e4b103a28962bcbfbb0/href">https://medium.com/media/5f11decd90524e4b103a28962bcbfbb0/href</a></iframe><p>This is a great time to save your work, open up a PR, and merge into master once tests pass. If you want to compare your work to mine, here’s my merge commit:</p><p><a href="https://github.com/mike-north/peepchat-ui/commit/e1898cfb33aa51ccae6dadf3cd2eadffacd76bdc">Merge pull request #11 from mike-north/nav-component · mike-north/peepchat-ui@e1898cf</a></p><p>One last thing I forgot to add is a small CSS tweak necessary to maintain expected stacking contexts, even when animating. Please add the following to your <strong>./app/styles/app.scss</strong></p><pre>.liquid-container {<br>  transform: none;<br>  -webkit-transform: none;<br>}</pre><h3>Animations with Liquid Fire</h3><p>First, install liquid fire via an ember-cli command</p><pre>ember install liquid-fire</pre><p>And create a new file <strong>./app/transitions.js</strong></p><pre>touch app/transitions.js</pre><p>This file is where you’ll define all of your route transition animations, declaratively. The first one we’ll want is a <strong>toLeft</strong> transition whenever we go from <strong>auth.login</strong> to <strong>auth.register</strong>, and a <strong>toRight</strong> if we go in the other direction. This is done as follows (in <strong>./app/transitions.js</strong>)</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9886b3e8d64d3e027a4cf4ed9868212a/href">https://medium.com/media/9886b3e8d64d3e027a4cf4ed9868212a/href</a></iframe><p>One more step: head over to <strong>./app/templates/auth.hbs </strong>and change the {{outlet}} to a {{liquid-outlet}}</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6b070ce882a00507a21972c8a73b333c/href">https://medium.com/media/6b070ce882a00507a21972c8a73b333c/href</a></iframe><p>You’re done. Super difficult, right? Go play with it</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/1*LSdc8Ca5l0j_OiDO8I1QvA.gif" /></figure><p>Now let’s animate the transition into the logged in state. This isn’t the same as clicking on a link, but because of liquid-fire’s deep integration with Ember, it’s basically the same change in another place. Head over to your <strong>./app/templates/application.hbs</strong> and change your outlet to a liquid-outlet</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/24c8ab76f4a0787fea43bb8ba53fa17e/href">https://medium.com/media/24c8ab76f4a0787fea43bb8ba53fa17e/href</a></iframe><p>and define a new transition in ./<strong>app/transitions.js</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e63aa1e3ff7ebfb5a2e8f9ddd6270a87/href">https://medium.com/media/e63aa1e3ff7ebfb5a2e8f9ddd6270a87/href</a></iframe><p>Take a moment and think at how easy that was, and how difficult it would be using the other tools you’re aware of. This feeling you’re having is the high degree of productivity you’re achieving, thanks to using an opinionated web framework.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*8eFvkv-IJIzpmldWGWoBsg.gif" /><figcaption>Logging in, animated!</figcaption></figure><h4>Some adjustments to our Logged-in UI</h4><p>One tweak that makes sense is to use the user’s email address instead of “Dropdown” in the navbar of the room list. It’s a small change, thanks to our flexible <strong>user-info</strong> component</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4b37f657cd06876dbc802ca2e75eecf4/href">https://medium.com/media/4b37f657cd06876dbc802ca2e75eecf4/href</a></iframe><p>There, that’s much better</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/568/1*VoWwSSzbbVSs-Bh4LtT_PQ.png" /></figure><p>Now that we have a proper means of logging out via a navbar, we can get rid of the old “logout” button, and rearrange our UI a little bit to set the stage for what will come in the next article.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CY87EH_K4ddXzgn7uquSLg.png" /><figcaption>Some small UI changes, all done in <strong>app/templates/app/index.hbs</strong></figcaption></figure><p>Because we have decoupled our actions from the DOM structure, making these changes is very straight forward</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1910911c61e95d8663825bb2cd2b6106/href">https://medium.com/media/1910911c61e95d8663825bb2cd2b6106/href</a></iframe><p>We’re done with animation for now, so push your work up to GitHub. If you’d like to compare your code to mine, here are my changes</p><ul><li><a href="https://github.com/mike-north/peepchat-ui/commit/7a922f4a8ae56d14c0c194de9f632983096a53b0">Merge pull request #12 from mike-north/animations · mike-north/peepchat-ui@7a922f4</a></li><li><a href="https://github.com/mike-north/peepchat-ui/commit/b04bcf0b046cc7587f1290213778bac897b88e40">[].includes() --&gt; [].indexOf() &gt;= 0 · mike-north/peepchat-ui@b04bcf0</a></li><li><a href="https://github.com/mike-north/peepchat-ui/commit/a01092e781cfe0624594dca11a08dd3a4d2a4f77">changes to &#39;logged in&#39; UI · mike-north/peepchat-ui@a01092e</a></li><li><a href="https://github.com/mike-north/peepchat-ui/commit/074f6e28dd704cdb8ea8e151fe8676a0bded6e4a">Merge pull request #15 from jeffweiss/patch-1 · mike-north/peepchat-ui@074f6e2</a></li></ul><p>In the next part of this series we’ll start building the foundations for the concept of “Messages”, associated with a Room.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=14f29bf93a25" width="1" height="1" alt=""><hr><p><a href="https://medium.com/peep-stack/building-a-performant-real-time-web-app-with-ember-fastboot-and-phoenix-part-6-14f29bf93a25">Building a performant real-time web app with Ember Fastboot and Phoenix (Part 6)</a> was originally published in <a href="https://medium.com/peep-stack">PEEP Stack</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a performant real-time web app with Ember Fastboot and Phoenix (Part 5)]]></title>
            <link>https://medium.com/peep-stack/building-a-performant-real-time-web-app-with-ember-fastboot-and-phoenix-part-5-817626ca4f5f?source=rss-b031920804e8------2</link>
            <guid isPermaLink="false">https://medium.com/p/817626ca4f5f</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[ember]]></category>
            <category><![CDATA[phoenix]]></category>
            <dc:creator><![CDATA[Mike North]]></dc:creator>
            <pubDate>Sat, 30 Apr 2016 13:02:39 GMT</pubDate>
            <atom:updated>2016-05-11T19:32:10.328Z</atom:updated>
            <content:encoded><![CDATA[<h4>Building a CRUD resource</h4><blockquote>This article is part 5 in a series. You should first read the previous parts leading up to this, or it may not make much sense!</blockquote><blockquote><a href="https://medium.com/@mikenorth/building-a-performant-web-app-with-ember-fastboot-and-phoenix-part-1-fa1241654308#.f71xu6y19"><em>Part 1: The meeting of two well-aligned, opinionated frameworks</em></a><em><br></em><a href="https://medium.com/@mikenorth/building-a-performant-real-time-web-app-with-ember-fastboot-and-phoenix-part-2-5dd2f74c7f34#.ceiizi47m"><em>Part 2: Users and Authentication (API)</em></a><em><br></em><a href="https://medium.com/@mikenorth/building-a-performant-real-time-web-app-with-ember-fastboot-and-phoenix-part-2-1-7c98452e19bb#.j04f57sjz"><em>Part 2.1: Some small adjustments to your API</em></a><em><br></em><a href="https://medium.com/@mikenorth/building-a-performant-real-time-web-app-with-ember-fastboot-and-phoenix-part-3-dd0e03232034#.lpj9mg1n3"><em>Part 3: Users and Authentication (UI)</em></a><a href="https://medium.com/@mikenorth/building-a-performant-real-time-web-app-with-ember-fastboot-and-phoenix-part-4-93118e278c68#.bsg5l8imu"><em><br>Part 4: Logging in to our API &amp; ember-simple-auth</em></a><em><br></em><a href="https://medium.com/@mikenorth/building-a-performant-real-time-web-app-with-ember-fastboot-and-phoenix-part-5-817626ca4f5f"><strong><em>Part 5: Building a CRUD resource</em></strong></a><strong><em><br></em></strong><a href="https://medium.com/peep-stack/building-a-performant-real-time-web-app-with-ember-fastboot-and-phoenix-part-6-14f29bf93a25#.1exrbgfsk"><em>Part 6: Animating your UI with liquid-fire</em></a><em><br>Part 7: Room UI &amp; Messages</em></blockquote><p>Now it’s time for us to start taking advantage of the alignment of our two opinionated frameworks, by creating a couple of CRUD resources. For our chat app, we want “rooms” and “messages”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/303/1*1zv9qMqzePveg9S38n1M6A.png" /><figcaption>UML of User, Room and Message</figcaption></figure><p>Some high-level requirements</p><ul><li>Rooms should “belong” to a user, and only that user should be able to update (i.e., change the name) or delete the room</li><li>Messages don’t need to be deletable or updatable. But timestamps are important</li><li>Common API requests we may make are “get all messages for this room” or “get all rooms owned by this user”. Let’s make sure to create DB indices where appropriate.</li><li>We want to insulate our UI from the particulars of our API whenever possible.</li></ul><h3>Building Rooms in Phoenix</h3><p>We’ll be making use of <a href="https://hexdocs.pm/ecto/Ecto.html">Ecto</a>, a simple (but powerful) Elixir data persistence library. Phoenix does a lot for us through code generation. Make sure you’re in your API project, and run the following in your terminal</p><pre>mix phoenix.gen.json Room rooms name:string owner_id:references:users</pre><p>You’ll see that a bunch of files were generated. Let’s take a look at a few of these.</p><h4>Room Model</h4><p>Open up <strong>./web/models/room.ex</strong> and take a look</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c01d488085cd3049ad87be400eb3120d/href">https://medium.com/media/c01d488085cd3049ad87be400eb3120d/href</a></iframe><p>There are a couple of things going on here.</p><p><strong>line 2</strong> — We’re “using” the base model module from Phoenix.Web. If you look at <strong>./web/web.ex</strong> this will make a little more sense</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/44d38e19e85e803eedce2fb0bf6e3228/href">https://medium.com/media/44d38e19e85e803eedce2fb0bf6e3228/href</a></iframe><p>Essentially, this is where we get our basic functionality from, and it’s one way that inheritance works in Elixir.</p><p><strong>line 4–9</strong>: We’re defining the way we expect our DB schema to look. In this case we have one string field, one reference to another table via a foreign key, and a pair of timestamps (<em>inserted_at</em>, <em>updated_at</em>) that are automatically set up for us</p><p><strong>line 11–12:</strong> we distinguish between fields that are required and fields that are optional. When we make a changeset (first step in creating/updating the DB), the proposed changes are validated against these lists of attributes</p><p><strong>line 14–17: </strong>the <em>changeset</em> method will make more sense later on as we start using it. Just for fun, let’s add one line here to make sure that chat room names are 4 or more characters long.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/859b063976ec3520dcd5381bc4ce8844/href">https://medium.com/media/859b063976ec3520dcd5381bc4ce8844/href</a></iframe><p>If you’re not used to the pipe forward operator (|&gt;), it’s a very simple concept that’s used all over Elixir.</p><blockquote>Pipe-forward simply means “use the value on the left side of the pipe, as the first argument in the function on the right side of the pipe”</blockquote><p>As a concrete example, the following two methods are equivalent, pipe-forward just makes code that involves chaining a lot of functions together a lot more readable</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/76afcf670388e88f6f5e22facc3423b0/href">https://medium.com/media/76afcf670388e88f6f5e22facc3423b0/href</a></iframe><p>If you go back to your terminal, you may notice that it left you some instructions about adding the resource to your router. Let’s go ahead and do that.</p><h4>Router</h4><p>Open up ./<strong>web/router.ex </strong>and add one line in the scope you’re piping through your <em>api_auth </em>pipeline.</p><pre>resources “rooms”, RoomController, except: [:new, :edit]</pre><p>Your router should now look like this</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8090913e021b564fa6080a7d544441e1/href">https://medium.com/media/8090913e021b564fa6080a7d544441e1/href</a></iframe><p>What’s happening in this one line is, we’re defining a collection of routes that are handled by our RoomController (another thing that our <em>mix phoenix.gen.json</em> command built for us). The <em>new</em> and <em>edit</em> routes are typically only used in non-API scenarios, so they’re disabled using the “except” option.</p><h4>Room Controller</h4><p>Open up <strong>./web/controllers/room_controller.ex</strong> — you’ll see that a lot of code has been generated for you already. This is an already working set of CRUD (Create, Read, Update, Delete) functionality! We just need to make a couple of changes in order to meet our requirements above (and some common sense requirements)</p><blockquote>Only logged-in users should be able to access rooms</blockquote><p>Add the following plug at the top of the module, just like we did for our UserController (<strong>./web/controllers/user_controller.ex</strong>)</p><pre>plug Guardian.Plug.EnsureAuthenticated, handler: Peepchat.AuthErrorHandler</pre><p>This will ensure that only authenticated users will be able to invoke the methods in this controller.</p><blockquote>saving the owner of a room upon creation</blockquote><p>When a user creates a room, we want to associate their user with it. We could ask them to pass their user ID, but this allows for the possibility that they could pass an id other than theirs. A less error-prone approach would be to use the currently logged in user’s ID directly, like this</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5bbf1450d94fda277c959b925ba08081/href">https://medium.com/media/5bbf1450d94fda277c959b925ba08081/href</a></iframe><p>only the owner of a room should be able to delete or update a room. An easy way to meet this requirement is to build the current user’s ID into the query again. Users who attempt to delete rooms that aren’t theirs will get a 404 in response. This is awesome for two reasons</p><ul><li>It’s easy to implement because we’re just adding a constraint to the DB query (rather than performing a more complex authorization check)</li><li>In a lot of situations, <a href="http://even/">it’s a good idea to return a 404 instead of a 403 (Unauthorized) anyway</a>, so that attackers can’t identify an addressable resource from a non-existent resource as easily</li></ul><p>This is all accomplished pretty easily with Ecto</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2866a8e53e40e48598fd3cc544157b8b/href">https://medium.com/media/2866a8e53e40e48598fd3cc544157b8b/href</a></iframe><p>Our implemented <em>update</em> and <em>delete</em> actions now should look something like this</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/637f69c891d359a749b4a90f620e782a/href">https://medium.com/media/637f69c891d359a749b4a90f620e782a/href</a></iframe><p>You’ll notice that we have to use the pin operator (^) when building DB queries that use variables. <a href="http://elixir-lang.org/getting-started/pattern-matching.html#the-pin-operator">Read more about that here</a> if you’re interested.</p><p>One of our requirements is to be able to get a list of rooms owned by a particular user. Pattern matching makes this really easy in Phoenix — we just will end up defining two <em>index </em>actions.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b8b7bd2cb15eea2f1c4ed740543e89ad/href">https://medium.com/media/b8b7bd2cb15eea2f1c4ed740543e89ad/href</a></iframe><p>These two methods can co-exist quite nicely, the first one will be used in the event that the second argument is an object with an “owner_id” property, otherwise the second one will be used.</p><p>All-in-all, our controller should look like this now</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4c5b85def4690669848781a80587fae6/href">https://medium.com/media/4c5b85def4690669848781a80587fae6/href</a></iframe><p>We are done with the controller for now</p><h4>Room Controller Tests</h4><p>Phoenix has generated some basic tests controller for us allready in <strong>./test/controllers/room_controller_test.exs</strong>, but we are still missing some important things</p><ul><li>Ensure that authenticated users can access the room resource (collection of endpoints)</li><li>Ensure that only owners are allowed to update or delete rooms</li><li>Basic tests for the “list of rooms owned by a specific user” endpoint</li></ul><p>ExUnit, the Elixir test framework that comes with Phoenix, is a topic worthy of its own set of articles, but we’ll just touch on what we need to know for now. Open up <strong>./test/controllers/room_controller_test.exs</strong>.</p><p>You’ll notice that the general structure of the test file looks like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/186bb6d45c5106b8f8db0d4fe53d88b1/href">https://medium.com/media/186bb6d45c5106b8f8db0d4fe53d88b1/href</a></iframe><p>We have a <em>setup</em> function that is called before every test runs, and it returns a two-value tuple. This second value is passed to each test. The first thing we need to do is update this setup method so that it effectively logs a test user in. Let’s update our setup method to this</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0d10c54dd8aadb3e44e0f7f4b33b9b60/href">https://medium.com/media/0d10c54dd8aadb3e44e0f7f4b33b9b60/href</a></iframe><p>Next, let’s deal with tests for our list of rooms. We want to seed our tests with some data, and an easy way to do this is with a private method inside our test case</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0266de1b890664ee527900c9003b5a0f/href">https://medium.com/media/0266de1b890664ee527900c9003b5a0f/href</a></iframe><p>Here we create three rooms belonging to the currently logged in user, and two more belonging to another user. Now we can test our two scenarios pretty effectively, in that a request to</p><pre>/rooms</pre><p>should return 5 results, and a request to</p><pre>/rooms?user_id=123</pre><p>or even</p><pre>/users/123/rooms</pre><p>should return 3 (we’ll see how to deal with path params vs queryparams later). Implementing these two tests is now quite simple</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9db6da5c5d7c5901e2bc3179ffdb253e/href">https://medium.com/media/9db6da5c5d7c5901e2bc3179ffdb253e/href</a></iframe><p>Note that I’m just checking for the length of the array here — that’s because deserialization of an individual object is handled by our <strong>ja_serializer</strong> library. Thus, if we have coverage for our <strong>show</strong> action, we should have reasonable test coverage for deserialization of “room” objects for this view covered. let’s do that next</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5a0bbcfdb939930dc7e309c5cdce35be/href">https://medium.com/media/5a0bbcfdb939930dc7e309c5cdce35be/href</a></iframe><p>The remaining tests are mostly set up for us. We just need to make some adjustments due to our use of JSON-API contracts. Here’s what my test module looks like when all is done</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4bc5c8c54a6b24f29f8cd79b7d45fa82/href">https://medium.com/media/4bc5c8c54a6b24f29f8cd79b7d45fa82/href</a></iframe><h4>User Controller</h4><p>We’ll need to take a quick detour to enhance our user controller a little bit, just by adding basic <em>show</em> and <em>index</em> actions. While we’re at it, let’s get rid of a deprecation warning having to do with the property key used to pass data to <strong>ja_serializer</strong> views</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/11fec6387e1bd82ea95a1b39d2e0f749/href">https://medium.com/media/11fec6387e1bd82ea95a1b39d2e0f749/href</a></iframe><p>This will set the stage for API endpoints like</p><pre>/users</pre><p>and</p><pre>/users/123</pre><p>To make these available, head back to the router and update the scope that uses your authenticated API pipeline</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5e85baf5f52f46b4385d4d39f3fdea89/href">https://medium.com/media/5e85baf5f52f46b4385d4d39f3fdea89/href</a></iframe><p>This will enable the new user-related endpoints, as well as the “rooms owned by a user” endpoint we already have in place in the room_controller.</p><p>To check out the new routing table, run the mix task</p><pre>mix phoenix.routes</pre><p>You should see something like</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7be69aa7aa29c34d31fd20262b2e2eb9/href">https://medium.com/media/7be69aa7aa29c34d31fd20262b2e2eb9/href</a></iframe><h4>Views</h4><p>We have to modify the user view so that the user object contains a link to the relationship for the rooms the user owns. <strong>ja_serializer</strong> makes it really easy to define a “has many” relationship. <a href="http://jsonapi.org/format/#document-resource-object-relationships">There’s more than one way to express this relationship</a>, but we’ll opt for a “link” — meaning a URL that’ll return the appropriate list of objects.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/634df325922ba7bc02c3a9f629b99959/href">https://medium.com/media/634df325922ba7bc02c3a9f629b99959/href</a></iframe><p>And of course we need to define a view for a room object as well</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/619935e0f4e89879011f81e3dc99c4e7/href">https://medium.com/media/619935e0f4e89879011f81e3dc99c4e7/href</a></iframe><p>One thing to observe here is that a “belongs to” relationship is defined as <strong>has_one</strong>. Again, we’ll opt for using a “link” to define this relationship. the resulting JSON representation for a user will now be something like this</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5145fd28a4c854b637887c52401c078b/href">https://medium.com/media/5145fd28a4c854b637887c52401c078b/href</a></iframe><p>and a room will be something like this</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f7f6600844edd2f819baab6525f227dd/href">https://medium.com/media/f7f6600844edd2f819baab6525f227dd/href</a></iframe><h4>Migration</h4><p>Just for fun, let’s add a DB constraint ensuring that the name of a room is unique across our whole app. Database changes are accomplished by a <a href="https://en.wikipedia.org/wiki/Schema_migration">schema migration</a>, which is a (usually) reversible discrete change to the structure of your database. When other developers check out your code change (including your migration), they can simply replay it to update their own database.</p><p>Open the DB migration file that Phoenix created as part of the <em>mix phoenix.gen.json </em>task. It should be named something like <strong>./priv/repo/migrations/20160427094427_create_room.exs</strong>, although the number (a timestamp) that the filename begins with will be different.</p><p>We’ll add just one new line at the bottom of the migration to create this name uniqueness DB constraint</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9e34c7f9ba6a05c44e9f8734b7110de0/href">https://medium.com/media/9e34c7f9ba6a05c44e9f8734b7110de0/href</a></iframe><p>And to have model-level validation error messages, we’ll want to add validation constraint to our room model (<strong>./web/models/room.ex</strong>)</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c68ac00c0a50f7e148a29bad89961e22/href">https://medium.com/media/c68ac00c0a50f7e148a29bad89961e22/href</a></iframe><p>It’s now time to run our DB migration. Head over to your terminal and run:</p><pre>mix ecto.migrate</pre><p>and now run your tests</p><pre>mix test</pre><p>They should all be passing. This is a great time to open up a PR and merge your work into master. If you want to compare your work to mine, here are all of my changes</p><p><a href="https://github.com/mike-north/peepchat-api/commit/07d768be59a2f7b59a7e915c85ee0316d7bfb9dc">Merge pull request #1 from mike-north/rooms · mike-north/peepchat-api@07d768b</a></p><h3>Building rooms in Ember</h3><p>Head on over to your UI project, and let’s get started. We’ll get some mileage out of ember-cli’s code generation by running these commands</p><pre>ember g model room name:string owner:belongs-to:user<br>ember g model user email:string password:string password_confirmation:string rooms:has-many:room</pre><p>This will set up a new Room model, with an <em>owner</em> “belongsTo” relationship of type User, and update the existing User model, to add a <em>rooms</em> “hasMany” relationship of type Room.</p><p>Now, let’s think about the UI we want to build</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3XE0hrqOKZL7y82Fx61QBQ.png" /></figure><p>To start building this UI, the next thing we’ll focus on is the leaf-level active route for the “logged in” page: <strong>./app/routes/app/index.js</strong>. A simple way to think about what’s needed here is to go back to the core purposes of a route</p><ul><li>To load and provide data to the active template(s)</li><li>To handle actions that pertain to the aforementioned data</li></ul><p>The data that we’ll need for this page consists of two things</p><ul><li>The list of rooms (asynchronous data)</li><li>Something representing a new record, originating from the client side (synchronous data)</li></ul><p>The actions we’ll need to be able to handle are</p><ul><li>createRoom — needs no argument, and will use the route’s “currentModel” state to either persist data, or render error messages into the UI</li><li>removeRoom — needs a Room record as an argument</li></ul><p>For the data, we’ll make use of Ember’s promise library: <a href="https://github.com/tildeio/rsvp.js">RSVP.js</a>. The <em>RSVP.hash</em> method is great for resolving an object that may consist of a mix of values and eventual values (a.k.a Promises). A simple example of how this might work</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6f7f06079b1c41ae26f1336baffd0dca/href">https://medium.com/media/6f7f06079b1c41ae26f1336baffd0dca/href</a></iframe><p>Now that we know how this works, we can define the overall structure of our route.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c249193b3525a0fa2540e5644f1506ec/href">https://medium.com/media/c249193b3525a0fa2540e5644f1506ec/href</a></iframe><p>We’ll want to make use of our <em>ember-cli-flash</em> awesomeness, so we should inject the appropriate service onto this route. Here’s what my route ends up looking like</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/034228253037615a3b749e0f2d1ff650/href">https://medium.com/media/034228253037615a3b749e0f2d1ff650/href</a></iframe><p>One aspect of this implementation that may be interesting to those unfamiliar with ember-data is that I’m waiting to create the ember-data record until we’re right about to send out the API request. The reason I’m doing this is because the live array returned from the invocation of</p><pre>this.store.findAll(‘room’)</pre><p>would include this result, even before the user hits the create button! Here’s what that would look like</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IT4KHAQ7GMjddTQZ17zy9A.png" /><figcaption><strong>Not an ideal user experience:</strong> We want to avoid showing records that the user is still creating on the screen</figcaption></figure><p>For this same reason, I’m explicitly unloading the record from the store in the event that there was a problem creating it.</p><p>Now we just have to update the template associated with this route, and some styles. Here’s what mine looks like</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fdc7b656de97718cc725d074410d4215/href">https://medium.com/media/fdc7b656de97718cc725d074410d4215/href</a></iframe><p>And the styles I added to my <strong>app/styles/app.scss</strong> file.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1d6d7ee0612f7a3ba594a61bc4162ad1/href">https://medium.com/media/1d6d7ee0612f7a3ba594a61bc4162ad1/href</a></iframe><p>Now, a logged in user should be able to create and destroy their rooms. Now is another good time to commit your changes, open a PR and merge it into your master branch once tests pass. Here’s what my changes on the UI side look like, if you’d care to compare</p><p><a href="https://github.com/mike-north/peepchat-ui/commit/ef2a3d0be2ccff4eabfc8a841f3d8cbfa699c804">Merge pull request #10 from mike-north/rooms · mike-north/peepchat-ui@ef2a3d0</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=817626ca4f5f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/peep-stack/building-a-performant-real-time-web-app-with-ember-fastboot-and-phoenix-part-5-817626ca4f5f">Building a performant real-time web app with Ember Fastboot and Phoenix (Part 5)</a> was originally published in <a href="https://medium.com/peep-stack">PEEP Stack</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a performant real-time web app with Ember Fastboot and Phoenix (Part 4)]]></title>
            <link>https://medium.com/peep-stack/building-a-performant-real-time-web-app-with-ember-fastboot-and-phoenix-part-4-93118e278c68?source=rss-b031920804e8------2</link>
            <guid isPermaLink="false">https://medium.com/p/93118e278c68</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[ember]]></category>
            <category><![CDATA[elixir]]></category>
            <dc:creator><![CDATA[Mike North]]></dc:creator>
            <pubDate>Wed, 27 Apr 2016 14:31:01 GMT</pubDate>
            <atom:updated>2016-08-22T01:34:19.135Z</atom:updated>
            <content:encoded><![CDATA[<h4>Logging in to our API &amp; ember-simple-auth</h4><blockquote>This article is part 4 in a series. You should first read the previous parts leading up to this, or it may not make much sense!</blockquote><blockquote><a href="https://medium.com/@mikenorth/building-a-performant-web-app-with-ember-fastboot-and-phoenix-part-1-fa1241654308#.f71xu6y19"><em>Part 1: The meeting of two well-aligned, opinionated frameworks</em></a><em><br></em><a href="https://medium.com/@mikenorth/building-a-performant-real-time-web-app-with-ember-fastboot-and-phoenix-part-2-5dd2f74c7f34#.ceiizi47m"><em>Part 2: Users and Authentication (API)</em></a><em><br></em><a href="https://medium.com/@mikenorth/building-a-performant-real-time-web-app-with-ember-fastboot-and-phoenix-part-2-1-7c98452e19bb#.j04f57sjz"><em>Part 2.1: Some small adjustments to your API</em></a><em><br></em><a href="https://medium.com/@mikenorth/building-a-performant-real-time-web-app-with-ember-fastboot-and-phoenix-part-3-dd0e03232034#.lpj9mg1n3"><em>Part 3: Users and Authentication (UI)</em></a><em><br></em><a href="https://medium.com/@mikenorth/building-a-performant-real-time-web-app-with-ember-fastboot-and-phoenix-part-4-93118e278c68#.axggzncxo"><strong><em>Part 4: Logging in to our API &amp; ember-simple-auth</em></strong></a><strong><em><br></em></strong><a href="https://medium.com/@mikenorth/building-a-performant-real-time-web-app-with-ember-fastboot-and-phoenix-part-5-817626ca4f5f"><em>Part 5: Building a CRUD resource</em></a><em><br></em><a href="https://medium.com/peep-stack/building-a-performant-real-time-web-app-with-ember-fastboot-and-phoenix-part-6-14f29bf93a25#.1exrbgfsk"><em>Part 6: Animating your UI with liquid-fire</em></a><em><br>Part 7: Room UI &amp; Messages</em></blockquote><p>Congrats on getting this far. Give yourself a high five 🙌! We are now going to get authentication working. You’ll want to create a user account in your dev environment using your newly-working authentication stuff.</p><p>Begin by installing another addon (will require stopping and then restarting ember-cli)</p><pre>ember install ember-simple-auth@simplabs/ember-simple-auth#fastboot</pre><p>A little about this addon:</p><ul><li><a href="https://github.com/simplabs/ember-simple-auth/"><strong>ember-simple-auth</strong></a> is a very lightweight library for authentication and authorization. Make sure to take a look at the latest instructions for use with Fastboot.</li></ul><h4>Session store</h4><p>By default, ember-simple-auth uses localstorage to keep track of user credentials. This won’t work for us, because localstorage is not passed along with requests, and we need Fastboot to receive our credentials in order to render the app in an authenticated (or not authenticated) state — whatever is appropriate. The good news is that there’s something else that we can use: cookies!</p><p>We’ll customize ember-simple-auth’s session store by creating a new file <strong>./app/session-stores/application.js</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e9fd6cb345cc90ca823d237d6d4c1ef1/href">https://medium.com/media/e9fd6cb345cc90ca823d237d6d4c1ef1/href</a></iframe><p>You’ll need to stop ember-cli and restart it to pick up on this change.</p><h4>Authenticator</h4><p>Another one of the important objects involved with ember-simple-auth is the authenticator. The authenticator is responsible for the particulars of retrieving a credential from some credential provider (our API). We’ll implement ours by creating a new file <strong>./app/authenticators/peepchat.js</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/60b54f5c35201e2cfa916ce3d8751539/href">https://medium.com/media/60b54f5c35201e2cfa916ce3d8751539/href</a></iframe><p>You could make your authenticator do just about anything, but in this case we’re getting a lot of functionality for free by building around the OAuth2 password grant standard. We just need to customize the API endpoint a little, which as you can see is not difficult.</p><h4>Authorizer</h4><p>The authorizer concept in ember-simple-auth deals with taking the data obtained by an Authenticator, and using it in order to communicate with a secured resource (i.e., our API). We’ll use an Authorizer that comes with ember-simple-auth, and we won’t need to alter it at all.</p><p>Create a new file <strong>./app/authorizers/oauth2.js</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6ab5999770fc73c614767cf2e832be14/href">https://medium.com/media/6ab5999770fc73c614767cf2e832be14/href</a></iframe><p>We’ll also want to integrate this authorizer with our ember-data adapter (<strong>./app/adapters/application.js</strong>), so that it passes credentials along automatically. Import the DataAdapterMixin, mix it into the adapter, and specify our authorizer via the <strong>authorizer</strong> attribute. Here’s what your adapter should look like now:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/62d38a284b2a04f3ffe6307f814137ff/href">https://medium.com/media/62d38a284b2a04f3ffe6307f814137ff/href</a></iframe><h3>Thinking about Routes</h3><p>An effective mental model to use for Ember’s routing layer is a hierarchy of routes. A given “path” of routes is active at any given time, and transitions in routing state constitute a pivot within the route tree. For example, let’s say we start with a URL <strong>/app</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JkCulhoyRv3zygUCOPvi8Q.png" /><figcaption>app.index route is active</figcaption></figure><p>and then click on a link that takes us to <strong>/auth/register</strong>, this will entail a pivot on the <strong>application </strong>route route.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FF5lW_FFY8PO73xZUTGGhg.png" /><figcaption>auth.register route is active</figcaption></figure><p>In our case, this particular routing hierarchy is useful for another reason. We want to guard particular sections of our app from being accessed in various authentication states.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*m1nLFFNSDtDO8OcyBlop5A.png" /></figure><p>Here’s what we’re aiming for</p><ul><li>The <strong>app</strong> route will check to see if users are logged in, and kick them out to <strong>auth.login</strong> if they’re not</li><li>The <strong>auth</strong> route will check to see if users are logged OUT, and kick them out to <strong>app.index </strong>if they’re logged in</li><li>The <strong>application </strong>route will handle our <em>logout </em>action, because we may have more than one section of the app that deals with authenticated users</li><li>the <strong>login </strong>route will handle our <em>doLogin </em>action (it already does)</li><li>the <strong>register</strong> route will handle our <em>doRegister</em> action (it already does)</li><li>visiting the top-level domain where our app is hosted should result in a choice for the user to either register or start chatting</li><li>once the user logs in, they should find themselves at a placeholder screen, identifying the current user (using the <strong>/user/current</strong> API endpoint we built in part 2 of this series) and giving the user an opportunity to logout</li></ul><p>Let’s start by generating a few of the missing route objects for ourselves. It’s important to understand that some of these routes already existed (i.e., the <strong>application</strong> route always exists), but were not explicitly defined within the source code for our app. In the even that Ember‘s resolver doesn’t find a specific javascript module representing an object like a route, the framework will use an instance of a basic object instead.</p><p>Head on over to your terminal and run</p><pre>ember g route application</pre><p>This should result in a few new files being created. First head over to ./<strong>app/routes/application.js </strong>and mixin ember-simple-auth’s ApplicationRouteMixin. This mixin already injects the <em>session</em> service (also an ember-simple-auth concept) onto the route, so we can quickly and easily implement the logout action as well.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/01ff87007798f0133461e995de111f01/href">https://medium.com/media/01ff87007798f0133461e995de111f01/href</a></iframe><p>You’ll need to make a small update to this route’s unit test as well, since we have a dependency on the existence of the session service. Just add the session service to the “needs” array, to bring that object into the container when this route is tested.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/18484dbfcf318fd2baeeffe8527702c3/href">https://medium.com/media/18484dbfcf318fd2baeeffe8527702c3/href</a></iframe><p>Next, let’s set up the basics for our “logged in” experience. Generate two routes using ember-cli</p><pre>ember g route app</pre><p>The app route should just check to see if the user is authenticated, and if they’re not, kick them out to the <strong>auth.login</strong> route (the login screen). Implement this in ./<strong>app/routes/app.js</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7895396ca8dd9972d3d801e5598a9b91/href">https://medium.com/media/7895396ca8dd9972d3d801e5598a9b91/href</a></iframe><p>Let’s generate an <strong>auth</strong> route (this is one of those that already existed implicitly behind the scenes) with ember-cli</p><pre>ember g route auth</pre><p>and implement some similar logic as we did in <strong>app</strong> — just flipping the condition, and using <strong>app.index</strong> as the route to send users to in the event that they’re already authenticated.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/532752037616fb186bf0b263ea36e421/href">https://medium.com/media/532752037616fb186bf0b263ea36e421/href</a></iframe><h4>Home</h4><p>We want people who arrive to this app via the top-level to have a clue as to how to proceed, and in the ember world, this means the <strong>index</strong> route. Generate an explicit index route by running</p><pre>ember g route index</pre><p>and open up <strong>app/templates/index.hbs</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ad412a9757728974857dc64c50d30207/href">https://medium.com/media/ad412a9757728974857dc64c50d30207/href</a></iframe><p>When you start up your app and visit <a href="http://localhost:4200/">http://localhost:4200</a> it should look something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xYPbEPPgzZJ6XmjytEDcyQ.png" /><figcaption>Visiting the root domain of our app</figcaption></figure><h4>The logged in experience</h4><p>Finally, let’s do something with the page users land on once they finish successfully logging in. Create a component called <strong>user-info</strong></p><pre>ember g component user-info</pre><p>This is going to be a very simple component, that allows us to render information about the currently logged in user, in a very flexible way.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/45bb6f8255cbd29414f523849ad40cb5/href">https://medium.com/media/45bb6f8255cbd29414f523849ad40cb5/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/82771a5d5ca74632482bd3e25efc08a3/href">https://medium.com/media/82771a5d5ca74632482bd3e25efc08a3/href</a></iframe><p>There’s no property <strong>currentUser</strong> on the session service yet, but we’ll put it there in a moment.</p><p>Generate an <strong>index </strong>child route of the <strong>app</strong> route (remember, the <strong>app</strong> route is the top-most parent of our logged-in experience)</p><pre>ember g route app/index</pre><p>Open up <strong>./app/templates/app/index.hbs</strong> and set it up to render a card component, welcoming the user and showing their email address</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5007477a1f236bf0bb788cb0dbf38255/href">https://medium.com/media/5007477a1f236bf0bb788cb0dbf38255/href</a></iframe><p>Think of the “block” (inside part, between the open and close tag) of the <strong>user-info</strong> component as a callback function. Because we’ve passed an argument to the <strong>{{yield}}</strong> helper within this component’s template, the “block” as being called with this argument. This allows us to make private component data available to the outside world in controlled way — a very important part of good component composability patterns.</p><h4>Configuring ember-simple-auth</h4><p>Open up your environment configuration (<strong>./config/environment.js</strong>) and add a new section for ember-simple-auth in your ENV declaration</p><pre>‘ember-simple-auth’: {<br> authenticationRoute: ‘auth.login’,<br> routeIfAlreadyAuthenticated: ‘app.index’,<br> routeAfterAuthentication: ‘app.index’<br>}</pre><p>In completeness, it should now look like this</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d0bc30c6940656499854a2ee8578ec5b/href">https://medium.com/media/d0bc30c6940656499854a2ee8578ec5b/href</a></iframe><p>We’ve got two things left, and then we’re all set with ember-simple-auth</p><h4>Logging in</h4><p>Open up your <strong>./app/routes/auth/login.js</strong> route so we can update the <em>doLogin</em> action. What we want to do is use the session service to obtain and store authentication credentials, based on the username and password that have been entered at the time the action is fired. Here’s what I ended up with:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0325c93ef7d3698ffadfbe4c7a445ec9/href">https://medium.com/media/0325c93ef7d3698ffadfbe4c7a445ec9/href</a></iframe><h4>What about session.currentUser?</h4><p>In our logged-in experience, our <strong>user-info</strong> component depends on the existence of a <strong>currentUser </strong>property on the session service. We need to ensure that whenever the user gets to this <strong>app.index</strong> route — or probably more generally, the <strong>app</strong> route and any child route, this property is available for use.</p><p>A good place to put this would be the <strong>app</strong> route’s <strong>afterModel</strong> hook. The <strong>model</strong> hook would work as well, but I don’t necessarily want to make this data available in templates (and that’s really what the <strong>model </strong>hook is for!).</p><p>Note that we’ll be making an asynchronous request, but let’s avoid using jQuery due to it not being available in Fastboot for performance reasons. We’ll use a <a href="https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API">fetch</a> polyfill instead. Go to your terminal and install the ember-network addon</p><pre>ember install ember-network</pre><p>Here’s my new <strong>app</strong> route (<strong>./app/routes/app.js</strong>)</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b5e92f4eb1baafbc46e8e69116c201ff/href">https://medium.com/media/b5e92f4eb1baafbc46e8e69116c201ff/href</a></iframe><p>You’ll have to make one tiny little change to your API. Guardian (on the phoenix side) will need you to specify the “Realm” of your authentication token. In our case, this is “Bearer”. Make this small change in your <strong>./web/router.ex</strong> and you should be good to go.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3e256ce5dbc890916e740be1040f9379/href">https://medium.com/media/3e256ce5dbc890916e740be1040f9379/href</a></iframe><p>Now is a great time to open up a PR and merge your work into master once your tests pass. If you’d like to compare your code to mine, here’s my merge commit for all the code for Part 4, so far</p><p><a href="https://github.com/mike-north/peepchat-ui/commit/4e727a17ce9a5034c35ccbea6502aca8fd87b894">Merge pull request #4 from mike-north/simple-auth · mike-north/peepchat-ui@4e727a1</a></p><p>And the commits for my small fixes, having to do with the “Bearer” token realm</p><ul><li><a href="https://github.com/mike-north/peepchat-ui/commit/cb1f090d38dc5eff44aa87e5aeadd9a9c8175f54">Use Bearer realm for token · mike-north/peepchat-ui@cb1f090</a></li><li><a href="https://github.com/mike-north/peepchat-api/commit/bb1e08aae9ecd2817f3a12267baf6a9eab550531">Add bearer realm to Guardian.Plug.VerifyHeader · mike-north/peepchat-api@bb1e08a</a></li></ul><h3>Toast</h3><h4>Delicious global notifications</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*jMlD8ykrCY4g6fe4oz_fXA.jpeg" /><figcaption>Material design calls messages that pop up from the bottom of the screen “toasts”</figcaption></figure><p>Although our login, registration and logout all work, we don’t yet do a great job giving feedback to users about success and/or failure. To fix this, we’ll make use of another great ember addon by <a href="https://medium.com/u/a4c91dcedec4">Lauren Elizabeth Tan</a> called ember-cli-flash, and we’ll wrap it with more <a href="http://materializecss.com/">Materialize</a> style goodness. Install it using ember-cli, per usual</p><pre>ember install ember-cli-flash</pre><p>And while you’re at it, create two new components</p><ul><li><strong>x-toasts</strong> for the notification center</li><li><strong>x-toast</strong> for an individual notification</li></ul><p>Put the x-toasts component in your <strong>app/templates/application.hbs</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0e3342d6d5a62bb5e94ce61e8c61cbaf/href">https://medium.com/media/0e3342d6d5a62bb5e94ce61e8c61cbaf/href</a></iframe><p>We need to do one interesting thing in the x-toasts component: reverse the order of the array of messages. This is because, while ember-cli-flash assumes the newest message should be on the top of the queue, we want it to be on the bottom of the queue (since they come up from the bottom)</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/06ebcf6d2503b256508d7e0004255576/href">https://medium.com/media/06ebcf6d2503b256508d7e0004255576/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0970c40291884a8004a789e0208be06a/href">https://medium.com/media/0970c40291884a8004a789e0208be06a/href</a></iframe><p>The toast component is a little more interesting for two reasons</p><ul><li>we want to prevent memory leaks, so we need to ensure that we clean up data associated with the flash message if the component is destroyed</li><li>We need to add a class to the component very shortly after it is inserted into the DOM, so we can use a CSS animation as the component spawns</li><li>The “exiting” property is already built in to ember-cli-flash, we just need to bind it to a class via <strong>classNameBindings</strong>.</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9b480c6ed1e49d47ab752bc2a70e3557/href">https://medium.com/media/9b480c6ed1e49d47ab752bc2a70e3557/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1d20855cf0f1a1659644f5471033a6d9/href">https://medium.com/media/1d20855cf0f1a1659644f5471033a6d9/href</a></iframe><p>You’ll also want to add some styles to your <strong>./app/styles/app.scss</strong> to make the messages look pretty</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4711f787fa4a2633886330d223fd884c/href">https://medium.com/media/4711f787fa4a2633886330d223fd884c/href</a></iframe><p>And customize some ember-cli-flash configuration options so that, by default:</p><ul><li>the “exiting” property is added to each flash message <strong>5000ms</strong> after it is spawned</li><li><strong>375ms</strong> later the flash message is removed from the DOM</li></ul><p>To set this up, add the following to your ENV declaration in <strong>./config/environment.js</strong></p><pre>flashMessageDefaults: {<br> timeout: 3000,<br> extendedTimeout: 375<br>}</pre><p>The last thing we need to do is actually use these messages for our three user interactions: register, login and logout</p><h4>Register</h4><p>Using ember-cli-flash is quite easy. Basically you inject the <strong>flashMessages</strong> service onto an object, and then call a method on it in order to generate a message. Everything else is taken care of by the addon</p><p>For example, in our application route..</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7a6b32d9370f692c144f21151bd1f5d5/href">https://medium.com/media/7a6b32d9370f692c144f21151bd1f5d5/href</a></iframe><p>Typically we’d want to handle error scenarios, but in this case there’s not much that can go wrong since we’re erasing a cookie that ember-simple-auth created for us.</p><h4>Login</h4><p>However, there are plenty of things that can go wrong with a login. Here are the outcomes I’d like to focus on and handle</p><ul><li>Successful login</li><li>Attempted login, but was not successful</li><li>All other API errors</li></ul><p>Basically, it would be good to have a specific error in the event that our API returns a 401 (Unauthorized) error, and a generic error for everything else. Here’s what I ended up with in my <strong>auth.login</strong> route</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/df63ac9342e60ccb6b2b1fe0131e7909/href">https://medium.com/media/df63ac9342e60ccb6b2b1fe0131e7909/href</a></iframe><p>Notice that the check I’m making for 401 errors takes into account that the API may be returning more than one error message — I’m checking for <em>any </em>error that has a 401 status code in the array.</p><h4>Register</h4><p>Registration can go wrong as well, but we’ll just handle generic success and failure cases. Head over to your <strong>./app/routes/auth/register.js</strong>, inject the <strong>flashMessages</strong> service, and use it in handlers for success and failure scenarios of the <strong>save()</strong> operation.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/17cffc6ee1c9d9f0d2e56161da298b23/href">https://medium.com/media/17cffc6ee1c9d9f0d2e56161da298b23/href</a></iframe><p>Great job! We’re done with notifications for now. Start your app up, and try some login and registration attempts. You should see messages popping up on the screen: red for errors, dark grey for others.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YLlktUiImXMuyuWVV41OpQ.png" /><figcaption>Material design “toasts”, implemented with ember-cli-flash</figcaption></figure><p>Try resizing your screen, the notifications will be placed differently for phone, tablet, and desktop browser sized screens</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gZb-qdC23Pu_yrOqP0Zong.png" /><figcaption>Material design “toast” notifications, optimized for phone-sized viewports</figcaption></figure><p>Now is a great time to make a git commit, open up a PR, and merge into your master branch when your tests pass. If you want to compare to my code changes for this second piece of Part 4, here is my merge commit</p><p><a href="https://github.com/mike-north/peepchat-ui/commit/edd42818219a28120036ad0e8609c7f1d85a59dc">Merge pull request #5 from mike-north/toasts · mike-north/peepchat-ui@edd4281</a></p><p>In part 5, we’ll start adding some real-time functionality, going back to the API side to play with <a href="http://www.phoenixframework.org/docs/channels">Phoenix Channels</a>!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=93118e278c68" width="1" height="1" alt=""><hr><p><a href="https://medium.com/peep-stack/building-a-performant-real-time-web-app-with-ember-fastboot-and-phoenix-part-4-93118e278c68">Building a performant real-time web app with Ember Fastboot and Phoenix (Part 4)</a> was originally published in <a href="https://medium.com/peep-stack">PEEP Stack</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a performant real-time web app with Ember Fastboot and Phoenix (Part 3)]]></title>
            <link>https://medium.com/peep-stack/building-a-performant-real-time-web-app-with-ember-fastboot-and-phoenix-part-3-dd0e03232034?source=rss-b031920804e8------2</link>
            <guid isPermaLink="false">https://medium.com/p/dd0e03232034</guid>
            <category><![CDATA[ember]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[elixir]]></category>
            <dc:creator><![CDATA[Mike North]]></dc:creator>
            <pubDate>Sun, 24 Apr 2016 15:31:01 GMT</pubDate>
            <atom:updated>2016-05-11T19:30:32.441Z</atom:updated>
            <content:encoded><![CDATA[<h4>Users and Authentication (UI)</h4><blockquote>This article is part 3 in a series. You should first read the previous parts leading up to this, or it may not make much sense!</blockquote><blockquote><a href="https://medium.com/@mikenorth/building-a-performant-web-app-with-ember-fastboot-and-phoenix-part-1-fa1241654308#.f71xu6y19"><em>Part 1: The meeting of two well-aligned, opinionated frameworks</em></a><em><br></em><a href="https://medium.com/@mikenorth/building-a-performant-real-time-web-app-with-ember-fastboot-and-phoenix-part-2-5dd2f74c7f34#.ceiizi47m"><em>Part 2: Users and Authentication (API)</em></a><em><br></em><a href="https://medium.com/@mikenorth/building-a-performant-real-time-web-app-with-ember-fastboot-and-phoenix-part-2-1-7c98452e19bb#.j04f57sjz"><em>Part 2.1: Some small adjustments to your API</em></a><em><br></em><a href="https://medium.com/@mikenorth/building-a-performant-real-time-web-app-with-ember-fastboot-and-phoenix-part-3-dd0e03232034#.lpj9mg1n3"><strong><em>Part 3: Users and Authentication (UI)</em></strong></a><strong><em><br></em></strong><a href="https://medium.com/@mikenorth/building-a-performant-real-time-web-app-with-ember-fastboot-and-phoenix-part-4-93118e278c68#.axggzncxo"><em>Part 4: Logging in to our API &amp; ember-simple-auth</em></a><em><br></em><a href="https://medium.com/@mikenorth/building-a-performant-real-time-web-app-with-ember-fastboot-and-phoenix-part-5-817626ca4f5f"><em>Part 5: Building a CRUD resource</em></a><em><br></em><a href="https://medium.com/peep-stack/building-a-performant-real-time-web-app-with-ember-fastboot-and-phoenix-part-6-14f29bf93a25#.1exrbgfsk"><em>Part 6: Animating your UI with liquid-fire</em></a><em><br>Part 7: Room UI &amp; Messages</em></blockquote><p>Ok, keep your API running, and open up your Ember UI project. We’ll want to install a couple of dependencies, which will require stopping and then restarting ember-cli</p><pre>ember install ember-cp-validations<br>ember install ember-materialize-shim<br>ember install ember-route-action-helper</pre><p>A little about these addons</p><ul><li><a href="https://github.com/offirgolan/ember-cp-validations"><strong>ember-cp-validations</strong></a> is a client-side validation library for Ember.js models.</li><li><a href="https://github.com/levanto-financial/ember-materialize-shim"><strong>ember-materialize-shim</strong></a> adds <a href="http://materializecss.com/">Materialize</a> to your app’s asset pipeline.</li><li><a href="https://github.com/DockYard/ember-route-action-helper"><strong>ember-route-action-helper</strong></a> allows us to save some time when using actions in top-level components.</li></ul><h4>Some cleanup</h4><p>Go ahead and remove everything in <strong>app/templates/application.hbs</strong> except for</p><pre>{{outlet}}</pre><p>and delete <strong>app/styles/app.css</strong> if it still exists. We’ll add a little more styling to your app, via the root SCSS file (<strong>app/styles/app.scss</strong>).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9747826f368f17718f48e5c661452438/href">https://medium.com/media/9747826f368f17718f48e5c661452438/href</a></iframe><h4>Component: Text Field</h4><p>We want to build a text field component, based off of the one you can find in the <a href="http://materializecss.com/forms.html">MaterializeCSS</a> documentation. The structure of the HTML should look like this</p><pre>&lt;div class=”input-field”&gt;<br>  &lt;input type=”text”&gt;<br>  &lt;label&gt;First Name&lt;/label&gt;<br>&lt;/div&gt;</pre><p>out of the box, we get some nice support for “hovering” labels — largely based off of some clever CSS. Additionally, we can stylize an “invalid” or “valid” state, and accompany with an error message if we like</p><pre>&lt;div class=”input-field”&gt;<br>  &lt;input class=”validate invalid” type=”text”&gt;<br>  &lt;label data-error=”Wrong first name”&gt;<br>    First Name<br>  &lt;/label&gt;<br>&lt;/div&gt;<br></pre><p>Let’s start simple. <a href="http://emberjs.com/api/classes/Ember.Component.html">Ember components</a> are defined by a top-level element, and then contents within that element. In our case, the “root” element of this component will be the DIV with the <em>input-field</em> class on it.</p><p>Begin by using ember-cli to build a component with an appropriate name. This name must have a dash in it, for reasons that are beyond the scope of this article. Let’s use <em>x-input</em>. Run this in your terminal:</p><pre>ember g component x-input</pre><p>ember-cli will generate</p><ul><li><strong>./app/components/x-input.js</strong> — a component javascript module</li><li><strong>./app/templates/components/x-input.hbs</strong> — a handlebars template for your component</li><li><strong>./tests/integration/components/x-input-test.js</strong> a passing component integration test.</li></ul><p>Now is a good time to stop and think about our component’s contract with the outside world. Treat this like a Public API — the internals of your component may change, but as long as the contract with the outside world remains the same, things should be smooth and easy. We need three things:</p><ul><li>The value that the component is bound to, which is updated based on the user’s changes</li><li>The label of the field</li><li>The type of the field (think: HTML input type)</li><li>Any error messages to display — we’ll add some nice client-side validation later, but that’s not a concern of this component</li></ul><p>The following should do for now:</p><pre><br>{{x-input<br>   type=”password”<br>   label=”Password”<br>   value=myPassword<br>   errors=myErrors }}</pre><p>Open up the component’s JavaScript module, and the handlebars template side by side. We’ll be working in these two files for a little while.</p><p>First, we’ll want to add the <em>input-field</em> class to the root element of the component. To do this, add the following property:</p><pre>classNames: [&#39;input-field&#39;]</pre><p>Also, we’ll want to default to a “text” input by default, so add this property too</p><pre>type: “text”</pre><p>Start your template off with something like this</p><pre>&lt;input<br>  value={{value}}<br>  type={{type}}<br>  onkeyup={{action (mut value) value=&#39;target.value&#39;}} /&gt;<br>&lt;label&gt;{{label}}&lt;/label&gt;</pre><p>What we’re doing here is using the “keyup” DOM event as a trigger to update the “value” property of our component, using the “target.value” property of the DOM event that’s fired.</p><p>Next let’s handle the error messages. We’ll want a comma-separated string of all error messages to show up as the label’s data-error attribute, but our component contract should be an array. To apply this transformation, a computed property will be useful. Go back to the component javascript module and add</p><pre>_errorMessages: computed(‘errors.[]’, function() {<br>  return (this.get(‘errors’) || []).join(‘, ‘);<br>})</pre><p>and in the template, bind this new _errorMessages property to the label’s data-error attribute</p><pre>&lt;label data-error={{_errorMessages}}&gt;{{label}}&lt;/label&gt;</pre><p>Now, this error message will only show up in the event that the right classes are on the input. We’ll want to set up some new computed properties to implement the following behavior</p><ul><li>If the component’s value property is non-empty, we’ll want the input to have the “validate” class. This will prevent the component from showing up with validation errors when the user first sees it and it’s blank.</li><li>If the component is validating (due to the value being non-empty), and the errors array property has one or more objects in it, the input should additionally have the “invalid” class, otherwise it should have the “valid” class.</li></ul><p>This can be done completely using Ember’s built-in handlebars helpers</p><pre>&lt;input<br> value={{value}}<br> type={{type}}<br> class=”{{if value<br>   (concat<br>     “validate ”<br>     (if errors.length “invalid” “valid”)<br>   )<br> }}”<br> onkeyup={{action (mut value) value=’target.value’}}&gt;</pre><p>Your component should now be implemented like this</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e95cbd294379e5a16db78f806c30f978/href">https://medium.com/media/e95cbd294379e5a16db78f806c30f978/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3fd262075c35a3a10eac7584ec40bdcc/href">https://medium.com/media/3fd262075c35a3a10eac7584ec40bdcc/href</a></iframe><p>Finally, we need to override Materialize’s built-in validation stuff. We will replace it with something much more sophisticated and easy to use.</p><p>Go to your terminal, and make a new initializer with ember-cli</p><pre>ember g initializer materialize-setup</pre><p>You want to override a function validate_field, if it exists on the window object. The initializer should end up looking like this</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3a22d297d76cf12b00c105a2a14e10f8/href">https://medium.com/media/3a22d297d76cf12b00c105a2a14e10f8/href</a></iframe><h4>Component: Card</h4><p>Next, let’s create a card component. For our purposes, cards will basically have three things</p><ul><li>A title</li><li>A body</li><li>A footer with a button in it, and that button’s label should be customizable</li></ul><p>Head on over to your terminal, and use ember-cli to kick start this</p><pre>ember g component x-card</pre><p>Now let’s think about the contract we want between this component and the rest of our app. Something like this should work nicely:</p><pre>{{#x-card<br>    title=&quot;Login to Peepchat&quot;<br>    onsubmit=myAction<br>    buttonText=&quot;Login&quot;}}</pre><pre>  &lt;p&gt; This is the body of the card &lt;/p&gt;</pre><pre>{{/x-card}}</pre><p>Open up the <strong>x-card.js</strong> and <strong>x-card.hbs </strong>side-by-side. The javascript side is extremely simple here</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/28b994c19ce515cf3c965c4bd9884245/href">https://medium.com/media/28b994c19ce515cf3c965c4bd9884245/href</a></iframe><p>And the handlebars is pretty straight forward as well</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4b5dfbb217b1f7dd2b4a7ed65d075174/href">https://medium.com/media/4b5dfbb217b1f7dd2b4a7ed65d075174/href</a></iframe><p>You’ll see here that I allow for the possibility that either the <em>onsubmit</em> action or <em>title </em>property don’t exist. It’s a good practice to make your component behave as reasonably as possible in the event that it has been passed “empty” state.</p><h4>Building out the login and registration pages</h4><p>Now it’s time to use our compose our two new components to build out our login and registration pages. For reasons that will become clear in a moment, we’ll want each of these cards to be their own specialized component</p><p>Create two new routes</p><pre>ember g route auth/login<br>ember g route auth/register</pre><p>and two new components</p><pre>ember g component login-card<br>ember g component register-card</pre><p>For now, login-card and register-card will be components that each contain the card, which contain the form for the login and registration pages, respectively. For now, don’t worry about the javascript modules for the components — we’ll just use the handlebars templates to encapsulate a card for each page</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/342b72b744ffabe5b6868bcba128bdbc/href">https://medium.com/media/342b72b744ffabe5b6868bcba128bdbc/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1abac76a7beff76d74e85317126a2a0d/href">https://medium.com/media/1abac76a7beff76d74e85317126a2a0d/href</a></iframe><p>Let’s start with the login page. Go to <a href="http://localhost:4200/auth/login">http://localhost:4200/auth/login</a> and open up your <strong>./app/templates/auth/login.hbs</strong>. You’ll want to wrap the Materialize grid around your cards, and use your x-input components within the body of the card. Something like this</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d0417107c97524c8a6e67ded98b71f7e/href">https://medium.com/media/d0417107c97524c8a6e67ded98b71f7e/href</a></iframe><p>You should now see something like this in your browser</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Iz4_C76K33Xx6SHdSzox7Q.png" /></figure><p>If you click on the “login” button, you should see an error message in your web console, indicating that no <em>doLogin</em> action has been found on your route. Open up <strong>./app/routes/auth/login.js</strong> and add a placeholder action so you can see that everything is wired up</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bf935511e49fd144a90d5d50fa296d4e/href">https://medium.com/media/bf935511e49fd144a90d5d50fa296d4e/href</a></iframe><p>Head on over to <strong>./app/templates/auth/register.hbs</strong> and do basically the same thing as for login, but add an extra field for password confirmation</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/390b187c8b2957a50543dc4ff7f6155c/href">https://medium.com/media/390b187c8b2957a50543dc4ff7f6155c/href</a></iframe><p>And add a similar placeholder action to the register route (<strong>./app/routes/auth/register.js</strong>)</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f80160040045cd365d145cff3293a712/href">https://medium.com/media/f80160040045cd365d145cff3293a712/href</a></iframe><p>If you go to <a href="http://localhost:4200/auth/register,">http://localhost:4200/auth/register,</a> you should see something like this</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qvahTUacPWhus9cSEEj4qQ.png" /><figcaption>Registration page</figcaption></figure><p>Awesome! Now let’s run our tests by going to <a href="http://localhost:4000/tests,">http://localhost:4000/tests</a>, you should see that a couple are now failing. You’ll need to update the component integration tests for <em>login-card and register-card</em> as follows</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/701a8e42ab07e9a3c5838f85abf8f896/href">https://medium.com/media/701a8e42ab07e9a3c5838f85abf8f896/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d29231210a97452d981a65fbee5f0feb/href">https://medium.com/media/d29231210a97452d981a65fbee5f0feb/href</a></iframe><p>Your tests should now pass. This is a good time to make a git commit, open up a pull request, and merge it into master. Thanks to the work we did in <a href="https://medium.com/@mikenorth/building-a-performant-web-app-with-ember-fastboot-and-phoenix-part-1-fa1241654308">part 1</a>, your UI will auto-deploy when your tests pass in <a href="http://travis-ci.org/">CI</a> 🙌.</p><p>If you want to compare your code to mine at this point, here’s what my project looks like</p><p><a href="https://github.com/mike-north/peepchat-ui/commit/61455c9aa28117ad8bb90c8a4385b1a814368b0e">Merge pull request #1 from mike-north/login-and-register · mike-north/peepchat-ui@61455c9</a></p><h4>Users in the UI</h4><p>Next, let’s create a model for users</p><pre>ember g model user email:string password:string password_confirmation:string</pre><p>Now we need to return this model from our ./<strong>app/routes/auth/register.js</strong> route’s model hook</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4be6cac44a2173286dc59d768f076c18/href">https://medium.com/media/4be6cac44a2173286dc59d768f076c18/href</a></iframe><p>We’ll do something similar to the <strong>./app/routes/auth/login.js</strong> route, but return a plain javascript object with the same properties instead</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/921e3d7841b1c8a5b837f6b82bb8e87d/href">https://medium.com/media/921e3d7841b1c8a5b837f6b82bb8e87d/href</a></iframe><p>I’m doing it this way for a few reasons</p><ul><li>I want to demonstrate that using ember-data records and plain javascript are both acceptable, and can both work with client-side validations</li><li>Registering a new user represents a “Create” operation, and I’ll be hijacking some of ember-data’s record creation stuff to implement it</li><li>Per the OAuth2 standard, the response we expect from logging in is a token — NOT a user object. This is enough of a departure from typical CRUD operations that it makes sense to use lower-level tools like <a href="https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API">fetch</a>.</li></ul><p>Now, in the register page’s template (<strong>./app/templates/auth/register.hbs</strong>) we’ll want to pass the models into the respective card components</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fac61d64290b5be3e73eb6fa517fa210/href">https://medium.com/media/fac61d64290b5be3e73eb6fa517fa210/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3acf98c0ea8295c04ef09303afadaf6c/href">https://medium.com/media/3acf98c0ea8295c04ef09303afadaf6c/href</a></iframe><p>Because our validation criteria will be different depending on whether a user is registering or logging in (password_confirmation doesn’t matter when logging in), we’ll put the client-side validation logic onto the components instead of the model.</p><p>It’s nice to have things like validations defined in a single place, so that changes can be made across the whole app quickly and easily. Let’s create a “util” for this (a generic javascript module). Run this in your terminal</p><pre>ember g util user-validations</pre><p>This will create a new file <strong>./app/utils/user-validations.js</strong> and an accompanying unit test. We’ll start with some basic validations that will cover our register and login use cases.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/522ff4266b61a4b6e5a1795a833a0b4e/href">https://medium.com/media/522ff4266b61a4b6e5a1795a833a0b4e/href</a></iframe><p>You’ll need to update your tests as well</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/aa0234f0566d6a39ca48c52ecbd14889/href">https://medium.com/media/aa0234f0566d6a39ca48c52ecbd14889/href</a></iframe><p>Obviously these aren’t meaningful tests. We’ll come back in a future part of this series to catch up on proper test writing. Now we need to hook these validations up in your <em>login-card</em> and <em>register-card</em> components. We will do so by simply importing the respective exports from the <em>user-validations</em> module we just created, and passing them into the appropriate components, as follows:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a6921bfcf811ada764fe2c1322b4c514/href">https://medium.com/media/a6921bfcf811ada764fe2c1322b4c514/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e9c9dbbb7f7c5f144441fc50087d53de/href">https://medium.com/media/e9c9dbbb7f7c5f144441fc50087d53de/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/91a94cecebe876356993ba3c67121b24/href">https://medium.com/media/91a94cecebe876356993ba3c67121b24/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b7bdddfcb3d334d6c3cee3086ab6ec0c/href">https://medium.com/media/b7bdddfcb3d334d6c3cee3086ab6ec0c/href</a></iframe><p>Check out your login (<a href="http://localhost:4200/auth/login">http://localhost:4200/auth/login</a>) and register (<a href="http://localhost:4200/auth/register">http://localhost:4200/auth/register</a>) pages now, and try typing in a few values for usernames and passwords. You should see client-side validation messages coming through when appropriate</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WcGGdTzvJ1l46Pr-scoeOg.png" /><figcaption>Login page, with client-side validations</figcaption></figure><p>This is another great opportunity to make a commit, open a pull request, and merge these changes into your project. If you want to compare your changes to mine, they are here:</p><p><a href="https://github.com/mike-north/peepchat-ui/commit/f1b0faa42ccd35ae5f00366311f0dbc2aa769214">Merge pull request #2 from mike-north/cs-validations · mike-north/peepchat-ui@f1b0faa</a></p><h4>Pointing to the right API</h4><p>Time to hook registration up to our API. First, let’s make sure ember-data is pointing to the correct place in our dev and production environments. The best way to do this is via environment configuration.</p><p>Open up <strong>./app/config/environment.js</strong> and at the following to the ENV variable declaration</p><pre>DS: {<br> host: &#39;<a href="http://localhost:4000&#39;">http://localhost:4000&#39;</a>,<br> namespace: &#39;api&#39;<br>}</pre><p>Then, look down toward the bottom of the file to find something like this</p><pre>if (environment === &#39;production&#39;) {</pre><pre>}</pre><p>In the case that we’re in the production environment, we’ll want to point ember-data to our production API.</p><p><strong><em>REMEMBER TO REPLACE THE HOST WITH YOUR OWN HEROKU API HOSTNAME</em></strong></p><pre>if (environment === &#39;production&#39;) {<br> ENV.DS.host = &#39;<a href="https://frozen-coast-87972.herokuapp.com&/#39;">https://frozen-coast-87972.herokuapp.com</a>&#39;;<br>}</pre><p>Now, use ember-cli to generate an adapter called ‘application’. This will be the default adapter used throughout your app</p><pre>ember g adapter application</pre><p>You’ll want to pull in the environment configuration, and set up your adapter as follows:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/23bfae4450e34d8eb01067ee22cc7ee2/href">https://medium.com/media/23bfae4450e34d8eb01067ee22cc7ee2/href</a></iframe><p>You’ll notice that we’re customizing the URL for creating “user” records. By default this would be</p><pre>POST <a href="http://localhost:4000/api/users">http://localhost:4000/api/users</a></pre><p>But of course we want it to be</p><pre>POST <a href="http://localhost:4000/api/register">http://localhost:4000/api/register</a></pre><h4>Registration</h4><p>Now go to your register route, and update it so that the <em>doRegister</em> action actually saves the record, and then sends the user to the login screen</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ae9acc6cfde48ed24da5eb1ca76490cc/href">https://medium.com/media/ae9acc6cfde48ed24da5eb1ca76490cc/href</a></iframe><p>Try registering a user, it should now work! This is a great time to save your work, make a PR and merge it into your master branch. If you want to compare your work to mine, here it is</p><p><a href="https://github.com/mike-north/peepchat-ui/commit/41aa8a2129558d7cf15996f4ee59d6493592fbee">Merge pull request #3 from mike-north/register-ui · mike-north/peepchat-ui@41aa8a2</a></p><p>The next part of this series will deal with actually logging in! Stay tuned!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dd0e03232034" width="1" height="1" alt=""><hr><p><a href="https://medium.com/peep-stack/building-a-performant-real-time-web-app-with-ember-fastboot-and-phoenix-part-3-dd0e03232034">Building a performant real-time web app with Ember Fastboot and Phoenix (Part 3)</a> was originally published in <a href="https://medium.com/peep-stack">PEEP Stack</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>