<?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 Tommaso Visconti on Medium]]></title>
        <description><![CDATA[Stories by Tommaso Visconti on Medium]]></description>
        <link>https://medium.com/@tommyblue?source=rss-b3ae6c5cd525------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*orjBvrYRP8LocgAwLlp1MQ.png</url>
            <title>Stories by Tommaso Visconti on Medium</title>
            <link>https://medium.com/@tommyblue?source=rss-b3ae6c5cd525------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 21:55:01 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@tommyblue/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[Complete backup of a SmugMug account]]></title>
            <link>https://medium.com/@tommyblue/complete-backup-of-a-smugmug-account-70d47d54ddb7?source=rss-b3ae6c5cd525------2</link>
            <guid isPermaLink="false">https://medium.com/p/70d47d54ddb7</guid>
            <category><![CDATA[smugmug]]></category>
            <category><![CDATA[photography]]></category>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[backup]]></category>
            <dc:creator><![CDATA[Tommaso Visconti]]></dc:creator>
            <pubDate>Sat, 06 Apr 2019 20:25:16 GMT</pubDate>
            <atom:updated>2020-07-27T20:47:08.067Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iIkS_1VpWkXfEeNnX-hFOQ.jpeg" /></figure><p>I’m a happy customer of the <a href="https://www.smugmug.com/">SmugMug</a> service where I store all my photos (~50GB divided in ~120 galleries).</p><p>I really love their interface, the mobile app, the website, etc. but they miss a very important feature IMHO: <strong>it’s not possible to make a complete download of all the photos</strong>.</p><p>That’s why I wrote a <a href="https://github.com/tommyblue/smugmug-backup">program</a> that does it.</p><p>SmugMug provides a feature which allows users to download a zip archive of a gallery, but I don’t want to browse and download all of them. Moreover, download is async: you ask for a download and you’ll receive an email in a few minutes with a link to the archive.</p><p><a href="https://api.smugmug.com/">SmugMug APIs</a> seemed promising so I decided to write my own app to accomplish this purpose.</p><p>And I did it in a few days!</p><p>The app is written in golang, except a little util (written by SmugMug) which requires Python3. You can find everything in my <a href="https://github.com/tommyblue/smugmug-backup">GitHub repository</a>.</p><p>UPDATE 27/07/2020</p><p>To replace the unhandy app from SmugMug to obtain the API credentials, I wrote a simple web app that <a href="https://github.com/tommyblue/smugmug-api-authenticator">you can get from GitHub</a> or directly use from Heroku at <a href="https://smugmug-api-authenticator.herokuapp.com/">https://smugmug-api-authenticator.herokuapp.com/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=70d47d54ddb7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to add a JS frontend to an API-only Phoenix app]]></title>
            <link>https://medium.com/@tommyblue/how-to-add-a-js-frontend-to-an-api-only-phoenix-app-354f71179ef6?source=rss-b3ae6c5cd525------2</link>
            <guid isPermaLink="false">https://medium.com/p/354f71179ef6</guid>
            <category><![CDATA[phoenix-framework]]></category>
            <category><![CDATA[elixir]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[phoenix]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Tommaso Visconti]]></dc:creator>
            <pubDate>Tue, 23 Oct 2018 20:11:41 GMT</pubDate>
            <atom:updated>2018-10-29T09:19:16.742Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*plprROpsS4DACsJWOUjVMA.jpeg" /></figure><p>If you generated a <a href="https://phoenixframework.org/">Phoenix</a> app with the --no-brunch option you probably needed an API backend app.</p><p>What if, with your app growing, you realize you’d like to add also some frontend code? This short how-to will show you how integrate a <a href="https://webpack.js.org/">Webpack</a> based app with support to <a href="https://www.typescriptlang.org/">Typescript</a>, <a href="https://reactjs.org/">React</a> and <a href="https://sass-lang.com/">Sass</a>.</p><p><em>If, instead, you have a standard Phoenix app (with Brunch support) and you want to switch to webpack, then</em><a href="https://medium.com/@tommyblue/react-sass-typescript-with-phoenix-framework-using-webpack-af0c8f7282d9"><em> read my previous article</em></a><em>.</em></p><h3>Create the Webpack scaffolding</h3><p>To begin, let’s create some initial files in the frontend folder (which needs to be created):</p><pre>mkdir -p frontend/src<br><em>cd</em> frontend/<br>npm init<br>touch src/index.tsx<br>touch src/style.scss</pre><p><em>All future commands are supposed to be ran from within the </em><em>frontend/ folder.</em></p><p>The npm init helped you create an initial package.json file. It is now time to add some required packages.</p><p><strong>Webpack</strong></p><pre>yarn add -D webpack webpack-cli</pre><p><strong>Babel</strong></p><pre>yarn add -D babel-loader @babel/core @babel/preset-env</pre><p><strong>Sass and CSS</strong></p><pre>yarn add -D style-loader css-loader sass-loader node-sass</pre><p><strong>Typescript</strong></p><pre>yarn add -D typescript awesome-typescript-loader</pre><p><strong>React</strong> and its typings</p><pre>yarn add react react-dom<br>yarn add -D @types/react @types/react-dom</pre><p>Webpack’s <strong>extract-text plugin</strong> (I’m using @next version because of an <a href="https://stackoverflow.com/questions/51383618/chunk-entrypoints-use-chunks-groupsiterable-and-filter-by-instanceof-entrypoint">annoying bug</a> in the stable version):</p><pre>yarn add -D extract-text-webpack-plugin@next</pre><p>Don’t forget to add the node_modules folder to your .gitignore file or you’ll commit a lot of useless files:</p><pre><em>echo</em> node_modules &gt; ../.gitignore</pre><p>Also create Typescript config and linting files:</p><p>tsconfig.json</p><pre>{<br>	&quot;compilerOptions&quot;: {<br>		&quot;allowJs&quot;: true,<br>		&quot;baseUrl&quot;: &quot;js&quot;,<br>		&quot;jsx&quot;: &quot;react&quot;,<br>		&quot;module&quot;: &quot;commonjs&quot;,<br>		&quot;moduleResolution&quot;: &quot;node&quot;,<br>		&quot;noImplicitAny&quot;: true,<br>		&quot;outDir&quot;: &quot;ts-build&quot;,<br>		&quot;sourceMap&quot;: false,<br>		&quot;target&quot;: &quot;es5&quot;<br>	},<br>	&quot;include&quot;: [<br>		&quot;./src/**/*&quot;<br>	]<br>}</pre><p>tslint.json</p><pre>{<br>  &quot;extends&quot;: [&quot;tslint:recommended&quot;, &quot;tslint-react&quot;],<br>  &quot;rules&quot;: {<br>    &quot;no-console&quot;: [false]<br>  }<br>}</pre><p><em>If, like me, you’re running an editor that supports linting and you’ll run it from the main app folder, you probably want to symlink the </em><em>tslint.json from there (or configure the editor linter to find it inside the </em><em>frontend/ folder).</em></p><p>Final step is to create the webpack configuration with the frontend/webpack.config.js file:</p><pre>const env =  process.env.NODE_ENV<br>const path =  require(&#39;path&#39;);</pre><pre>const ExtractTextPlugin =  require(&quot;extract-text-webpack-plugin&quot;);</pre><pre>module.exports = {<br>	entry: [&#39;./src/index.tsx&#39;, &#39;./src/style.scss&#39;],<br>	output: {<br>		path: path.resolve(__dirname, &quot;../priv/static&quot;),<br>		filename: &quot;js/app.js&quot;<br>	},<br>	resolve: {<br>		extensions: [&quot;.ts&quot;, &quot;.tsx&quot;, &quot;.js&quot;, &quot;.jsx&quot;],<br>		modules: [&quot;deps&quot;, &quot;node_modules&quot;]<br>	},<br>	module: {<br>		rules: [{<br>			test: /\.scss$/,<br>			use: ExtractTextPlugin.extract({<br>				use: [{<br>					loader: &quot;css-loader&quot;,<br>					options: {<br>						minimize: true,<br>						sourceMap: env ===  &#39;production&#39;,<br>					}<br>				}, {<br>					loader: &quot;sass-loader&quot;,<br>					options: {<br>						includePaths: [path.resolve(&#39;node_modules&#39;)]<br>					}<br>				}],<br>				fallback: &quot;style-loader&quot;<br>			})<br>		}, {<br>			test: /\.tsx?$/,<br>			loader: &quot;awesome-typescript-loader&quot;<br>		}, {<br>			test: /\.js$/,<br>			exclude: /(node_modules|bower_components)/,<br>			use: {<br>				&#39;loader&#39;: &#39;babel-loader&#39;,<br>				options: {<br>					presets: [&#39;@babel/preset-env&#39;]<br>				}<br>			}<br>		}]<br>	},<br>	plugins: [<br>		new  ExtractTextPlugin({<br>		filename: &quot;css/app.css&quot;<br>	})<br>	]<br>};</pre><p>At this point the frontend pipeline is ready to be executed. From the frontend folder, run</p><pre>webpack --watch-stdin --progress --color</pre><p>and, hopefully, your app will be correctly compiled.</p><h3>Run the pipeline with Phoenix server</h3><p>We want to run the pipeline when we execute mix phx.server. This can be done editing the config/dev.exs file:</p><pre>watchers: [<br>  node: [<br>    &quot;node_modules/webpack/bin/webpack.js&quot;, &quot;--watch-stdin&quot;, &quot;--progress&quot;, &quot;--color&quot;,<br>    cd: Path.expand(&quot;../frontend&quot;, __DIR__)<br>  ]<br>]</pre><h3>React “Hello, World!”</h3><p>Our scaffolding <em>should</em> work, to verify it, let’s create a simple React “Hello, World!”.</p><p>It’s simple enough to only be contained in the frontend/src/index.tsx file:</p><pre>import * as React from &quot;react&quot;;<br>import * as ReactDOM from &quot;react-dom&quot;;</pre><pre>const MainComponent = () =&gt; (&lt;div className=&quot;hello-world&quot;&gt;Hello, World!&lt;/div&gt;);</pre><pre>ReactDOM.render(<br>    &lt;MainComponent /&gt;,<br>    <em>document</em>.getElementById(&quot;app&quot;)<br>);</pre><p>The template file at lib/&lt;app&gt;_web/templates/layout/app.html.eex must be edited adding the react entrypoint &lt;div id=&quot;app&quot; /&gt;.</p><p>It’s done, run mix phx.server and profit:</p><pre>mix phx.server</pre><pre>[info] Running &lt;app&gt;.Endpoint with Cowboy using http://0.0.0.0:4000<br> 10% building modules 1/1 modules 0 active<br>webpack is watching the files…<br>...<br>[debug] Live reload: priv/static/js/app.js<br>[debug] Live reload: priv/static/css/app.css<br>...</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=354f71179ef6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[API Authentication with Phoenix and React — part 2]]></title>
            <link>https://medium.com/@tommyblue/api-authentication-with-phoenix-and-react-part-2-d613f9667f83?source=rss-b3ae6c5cd525------2</link>
            <guid isPermaLink="false">https://medium.com/p/d613f9667f83</guid>
            <category><![CDATA[phoenix]]></category>
            <category><![CDATA[elixir]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Tommaso Visconti]]></dc:creator>
            <pubDate>Tue, 03 Apr 2018 07:57:17 GMT</pubDate>
            <atom:updated>2018-04-03T07:59:36.710Z</atom:updated>
            <content:encoded><![CDATA[<p><a href="https://www.tommyblue.it/2018/03/29/api-authentication-with-phoenix-and-react-part-1/">In the first part of this post</a> I’ve shown how to configure the API server to let the user authenticate, return an authentication token, and request it to access protected routes.<br>Now I’m going to configure a <a href="https://reactjs.org/">React</a> app to consume that API and manage authentication.</p><p>The app uses <a href="https://reacttraining.com/react-router/">React Router</a> to manage routes and <a href="https://redux.js.org/">Redux</a> for the state of the app.</p><h3>Protect private routes</h3><p>I’m going to define a PrivateRoute component as a wrapper around Route. The component will check the user authentication.</p><p>The router configuration will have a standard Route component for the Login page and will use PrivateRoute for the rest of the routes:</p><pre>&lt;Router&gt;<br>    &lt;Switch&gt;<br>        &lt;Route path=&#39;/login&#39; component={Login} /&gt;<br>        &lt;PrivateRoute path=&#39;/private&#39; component={PrivateComponent}/&gt;<br>    &lt;/Switch&gt;<br>&lt;/Router&gt;</pre><p>The PrivateRoute component will check the isAuthenticated flag in the state and will redirect back to login if false or will render the private component otherwise:</p><pre>import React from &#39;react&#39;;<br>import { Route, Redirect } from &#39;react-router-dom&#39;;<br>import { connect } from &#39;react-redux&#39;;</pre><pre>const mapStateToProps = state =&gt; {<br>    return {<br>        isAuthenticated: state.isAuthenticated,<br>    };<br>};</pre><pre>class PrivateRoute extends React.Component {<br>    render() {<br>        if (!this.props.isAuthenticated) {<br>            return (<br>                &lt;Redirect<br>                    to={{<br>                    pathname: &quot;/login&quot;,<br>                    state: { from: this.props.location }<br>                    }}<br>                /&gt;<br>            );<br>        }</pre><pre>        return (<br>            &lt;Route component={this.props.Component} {...this.props} /&gt;<br>        );<br>    }<br>}</pre><pre>export default connect(mapStateToProps)(PrivateRoute);</pre><h3>Sign in and receive the token from the server</h3><p>The Login component will simply show a form and will manage the initial authentication, saving the token in a cookie for later use:</p><pre>import React from &#39;react&#39;;<br>import { connect } from &#39;react-redux&#39;;</pre><pre>import {<br>    signIn,<br>} from &#39;../actions&#39;;</pre><pre>const mapStateToProps = state =&gt; {<br>    return {<br>        isAuthenticated: state.isAuthenticated,<br>    };<br>};</pre><pre>const mapDispatchToProps = dispatch =&gt; {<br>    return {<br>        onSignIn: (email, password) =&gt; dispatch(signIn(email, password)),<br>    };<br>};</pre><pre>class Login extends React.Component {<br>    constructor(props) {<br>        super(props);<br>        this.onSignIn = this.onSignIn.bind(this);<br>        this.state = {email: &quot;&quot;, password: &quot;&quot;};<br>    }</pre><pre>    render() {<br>        return (<br>            &lt;div className=&quot;container&quot;&gt;<br>                &lt;h1 className=&quot;title&quot;&gt;Login&lt;/h1&gt;<br>                {this.props.isAuthenticated ? this.alreadyAuthenticated() : this.form()}<br>            &lt;/div&gt;<br>        );<br>    }</pre><pre>    alreadyAuthenticated() {<br>        return (&quot;You&#39;re already authenticated.&quot;)<br>    }</pre><pre>    form() {<br>        return (<br>            &lt;form&gt;<br>                &lt;div className=&quot;field&quot;&gt;<br>                    &lt;label className=&quot;label&quot;&gt;Email&lt;/label&gt;<br>                    &lt;div className=&quot;control&quot;&gt;<br>                        &lt;input<br>                            className=&quot;input&quot;<br>                            type=&quot;email&quot;<br>                            placeholder=&quot;Your email address&quot;<br>                            value={this.state.email}<br>                            autoFocus={true}<br>                            onChange={(e) =&gt; this.setState({...this.state, email: e.target.value})}<br>                        /&gt;<br>                    &lt;/div&gt;<br>                &lt;/div&gt;</pre><pre>                &lt;div className=&quot;field&quot;&gt;<br>                    &lt;label className=&quot;label&quot;&gt;Password&lt;/label&gt;<br>                    &lt;div className=&quot;control&quot;&gt;<br>                        &lt;input<br>                            className=&quot;input&quot;<br>                            type=&quot;password&quot;<br>                            placeholder=&quot;Your password&quot;<br>                            value={this.state.password}<br>                            onChange={(e) =&gt; this.setState({...this.state, password: e.target.value})}<br>                        /&gt;<br>                    &lt;/div&gt;<br>                &lt;/div&gt;</pre><pre>                &lt;button<br>                    className=&quot;button is-primary&quot;<br>                    onClick={this.onSignIn}<br>                &gt;Sign in&lt;/button&gt;<br>            &lt;/form&gt;<br>        );<br>    }</pre><pre>    onSignIn() {<br>        this.props.onSignIn(this.state.email, this.state.password);<br>    }<br>}</pre><pre>export default connect(<br>    mapStateToProps,<br>    mapDispatchToProps<br>)(Login);</pre><p>The signIn action is where the &quot;magic&quot; happens:</p><pre>export const signIn = (email, password) =&gt; ((dispatch) =&gt; {<br>    return fetch(`http://&lt;server_url&gt;/api/sessions/sign_in}`, {<br>        method: &quot;POST&quot;,<br>        headers: {<br>            &#39;Accept&#39;: &#39;application/json&#39;,<br>            &#39;Content-Type&#39;: &#39;application/json&#39;<br>        },<br>        body: JSON.stringify({email, password}),<br>      }).then(<br>        response =&gt; {<br>            if (!response.ok) {<br>                // Manage error<br>                return dispatch(errorOnFetch(response.statusText));<br>            }<br>            return response.json().then(response =&gt; dispatch(signInSuccessfull(response.data)));<br>        },<br>        error =&gt; {<br>            return dispatch(errorOnFetch(error))<br>        }<br>    );<br>});</pre><pre>const signInSuccessfull = (data) =&gt; {<br>    setAuthToken(data.token);<br>    return {<br>        type: AUTHENTICATION_SUCCEDED,<br>    }<br>};</pre><p>Two main things happen in the signInSuccessfull method: the token returned by the server is passed to the setAuthToken method and the AUTHENTICATION_SUCCEEDEDaction is returned to the redux reducer.</p><p>The reducer sets the isAuthenticated flag to true (do you remember the check in the PrivateRoute component?):</p><pre>const mainReducer = (state = initialState, action) =&gt; {<br>    switch (action.type) {<br>        case AUTHENTICATION_SUCCEDED:<br>            return ({...state,<br>                isAuthenticated: true,<br>            });<br>        case AUTHENTICATION_SIGNOUT:<br>            return ({...state,<br>                isAuthenticated: false,<br>            });<br>    }<br>}</pre><p>The setAuthToken method saves the token in a cookie, so that it will be then available for the next requests:</p><pre>const setAuthToken = (token) =&gt; {<br>    const cookies = new Cookies();<br>    cookies.set(&#39;my_auth_token&#39;, token, {<br>        path: &#39;/&#39;<br>    });<br>};</pre><p>I’m using the <a href="https://github.com/reactivestack/cookies/tree/master/packages/universal-cookie">universal-cookie</a> package here, so we need to install it:</p><pre>yarn add universal-cookie</pre><p>Other useful methods will permit to get the cookie or delete it:</p><pre>export const getAuthToken = () =&gt; {<br>    const cookies = new Cookies();<br>    return cookies.get(&#39;my_auth_token&#39;);<br>};</pre><pre>const removeAuthToken = () =&gt; {<br>    const cookies = new Cookies();<br>    cookies.remove(&#39;my_auth_token&#39;, {<br>        path: &#39;/&#39;,<br>    });<br>};</pre><h3>Use the token for private routes</h3><p>At this point we have a valid token saved in a cookie. We just need to use it when making a request for a private API endpoint.</p><p>I’ll use a wrapper function around fetch to add the Authorization header to the requests:</p><pre>const authFetch = (url, options) =&gt; (<br>    fetch(url, mergeAuthHeaders(options)).then(<br>        response =&gt; {<br>            // Sign out if we receive a 401!<br>            if (response.status === 401) {<br>                store.dispatch(signOut());<br>                throw new Error(&quot;Unauthorized&quot;);<br>            }<br>            return response;<br>        },<br>        error =&gt; error<br>    )<br>);</pre><pre>const mergeAuthHeaders = (baseOptions) =&gt; {<br>    const options = _.isUndefined(baseOptions) ? {} : baseOptions;<br>    if (!_.has(options, &#39;headers&#39;)) {<br>        options.headers = {};<br>    }<br>    options.headers = {<br>        ...options.headers,<br>        &#39;Authorization&#39;: `Bearer ${getAuthToken()}`,<br>    };<br>    return options;<br>}</pre><p>The authFetch method receives a URL to fetch and the options for the fetch method. It merges the authentication header in the options and makes the request.<br>If it receives a 401 response, then it makes the sign out, deleting the cookie and setting the isAuthenticated flag to false:</p><pre>export const signOut = () =&gt; {<br>    removeAuthToken();<br>    return {<br>        type: AUTHENTICATION_SIGNOUT,<br>    }<br>};</pre><p>That’s it, you should probably add more logic to manage side cases and errors, but this is enough to consume the APIs we built.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d613f9667f83" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[API Authentication with Phoenix and React — part 1]]></title>
            <link>https://medium.com/@tommyblue/api-authentication-with-phoenix-and-react-part-1-30c6865bfbd3?source=rss-b3ae6c5cd525------2</link>
            <guid isPermaLink="false">https://medium.com/p/30c6865bfbd3</guid>
            <category><![CDATA[elixir]]></category>
            <category><![CDATA[phoenix]]></category>
            <category><![CDATA[api-development]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[phoenix-framework]]></category>
            <dc:creator><![CDATA[Tommaso Visconti]]></dc:creator>
            <pubDate>Fri, 30 Mar 2018 06:42:26 GMT</pubDate>
            <atom:updated>2019-08-09T10:12:20.451Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/615/1*-MTuYZ4k46A8JJdWlq_x5A.png" /></figure><p><strong>Scenario:</strong> you just wrote a cool web app using React for the frontend part and Phoenix as the API server.<br>Then you realize everybody can poke around your stuff and you decide <strong>it’s time to restrict the access to known users</strong>, how to do it?</p><p>I’ll configure a <a href="http://phoenixframework.org/">Phoenix</a> server to manage <a href="https://tools.ietf.org/html/rfc6750">access tokens</a>, used by a <a href="https://reactjs.org/">React</a> app to make authenticated calls.</p><p>This blog post only deals with the backend part and consists of these steps:</p><ul><li>add users and give them the ability to sign in</li><li>manage authentication tokens for the users</li><li>define a pipeline to grant access to restricted routes only to authenticated requests</li></ul><p><strong>I’m not going to cover the SSL configuration here, but it’s fundamental to only serve the endpoints over HTTPS. You can check out </strong><a href="https://spin.atomicobject.com/2018/03/07/force-ssl-phoenix-framework/"><strong>this article</strong></a><strong> which explains how to force SSL in Phoenix.</strong></p><h3>Create the Users</h3><p>Let’s create the schemas for the User:</p><pre>$ mix phx.gen.schema User users email:string:unique password_hash:string</pre><p>The mix command doesn’t accept any option to avoid null values for the fields, so the migration files must be edited.<br>This is the final version of the migration file (only the relevant parts):</p><pre>create table(:users) do<br>  add :email, :string, null: false<br>  add :password_hash, :string, null: false<br>  timestamps()<br>end<br>create unique_index(:users, [:email])</pre><p>We’re going to save hashed password, not clear-text passwords, so our schema will have a virtual password field which, behind the scenes, will be hashed and saved.</p><p>To crypt passwords we’re going to use the <a href="https://github.com/riverrun/comeonin/">Comeonin</a> lib, that must be added to the dependencies, together with BCrypt (don’t forget to run mix deps.get after you made the changes):</p><pre># mix.exs<br>defp deps do<br>  [...]<br>  {:comeonin, &quot;~&gt; 4.0&quot;},<br>  {:bcrypt_elixir, &quot;~&gt; 1.0&quot;}<br>end</pre><p>So let’s now see the <strong>User module</strong>:</p><pre># lib/my_app/user.ex<br>defmodule MyApp.User do<br>  use Ecto.Schema<br>  import Ecto.Changeset<br>  alias MyApp.User</pre><pre>  schema &quot;users&quot; do<br>    field :email, :string<br>    field :password_hash, :string<br>    field :password, :string, virtual: true<br>    timestamps()<br>  end</pre><pre>  def changeset(%User{} = user, attrs) do<br>    user<br>    |&gt; cast(attrs, [:email, :password])<br>    |&gt; validate_required([:email, :password])<br>    |&gt; unique_constraint(:email, downcase: true)<br>    |&gt; put_password_hash()<br>  end</pre><pre>  defp put_password_hash(changeset) do<br>    case changeset do<br>      %Ecto.Changeset{valid?: true, changes: %{password: pass}} -&gt;<br>        put_change(changeset, :password_hash, Comeonin.Bcrypt.hashpwsalt(pass))<br>      _ -&gt;<br>        changeset<br>    end<br>  end<br>end</pre><p>At this point we can create new users:</p><pre>$ iex -S mix</pre><pre>iex(1)&gt; MyApp.Repo.insert!(MyApp.User.changeset(%MyApp.User{}, %{email: “my_email@provider.com”, password: “s3cr3t”}))</pre><pre>[debug] QUERY OK db=4.8ms<br>INSERT INTO &quot;users&quot; (&quot;email&quot;,&quot;password_hash&quot;,&quot;inserted_at&quot;,&quot;updated_at&quot;) VALUES ($1,$2,$3,$4) RETURNING &quot;id&quot; [&quot;my_email@provider.com&quot;, &quot;$2b$12$SWV0KN46DePgZtQ0uaXYj.PA5vDf00aqcexIsvxyLXp5gDBuWrwKy&quot;, {{2018, 3, 24}, {22, 47, 37, 981969}}, {{2018, 3, 24}, {22, 47, 37, 984213}}]<br>%MyApp.User{<br>  __meta__: #Ecto.Schema.Metadata&lt;:loaded, &quot;users&quot;&gt;,<br>  email: &quot;my_email@provider.com&quot;,<br>  id: 1,<br>  inserted_at: ~N[2018-03-24 22:47:37.981969],<br>  password: &quot;s3cr3t&quot;,<br>  password_hash: &quot;$2b$12$SWV0KN46DePgZtQ0uaXYj.PA5vDf00aqcexIsvxyLXp5gDBuWrwKy&quot;,<br>  updated_at: ~N[2018-03-24 22:47:37.984213]<br>}</pre><h3>User tokens</h3><p>Ok, now that we have users, we must generate tokens for them, so that they can access restricted routes.</p><p>The first step is to create the schema:</p><pre>$ mix phx.gen.schema AuthToken auth_tokens user_id:references:users token:text:unique revoked:boolean revoked_at:utc_datetime</pre><p>As before, we must edit the migration to add missing null: false:</p><pre>create table(:auth_tokens) do<br>  add :user_id, references(:users, on_delete: :nothing), null: false<br>  add :token, :text, null: false<br>  add :revoked, :boolean, default: false, null: false<br>  add :revoked_at, :utc_datetime<br>  timestamps()<br>end<br>create unique_index(:auth_tokens, [:token])<br>create index(:auth_tokens, [:user_id])</pre><p>The schema file is:</p><pre>defmodule MyApp.AuthToken do<br>  use Ecto.Schema<br>  import Ecto.Changeset<br>  alias MyApp.AuthToken<br>  alias MyApp.User</pre><pre>schema &quot;auth_tokens&quot; do<br>    belongs_to :user, User<br>    field :revoked, :boolean, default: false<br>    field :revoked_at, :utc_datetime<br>    field :token, :string<br>    timestamps()<br>  end</pre><pre>  def changeset(%AuthToken{} = auth_token, attrs) do<br>    auth_token<br>    |&gt; cast(attrs, [:token])<br>    |&gt; validate_required([:token])<br>    |&gt; unique_constraint(:token)<br>  end<br>end</pre><p>We’ve added the belongs_to relationship there, you must also edit the User schema adding:</p><pre>schema &quot;users&quot; do<br>  has_many :auth_tokens, MyApp.AuthToken<br>  [...]<br>end</pre><p>We’re going to need a bunch of methods to deal with authorization headers and tokens, so a service could be useful.</p><p>Let’s create an Authenticator service with the first methods we’ll use to generate and verify tokens with <a href="https://hexdocs.pm/phoenix/Phoenix.Token.html">Phoenix.Token</a>:</p><pre>defmodule MyApp.Services.Authenticator do<br>  # These values must be moved in a configuration file<br>  @seed &quot;user token&quot;</pre><pre># good way to generate: <br>  # :crypto.strong_rand_bytes(30) <br>  # |&gt; Base.url_encode64 <br>  # |&gt; binary_part(0, 30)<br>  @secret &quot;CHANGE_ME_k7kTxvFAgeBvAVA0OR1vkPbTi8mZ5m&quot;</pre><pre>  def generate_token(id) do<br>    Phoenix.Token.sign(@secret, @seed, id, max_age: 86400)<br>  end</pre><pre>  def verify_token(token) do<br>    case Phoenix.Token.verify(@secret, @seed, token, max_age: 86400) do<br>      {:ok, id} -&gt; {:ok, token}<br>      error -&gt; error<br>    end<br>  end<br>end</pre><h3>Sign in and out the users</h3><p>We now need to let the users sign in (create a token for the user) and sign out (delete the token).</p><p>We’ll manage the logic inside the User module:</p><pre>defmodule MyApp.User do<br>  [...]<br>  alias MyApp.Services.Authenticator<br>  <br>  def sign_in(email, password) do<br>    case Comeonin.Bcrypt.check_pass(Repo.get_by(User, email: email), password) do<br>      {:ok, user} -&gt;<br>        token = Authenticator.generate_token(user)<br>        Repo.insert(Ecto.build_assoc(user, :auth_tokens, %{token: token}))<br>      err -&gt; err<br>    end<br>  end<br>  <br>  def sign_out(conn) do<br>    case Authenticator.get_auth_token(conn) do<br>      {:ok, token} -&gt;<br>        case Repo.get_by(AuthToken, %{token: token}) do<br>          nil -&gt; {:error, :not_found}<br>          auth_token -&gt; Repo.delete(auth_token)<br>        end<br>      error -&gt; error<br>    end<br>  end<br>end</pre><p>The first line of the sign_in function looks for the user in the Repo then passes it to Bcrypt.check_pass together with the provided password, to verify it.</p><p>In the case the user can’t be found, check_pass receives a wrong user and returns {:error, &quot;invalid user-identifier&quot;} while in the case the password verification fails it returns {:error, &quot;invalid password&quot;}.<br>So, in both cases, we return a {:error, reason} tuple (we’ll later use this in the controller).</p><p>If the user is found and the password is valid, we create a token for the user and return it.</p><p>The sign_out function looks for the token in the header and deletes it if found.</p><p>The function that extracts the token is based on a simple regexp:</p><pre>defmodule MyApp.Services.Authenticator do<br>  [...]<br>  def get_auth_token(conn) do<br>    case extract_token(conn) do<br>      {:ok, token} -&gt; verify_token(token)<br>      error -&gt; error<br>    end<br>  end</pre><pre>  defp extract_token(conn) do<br>    case Plug.Conn.get_req_header(conn, &quot;authorization&quot;) do<br>      [auth_header] -&gt; get_token_from_header(auth_header)<br>       _ -&gt; {:error, :missing_auth_header}<br>    end<br>  end</pre><pre>  defp get_token_from_header(auth_header) do<br>    {:ok, reg} = Regex.compile(&quot;Bearer\:?\s+(.*)$&quot;, &quot;i&quot;)<br>    case Regex.run(reg, auth_header) do<br>      [_, match] -&gt; {:ok, String.trim(match)}<br>      _ -&gt; {:error, &quot;token not found&quot;}<br>    end<br>  end<br>end</pre><p>At this point all the underground pieces are in place, but we need to create the endpoints to let the user make the actions.</p><p>First, add the required routes:</p><pre>scope &quot;/sessions&quot; do<br>  post &quot;/sign_in&quot;, SessionsController, :create<br>  delete &quot;/sign_out&quot;, SessionsController, :delete<br>end</pre><p>We can check the result with mix phx.routes:</p><pre>sessions_path  POST    /sessions/sign_in    MyApp.SessionsController :create<br>sessions_path  DELETE  /sessions/sign_out    MyApp.SessionsController :delete</pre><p>We must then create the SessionsController:</p><pre>defmodule MyAppWeb.SessionsController do<br>  use MyAppWeb, :controller<br>  alias MyApp.User<br>  <br>  def create(conn, %{&quot;email&quot; =&gt; email, &quot;password&quot; =&gt; password}) do<br>    case User.sign_in(email, password) do<br>      {:ok, auth_token} -&gt;<br>        conn<br>        |&gt; put_status(:ok)<br>        |&gt; render(&quot;show.json&quot;, auth_token)<br>      {:error, reason} -&gt;<br>        conn<br>        |&gt; send_resp(401, reason)<br>    end<br>  end</pre><pre>def delete(conn, _) do<br>    case User.sign_out(conn) do<br>      {:error, reason} -&gt; conn |&gt; send_resp(400, reason)<br>      {:ok, _} -&gt; conn |&gt; send_resp(204, &quot;&quot;)<br>    end<br>  end<br>end</pre><p>and its view:</p><pre># views/sessions_view.ex<br>defmodule MyAppWeb.SessionsView do<br>  use MyAppWeb, :view</pre><pre>  def render(&quot;show.json&quot;, auth_token) do<br>    %{data: %{token: auth_token.token}}<br>  end<br>end</pre><p>Done, it’s now time to make some tests calling these endpoints. I personally use <a href="https://install.advancedrestclient.com/#/install">Advanced Rest Client</a> (aka ARC), a Chrome extension to make HTTP calls.</p><p>To test sign in, we must make a POST call to http://localhost:4000/sessions/sign_in with the following JSON body:</p><pre>{<br>  &quot;email&quot;:&quot;my_email@provider.com&quot;,<br>  &quot;password&quot;: &quot;s3cr3t&quot;<br>}</pre><p>If we didn’t make any error we’ll get back the token in a json structure as we defined in show.json:</p><pre>{<br>  &quot;data&quot;: {<br>    &quot;token&quot;: &quot;SFMyNTY.g3QAAAAC[...cut...]&quot;<br>  }<br>}</pre><p>Now make a DELETE call against http://localhost:4000/sessions/sign_out, adding an authorization header in the form: Authorization: Bearer SFMyNTY.g3QAAAAC[…cut…]. You should receive a 204 response.</p><p>Take a look at the database for further feedback. A new token for the user must be created at sign in and it must be deleted at sign out.</p><h3>Require the token to access restricted routes</h3><p>We’re almost there: users are able to sign in and receive an authentication token, we should now restrict the access to private routes requiring an authorization token.</p><p>The key is a basic component of Phoenix: the <a href="https://hexdocs.pm/phoenix/plug.html">Plug</a>.</p><p>To apply one or more plugs to routes, we need to create a pipeline and pipe the routes through it:</p><pre>defmodule MyAppWeb.Router do<br>  pipeline :authenticate do<br>    plug MyAppWeb.Plugs.Authenticate<br>  end</pre><pre>  scope &quot;/restricted&quot;, Restricted do<br>    pipe_through :authenticate<br>    resources &quot;/private&quot;<br>    # more routes<br>  end<br>  [...]<br>end</pre><p>The Authenticate plug will look for the authorization token in the request headers and will validate it. Only requests with valid tokens will go through. Invalid requests will get a 401 response.</p><p>This is the plug file:</p><pre>defmodule MyAppWeb.Plugs.Authenticate do<br>  import Plug.Conn</pre><pre>  def init(default), do: default</pre><pre>  def call(conn, _default) do<br>    case MyApp.Services.Authenticator.get_auth_token(conn) do<br>      {:ok, token} -&gt;<br>        case MyApp.Repo.get_by(MyApp.AuthToken, %{token: token, revoked: false}) |&gt; Repo.preload(:user) do<br>          nil -&gt; unauthorized(conn)<br>          auth_token -&gt; authorized(conn, auth_token.user)<br>        end<br>      _ -&gt; unauthorized(conn)<br>    end<br>  end</pre><pre>  defp authorized(conn, user) do<br>    # If you want, add new values to `conn`<br>    conn <br>    |&gt; assign(:signed_in, true)<br>    |&gt; assign(:signed_user, user)<br>  end</pre><pre>  defp unauthorized(conn) do<br>    conn |&gt; send_resp(401, &quot;Unauthorized&quot;) |&gt; halt()<br>  end<br>end</pre><h3>Revoke a compromised token</h3><p>In the case a token is somehow “compromised”, the user can revoke it.</p><p>We need a new restricted route which updates the compromised token setting the revoked=true and revoked_at=&lt;current timestamp&gt;.</p><p>I’m going to leave this as an exercise for the readers.</p><h3>Consume the APIs with React</h3><p>In the next part of this guide (to be published soon), I’ll show how to use what done here in a frontend app built using React.</p><h3>Note: JWT and why I didn’t use it</h3><p>In the first iteration of the code I decided to use <a href="https://github.com/ueberauth/guardian">Guardian</a> and <a href="https://jwt.io/">JWT</a> (JSON Web Tokens) but then I realized I couldn’t revoke tokens without store them in the db and actually make a query at each API call (and avoiding a query was the main reason that lead me to use JWT), so I decided it was a over-engineered solution and moved to the integrated <a href="https://hexdocs.pm/phoenix/Phoenix.Token.html">Phoenix.Token</a>.</p><p>If you’re interested in the JWT revoke topic, check the <a href="https://github.com/ueberauth/guardian_db/blob/master/README.md#disadvantages">GuardianDB README</a> which has a good explanation:</p><blockquote>In other words, once you have reached a point where you think you need Guardian.DB, it may be time to take a step back and reconsider your whole approach to authentication!</blockquote><h3>References</h3><ul><li><a href="http://learningwithjb.com/posts/authenticating-users-using-a-token-with-phoenix">http://learningwithjb.com/posts/authenticating-users-using-a-token-with-phoenix</a></li><li><a href="https://dennisreimann.de/articles/phoenix-passwordless-authentication-magic-link.html">https://dennisreimann.de/articles/phoenix-passwordless-authentication-magic-link.html</a></li><li><a href="http://whatdidilearn.info/2018/02/18/authentication-in-phoenix.html">http://whatdidilearn.info/2018/02/18/authentication-in-phoenix.html</a></li><li><a href="https://itnext.io/authenticating-absinthe-graphql-apis-in-phoenix-with-guardian-d647ea45a69a">https://itnext.io/authenticating-absinthe-graphql-apis-in-phoenix-with-guardian-d647ea45a69a</a></li><li><a href="https://medium.freecodecamp.org/authentication-using-elixir-phoenix-f9c162b2c398">https://medium.freecodecamp.org/authentication-using-elixir-phoenix-f9c162b2c398</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=30c6865bfbd3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[React+Sass+Typescript with Phoenix framework using Webpack]]></title>
            <link>https://medium.com/@tommyblue/react-sass-typescript-with-phoenix-framework-using-webpack-af0c8f7282d9?source=rss-b3ae6c5cd525------2</link>
            <guid isPermaLink="false">https://medium.com/p/af0c8f7282d9</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[phoenix-framework]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[webpack]]></category>
            <dc:creator><![CDATA[Tommaso Visconti]]></dc:creator>
            <pubDate>Tue, 05 Sep 2017 13:49:08 GMT</pubDate>
            <atom:updated>2017-09-05T13:49:33.516Z</atom:updated>
            <cc:license>https://creativecommons.org/licenses/by-nc-sa/4.0/</cc:license>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ffJ5VWBKVuOnBBxhrKfXKQ.jpeg" /></figure><p>If you’re playing with <a href="https://elixir-lang.org/">Elixir</a> and <a href="http://phoenixframework.org/">Phoenix</a> you’ll probably already know that Phoenix uses <a href="http://brunch.io/">Brunch.io</a> to build the assets pipeline.<br>I initially started building my app with <a href="https://facebook.github.io/react/">React</a> / <a href="http://redux.js.org/">Redux</a> + <a href="http://sass-lang.com/">SASS</a> and I was quite happy, but when I decided to add <a href="https://www.typescriptlang.org/">Typescript</a> to the recipe, I found Brunch.io wasn’t very helpful!</p><p>I’ve already used these tools using <a href="https://webpack.github.io/">Webpack</a> as building tool, so I decided to switch to it.<br>I had a working Webpack configuration I was using in other projects, so I only had to find out how to apply it to Phoenix.</p><p>When I initially generated the Phoenix app, I didn’t use the --no-brunch command line flag to generate it without Brunch, and the app itself was alreadyt working. So I wanted to replace the existing Brunch config with the new one without nuking any existing feature.</p><p>Below you can find the (few) steps required for this upgrade.</p><h3>Remove Brunch and install Webpack</h3><p>To remove Brunch, just remove the assets/brunch-config.js file and uninstall all <em>brunch-related</em> packages. In my case:</p><pre>yarn remove brunch babel-brunch clean-css-brunch sass-brunch uglify-js-brunch</pre><p>In the assets/package.json file you can also see that Brunch is mentioned in the scripts commands:</p><pre>&quot;scripts&quot;: {<br>  &quot;deploy&quot;: &quot;brunch build --production&quot;,<br>  &quot;watch&quot;: &quot;brunch watch --stdin&quot;<br>},</pre><p>Replace them with the Webpack commands (to run the webpack command you’d probably need to globally install it with yarn global add webpack):</p><pre>&quot;scripts&quot;: {<br>  &quot;deploy&quot;: &quot;webpack -p&quot;,<br>  &quot;compile&quot;: &quot;webpack --progress --color&quot;,<br>  &quot;watch&quot;: &quot;webpack --watch-stdin --progress --color&quot;<br>},</pre><p>You’re now ready to install the webpack ecosystem we’re going to use:</p><pre>yarn add -D webpack babel-core babel-loader babel-preset-es2015 copy-webpack-plugin css-loader extract-text-webpack-plugin file-loader node-sass sass-loader style-loader webpack-notifier</pre><h3>Add Typescript to the project</h3><p>To add Typescript support we need some more packages too:</p><pre>yarn add -D typescript ts-loader tslint tslint-react @types/phoenix @types/react @types/react-dom @types/react-redux</pre><p>The Typescript configuration file is assets/tsconfig.json:</p><pre>{<br>  &quot;compilerOptions&quot;: {<br>    &quot;target&quot;: &quot;es2015&quot;,<br>    &quot;module&quot;: &quot;es2015&quot;,<br>    &quot;jsx&quot;: &quot;preserve&quot;,<br>    &quot;moduleResolution&quot;: &quot;node&quot;,<br>    &quot;baseUrl&quot;: &quot;js&quot;,<br>    &quot;outDir&quot;: &quot;ts-build&quot;,<br>    &quot;allowJs&quot;: true<br>  },<br>  &quot;exclude&quot;: [<br>    &quot;node_modules&quot;,<br>    &quot;priv&quot;,<br>    &quot;ts-build&quot;<br>  ]<br>}</pre><p>As you probably noticed in the previous command, I also installed <a href="https://palantir.github.io/tslint/">TSLint</a> support for linting features. Add the related package to your editor (like <a href="https://github.com/Microsoft/vscode-tslint">vscode-tslint</a> for <a href="https://code.visualstudio.com/">VSCode</a>) to have (almost-)real-time linting warnings. <br>You also need a configuration file, here’s mytslint.json file:</p><pre>{<br>  &quot;extends&quot;: [&quot;tslint:recommended&quot;, &quot;tslint-react&quot;],<br>  &quot;rules&quot;: {<br>    &quot;no-console&quot;: [false]<br>  }<br>}</pre><h3>Webpack configuration</h3><p>Before configuring Webpack, let’s configure <a href="https://babeljs.io/">Babel</a>, using the assets/.babelrc file:</p><pre>{<br>  &quot;presets&quot;: [&quot;es2015&quot;, &quot;react&quot;]<br>}</pre><p>And now, finally, the big part, the Webpack configuration file, assets/webpack.config.js:</p><pre>const env = process.env.NODE_ENV<br>const path = require(&quot;path&quot;)<br>const ExtractTextPlugin = require(&quot;extract-text-webpack-plugin&quot;);<br>const CopyWebpackPlugin = require(&quot;copy-webpack-plugin&quot;)</pre><pre>const config = {<br>  entry: [&quot;./css/app.scss&quot;, &quot;./js/app.js&quot;],<br>  output: {<br>    path: path.resolve(__dirname, &quot;../priv/static&quot;),<br>    filename: &quot;js/app.js&quot;<br>  },<br>  resolve: {<br>    extensions: [&quot;.ts&quot;, &quot;.tsx&quot;, &quot;.js&quot;, &quot;.jsx&quot;],<br>    modules: [&quot;deps&quot;, &quot;node_modules&quot;]<br>  },<br>  module: {<br>    rules: [{<br>      test: /\.tsx?$/,<br>      use: [&quot;babel-loader&quot;, &quot;ts-loader&quot;]<br>    }, {<br>      test: /\.jsx?$/,<br>      use: &quot;babel-loader&quot;<br>    }, {<br>      test: /\.scss$/,<br>      use: ExtractTextPlugin.extract({<br>        use: [{<br>          loader: &quot;css-loader&quot;,<br>          options: {<br>            minimize: true,<br>            sourceMap: env === &#39;production&#39;,<br>          },<br>        }, {<br>          loader: &quot;sass-loader&quot;,<br>          options: {<br>            includePaths: [path.resolve(&#39;node_modules&#39;)],<br>          }<br>        }],<br>        fallback: &quot;style-loader&quot;<br>      })<br>    }, {<br>      test: /\.(ttf|otf|eot|svg|woff(2)?)(\?[a-z0-9]+)?$/,<br>      // put fonts in assets/static/fonts/<br>      loader: &#39;file-loader?name=/fonts/[name].[ext]&#39;<br>    }]<br>  },<br>  plugins: [<br>    new ExtractTextPlugin({<br>      filename: &quot;css/[name].css&quot;<br>    }),<br>    new CopyWebpackPlugin([{ from: &quot;./static&quot; }])<br>  ]<br>};</pre><pre>module.exports = config;</pre><h3>Final polishing and tests</h3><p>The final step is to update the main template file app.html.eex to use the generated files (that you can find in the priv/static folder once compiled):</p><pre>[..]<br>&lt;link rel=&quot;stylesheet&quot; href=&quot;&lt;%= static_path(@conn, &quot;/css/main.css&quot;) %&gt;&quot;&gt;<br>[..]<br>&lt;script src=&quot;&lt;%= static_path(@conn, &quot;/js/app.js&quot;) %&gt;&quot;&gt;&lt;/script&gt;</pre><p>The whole pipeline is now ready, except we must tell Phoenix to run Webpack when the server is launched.<br>At the moment you can already test the pipeline running, from the assets/ folder, the command: yarn run compile</p><p>To configure Phoenix, update the config/dev.exs file replacing Brunch command with Webpack:</p><pre>watchers: [<br>  node: [<br>    &quot;node_modules/webpack/bin/webpack.js&quot;, &quot;--watch-stdin&quot;, &quot;--progress&quot;, &quot;--color&quot;,<br>    cd: Path.expand(&quot;../assets&quot;, __DIR__)<br>  ]<br>]</pre><p>That’s it. <br>Run mix phx.server and you’ll have both the Phoenix server running and the assets pipeline compiled and watching for file updates.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=af0c8f7282d9" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>