<?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 Uk Chukundah on Medium]]></title>
        <description><![CDATA[Stories by Uk Chukundah on Medium]]></description>
        <link>https://medium.com/@ukchukx?source=rss-5114de41076a------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*h5y20Q4CN5TgviSv2j42Hg.jpeg</url>
            <title>Stories by Uk Chukundah on Medium</title>
            <link>https://medium.com/@ukchukx?source=rss-5114de41076a------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 21 Nov 2026 11:56:30 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ukchukx/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[#EndSARS: Fighting the supporting structures of police brutality]]></title>
            <link>https://medium.com/@ukchukx/endsars-fighting-the-supporting-structures-of-police-brutality-3a49399b685e?source=rss-5114de41076a------2</link>
            <guid isPermaLink="false">https://medium.com/p/3a49399b685e</guid>
            <category><![CDATA[police-brutality]]></category>
            <category><![CDATA[endsarsnow]]></category>
            <category><![CDATA[police-reform]]></category>
            <category><![CDATA[endsars]]></category>
            <dc:creator><![CDATA[Uk Chukundah]]></dc:creator>
            <pubDate>Tue, 13 Oct 2020 22:16:52 GMT</pubDate>
            <atom:updated>2020-10-13T22:16:52.585Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*DEe2S45ndgJ09Rhg.jpg" /><figcaption><em>Photo by </em><a href="https://unsplash.com/@ev?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText"><em>ev</em></a><em> on </em><a href="https://unsplash.com/s/photos/police?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText"><em>Unsplash</em></a></figcaption></figure><p>It is no secret that SARS is a symptom of a systemic failure in our policing structure. We also know this protest will not solve the root causes and that is not the aim of the protests (or at least, it shouldn’t be).</p><p>Think of the protests as giving first aid to a sick patient before they can get lasting medical care. You have to first stop the bleeding before trying to fix the patient’s poor diet. We need to stop the brutalizing of our youth first before we can fix our police system.</p><blockquote>We need to stop the brutalizing of our youth first before we can fix our police system.</blockquote><p>Besides peaceful protests, we need other means of applying pressure to yield results. Let us explore tactics we can deploy to improve our chances of success.</p><h3>Short term tactics</h3><p>I would like to appreciate Segun Awosanya (@segalink), Citizens’ Gavel (@citizen_gavel) and others for the yeoman’s job of rescuing people from police harassment. To reduce police harassment, we need to <strong>entrench</strong>, <strong>multiply</strong> and <strong>popularize</strong>.</p><p>We entrench by putting youths in positions of authority and influence so they can help when needed.</p><p>We multiply by doing the above in every locality to bring help closer to the people.</p><p>We popularize by growing their social media reach and making their contact information widely available.</p><h3>Long term tactics</h3><p>I would like to focus on one — association — and the different ways we can apply it for long term change. Association is how we enforce and propagate cultural norms and practices. With it, we can nudge people (the so-called “big men”) who would rather be aloof to join the protest.<br>We need to direct it at the structures supporting police brutality:</p><ul><li>funding,</li><li>anonymity,</li><li>social connections.</li></ul><p><strong>How to fight the funding of rogue police units</strong></p><p>Youths are the conveners and executors of the protests, as they are the primary sufferers of police brutality at the hands of police. The “big men” can afford protection from the same police and so see no need to join the protests. Appealing to their compassion has not worked so far, so we should adopt a more effective form of appeal.</p><p>Appealing to their self-interest through economic boycotts is the way to go. This reduces the resources available to buy protection to shield them from the ills plaguing everyone else. It will also encourage them to join the protests as they would then be exposed to the problems. It also has the effect of eliminating a source of funds to the police, making them more willing to listen. People tend to be better listeners when their sources of income are endangered.</p><blockquote><em>People tend to be better listeners when their sources of income are endangered.</em></blockquote><p>Let’s walk through how this would work. Imagine a stereotypical “big man” in your community who is a distributor of drinks and has police protection. We boycott his business until he gives up his police protection. If that doesn’t work, we up the pressure by going after his support structures. Boycott his suppliers and customers until they boycott him.</p><p>It’s best to start with those that sell perishables or have high fixed costs as they can’t afford to wait it out. This gain easy wins in short time periods and provide momentum to take on bigger targets.</p><p><strong>How to fight anonymity of officers who commit crimes</strong></p><p>Make officers who harass citizens popular. Attach their faces to the crimes. Put a collective societal spotlight on them. Demand accountability from their immediate superiors. That would make them less likely to cover for or take the fall for the errant officers. It would also rob them of peer support that would help them brave the consequences of their crimes.</p><p>Put pressure on the appropriate quarters to prosecute and discipline as needed. Demand public updates on all steps taken and progress made. Force everything out into the open. Taking away concealment reduces the ability to maneuver. Crimes can’t be swept under the rug if there is no rug.</p><blockquote><em>Crimes can’t be swept under the rug if there is no rug.</em></blockquote><p><strong>How to fight the social connections enabling brutality</strong></p><p>Boycott businesses owned by their family members and friends. Refuse to associate with them unless they condemn and distance themselves from the culpable officers. This would starve them of emotional support. It would also reduce resources available to run away from their crimes.</p><p>All tactics we adopt should be fluid and adaptable to be able to respond to countermoves.</p><p>Long live the Federal Republic of Nigeria.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3a49399b685e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Using SQLite with Rust and Actix Web (with Tests)]]></title>
            <link>https://levelup.gitconnected.com/using-sqlite-with-rust-and-actix-web-with-tests-11a935ac3d95?source=rss-5114de41076a------2</link>
            <guid isPermaLink="false">https://medium.com/p/11a935ac3d95</guid>
            <category><![CDATA[diesel]]></category>
            <category><![CDATA[rust]]></category>
            <category><![CDATA[actix-web]]></category>
            <dc:creator><![CDATA[Uk Chukundah]]></dc:creator>
            <pubDate>Thu, 11 Jun 2020 02:42:09 GMT</pubDate>
            <atom:updated>2020-06-11T02:42:09.763Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="Photo by Markus Winkler on Unsplash." src="https://cdn-images-1.medium.com/max/1024/0*Y_p2i3T0L0Y3w9Hw.jpg" /></figure><p>In this article, we’ll explore how to use SQLite (in conjunction with Diesel) with Rust in both file and memory modes.</p><h3>Prerequisite</h3><p>In addition to having Rust &amp; Diesel CLI installed, install SQLite for your platform:</p><pre># Linux<br>$ sudo apt install sqlite3 libsqlite3-0 libsqlite3-dev</pre><pre># OSX<br>$ brew install sqlite3</pre><h3>Create project (<a href="https://github.com/ukchukx/diesel-sqlite/commit/bd1f5209c522c9df1540cc1806821a4268870e7d">commit</a>)</h3><pre>$ cargo new diesel-sqlite<br>$ cd diesel-sqlite</pre><p>Add the following dependencies:</p><ul><li>Diesel to provide ORM capabilities.</li><li>Actix web for our web layer.</li><li>Dotenv for working with environment variables.</li><li>Uuid to generate IDs.</li></ul><pre>[dependencies]<br>actix-rt = &quot;1.0&quot;<br>actix-web = &quot;2.0&quot;<br>chrono = { version = &quot;0.4.11&quot;, features = [&quot;serde&quot;] }<br>diesel = { version = &quot;1.4.4&quot;, features = [&quot;sqlite&quot;, &quot;uuidv07&quot;, &quot;chrono&quot;] }<br>dotenv = &quot;0.15.0&quot;<br>serde = { version = &quot;1.0&quot;, features = [&quot;derive&quot;] }<br>serde_json = &quot;1.0&quot;<br>uuid = { version = &quot;0.8&quot;, features = [&quot;serde&quot;, &quot;v4&quot;] }</pre><p>Next, create a .env file with a DATABASE_URL:</p><pre>DATABASE_URL=users.db</pre><h3>Initialize Diesel and create migration script (<a href="https://github.com/ukchukx/diesel-sqlite/commit/4c06113bb82a3ac66910f430e4274a154c3c02d2">commit</a>)</h3><pre>$ diesel setup<br>$ diesel migration generate create_users</pre><p>Add the following SQL statements to the generated up and down migration files.</p><pre>-- migrations/xxxx_create_users/up.sql</pre><pre>CREATE TABLE IF NOT EXISTS users (<br>  id CHARACTER(36) NOT NULL PRIMARY KEY,<br>  email VARCHAR(60),<br>  phone VARCHAR(20),<br>  created_at DATETIME DEFAULT CURRENT_TIMESTAMP NOT NULL,<br>  updated_at DATETIME DEFAULT CURRENT_TIMESTAMP NOT NULL<br>);</pre><pre>CREATE TRIGGER IF NOT EXISTS UpdateTimestamps AFTER UPDATE ON users<br>  FOR EACH ROW WHEN NEW.updated_at &lt;= OLD.updated_at <br>BEGIN <br>  update users set updated_at=CURRENT_TIMESTAMP where id=OLD.id;  <br>END;</pre><pre>-- migrations/xxxx_create_users/down.sql</pre><pre>DROP TRIGGER IF EXISTS UpdateTimestamps;</pre><pre>DROP TABLE IF EXISTS users;</pre><p>Create the users table by running:</p><pre>$ diesel migration run</pre><p>After running that, Diesel should create a schema in src/schema.rs for you.</p><p>Let’s re-organize our database files:</p><ul><li>Create a db directory under the src directory.</li><li>Move src/schema.rs into the db directory.</li><li>Update the file variable in diesel.toml from src/schema.rs to src/db/schema.rs.</li><li>Create a file models.rs in the db directory.</li></ul><p>After that, create a file src/db.rs with the following:</p><pre>// src/db.rs<br>pub mod models;<br>pub mod schema;</pre><h3>Create model (<a href="https://github.com/ukchukx/diesel-sqlite/commit/537b998b7ce67197f07ab1cd6cc82b55d170d63a">commit</a>)</h3><p>First, we’ll embed our migrations since we’ll want to use SQLite’s memory mode for our tests. An added benefit is that our migrations is compiled into our app creating a single executable and removing that dependency on a file system.</p><p>Add diesel_migrations to our dependencies:</p><pre># Cargo.toml</pre><pre>[dependencies]<br># ...<br>diesel_migrations = &quot;1.4.0&quot;</pre><p>Add these to the top of main.rs:</p><pre>// src/main.rs<br>#[macro_use]<br>extern crate diesel;<br>#[macro_use]<br>extern crate diesel_migrations;<br></pre><pre>mod db;<br>// ...</pre><p>In src/db.rs, paste:</p><pre>// src/db.rs</pre><pre>// ...<br>embed_migrations!();</pre><pre>pub fn establish_connection() -&gt; SqliteConnection {<br>    if cfg!(test) {<br>        let conn = SqliteConnection::establish(&quot;:memory:&quot;)<br>          .unwrap_or_else(|_| panic!(&quot;Error creating test database&quot;));<br>        <br>        let _result = diesel_migrations::run_pending_migrations(&amp;conn);</pre><pre>        conn<br>    } else {<br>        dotenv().ok();<br>    <br>        let database_url = env::var(&quot;DATABASE_URL&quot;).expect(&quot;DATABASE_URL must be set&quot;);<br>    <br>        SqliteConnection::establish(&amp;database_url)<br>          .unwrap_or_else(|_| panic!(&quot;Error connecting to {}&quot;, database_url))<br>    }<br>}</pre><p>We make use of Rust’s conditional compilation facilities in establish_connection() to return an in-memory connection for tests and a file connection for normal runs.</p><p>Paste this into src/db/models.rs:</p><pre>use uuid::Uuid;<br>use serde::{Deserialize, Serialize};<br>use diesel::prelude::*;</pre><pre>use super::schema::users;<br>use super::schema::users::dsl::users as user_dsl;<br></pre><pre>#[derive(Debug, Deserialize, Serialize, Queryable, Insertable)]<br>#[table_name = &quot;users&quot;]<br>pub struct User {<br>    pub id: String,<br>    pub email: Option&lt;String&gt;,<br>    pub phone: Option&lt;String&gt;,<br>    pub created_at: chrono::NaiveDateTime,<br>    pub updated_at: chrono::NaiveDateTime,<br>}</pre><pre>impl User {<br>    pub fn list(conn: &amp;SqliteConnection) -&gt; Vec&lt;Self&gt; {<br>        user_dsl.load::&lt;User&gt;(conn).expect(&quot;Error loading users&quot;)<br>    }</pre><pre>    pub fn by_id(id: &amp;str, conn: &amp;SqliteConnection) -&gt; Option&lt;Self&gt; {<br>        if let Ok(record) = user_dsl.find(id).get_result::&lt;User&gt;(conn) {<br>            Some(record)<br>        } else {<br>            None<br>        }<br>    }</pre><pre>    pub fn by_email(email_str: &amp;str, conn: &amp;SqliteConnection) -&gt; Option&lt;Self&gt; {<br>        use super::schema::users::dsl::email;</pre><pre>        if let Ok(record) = user_dsl.filter(email.eq(email_str)).first::&lt;User&gt;(conn) {<br>            Some(record)<br>        } else {<br>            None<br>        }<br>    }</pre><pre>    pub fn by_phone(phone_str: &amp;str, conn: &amp;SqliteConnection) -&gt; Option&lt;Self&gt; {<br>        use super::schema::users::dsl::phone;</pre><pre>        if let Ok(record) = user_dsl.filter(phone.eq(phone_str)).first::&lt;User&gt;(conn) {<br>            Some(record)<br>        } else {<br>            None<br>        }<br>    }</pre><pre>    pub fn create(email: Option&lt;&amp;str&gt;, phone: Option&lt;&amp;str&gt;, conn: &amp;SqliteConnection) -&gt; Option&lt;Self&gt; {<br>        let new_id = Uuid::new_v4().to_hyphenated().to_string();<br>        <br>        if email.is_none() &amp;&amp; phone.is_none() {<br>            return None<br>        } <br>                <br>        if phone.is_some() {<br>            if let Some(user) = Self::by_phone(&amp;phone.unwrap(), conn) {<br>                return Some(user)<br>            } <br>        }<br>        <br>        if email.is_some() {<br>            if let Some(user) = Self::by_email(&amp;email.unwrap(), conn) {<br>                return Some(user)<br>            } <br>        }</pre><pre>        let new_user = Self::new_user_struct(&amp;new_id, phone, email);</pre><pre>        diesel::insert_into(user_dsl)<br>            .values(&amp;new_user)<br>            .execute(conn)<br>            .expect(&quot;Error saving new user&quot;);</pre><pre>        Self::by_id(&amp;new_id, conn)<br>    }</pre><pre>    fn new_user_struct(id: &amp;str, phone: Option&lt;&amp;str&gt;, email: Option&lt;&amp;str&gt;) -&gt; Self {<br>        User {<br>            id: id.into(),<br>            email: email.map(Into::into),<br>            phone: phone.map(Into::into),<br>            created_at: chrono::Local::now().naive_local(),<br>            updated_at: chrono::Local::now().naive_local(),<br>        }<br>    }<br>}<br></pre><pre>#[cfg(test)]<br>mod user_test;</pre><p>First, we declare import and declare our User struct.<br>Each of our User methods takes a SqliteConnection argument so we can pass in any connection we want (test or otherwise) without having to alter the method.<br>For the query methods, Diesel returns a Result, which we convert to an Option with <a href="https://doc.rust-lang.org/std/result/enum.Result.html#method.ok">.ok()</a> to conform to our return type.</p><p>In create(), we first ensure that the supplied email and/or phone do not exist in the database before creating a new User record.</p><p>At the bottom of the file, we declare that the tests are declared in a file located in src/db/models/user_test.rs by convention.</p><p>Paste these tests in the file:</p><pre>use crate::db::{establish_connection, models::User};</pre><pre>#[test]<br>fn create_user_with_phone_and_email() {<br>    let conn = establish_connection();<br>    let email = Some(&quot;test@email.com&quot;);<br>    let phone = Some(&quot;123456789&quot;);</pre><pre>    let user = User::create(email, phone, &amp;conn).unwrap();</pre><pre>    assert_eq!(user.email.unwrap().as_str(), email.unwrap());<br>    assert_eq!(user.phone.unwrap().as_str(), phone.unwrap());<br>}</pre><pre>#[test]<br>fn create_user_with_phone_only() {<br>    let conn = establish_connection();<br>    let email = None;<br>    let phone = Some(&quot;123456789&quot;);</pre><pre>    let user = User::create(email, phone, &amp;conn).unwrap();</pre><pre>    assert!(user.email.is_none());<br>    assert_eq!(user.phone.unwrap().as_str(), phone.unwrap());<br>}</pre><pre>#[test]<br>fn create_user_with_email_only() {<br>    let conn = establish_connection();<br>    let email = Some(&quot;test@email.com&quot;);<br>    let phone = None;</pre><pre>    let user = User::create(email, phone, &amp;conn).unwrap();</pre><pre>    assert_eq!(user.email.unwrap().as_str(), email.unwrap());<br>    assert!(user.phone.is_none());<br>}</pre><pre>#[test]<br>fn create_user_with_existing_email() {<br>    let conn = establish_connection();<br>    let email = Some(&quot;test@email.com&quot;);<br>    let phone = None;</pre><pre>    let user = User::create(email, phone, &amp;conn).unwrap();<br>    let existing_user = User::create(email, phone, &amp;conn).unwrap();</pre><pre>    assert_eq!(user.id, existing_user.id);<br>}</pre><pre>#[test]<br>fn create_user_with_existing_phone() {<br>    let conn = establish_connection();<br>    let email = None;<br>    let phone = Some(&quot;123456789&quot;);</pre><pre>    let user = User::create(email, phone, &amp;conn).unwrap();<br>    let existing_user = User::create(email, phone, &amp;conn).unwrap();</pre><pre>    assert_eq!(user.id, existing_user.id);<br>}</pre><pre>#[test]<br>fn list_users() {<br>    let conn = establish_connection();<br>    let email = None;<br>    let phone = Some(&quot;123456789&quot;);</pre><pre>    let user = User::create(email, phone, &amp;conn).unwrap();<br>    let existing_users = User::list(&amp;conn);</pre><pre>    assert_eq!(1, existing_users.len());<br>    assert_eq!(user.id, existing_users[0].id);<br>}</pre><pre>#[test]<br>fn get_user_by_phone() {<br>    let conn = establish_connection();<br>    let email = None;<br>    let phone = Some(&quot;123456789&quot;);</pre><pre>    let user = User::create(email, phone, &amp;conn).unwrap();<br>    let existing_user = User::by_phone(&amp;phone.unwrap(), &amp;conn).unwrap();</pre><pre>    assert_eq!(user.id, existing_user.id);<br>}</pre><pre>#[test]<br>fn get_user_by_email() {<br>    let conn = establish_connection();<br>    let email = Some(&quot;test@email.com&quot;);<br>    let phone = None;</pre><pre>    let user = User::create(email, phone, &amp;conn).unwrap();<br>    let existing_user = User::by_email(&amp;email.unwrap(), &amp;conn).unwrap();</pre><pre>    assert_eq!(user.id, existing_user.id);<br>}</pre><pre>#[test]<br>fn get_user_by_id() {<br>    let conn = establish_connection();<br>    let email = Some(&quot;test@email.com&quot;);<br>    let phone = Some(&quot;123456789&quot;);</pre><pre>    let user = User::create(email, phone, &amp;conn).unwrap();<br>    let existing_user = User::by_id(&amp;user.id, &amp;conn).unwrap();</pre><pre>    assert_eq!(user.id, existing_user.id);<br>}</pre><h3>Add a web service (<a href="https://github.com/ukchukx/diesel-sqlite/commit/a987f138b2e9b74d818d09fafe28c7bb76e9357c">commit</a>)</h3><p>Update our actix-web dependency to provide some test facilities that aren&#39;t available in 2.0 and add r2d2 to help with connection pooling:</p><pre>[dependencies]<br># ...<br>actix-web = &quot;3.0.0-alpha.1&quot;<br>diesel = { version = &quot;1.4.4&quot;, features = [&quot;sqlite&quot;, &quot;uuidv07&quot;, &quot;r2d2&quot;, &quot;chrono&quot;] }<br>r2d2 = &quot;0.8.8&quot;<br>r2d2-diesel = &quot;1.0.0&quot;</pre><p>Let’s refactor src/db.rs to use connection pooling:</p><pre>// src/db.rs<br>// ...<br>use diesel::sqlite::SqliteConnection;<br>use r2d2_diesel::ConnectionManager;<br>use r2d2::Pool;<br></pre><pre>embed_migrations!();<br></pre><pre>pub type DbPool = Pool&lt;ConnectionManager&lt;SqliteConnection&gt;&gt;;<br></pre><pre>pub fn run_migrations(conn: &amp;SqliteConnection) {<br>  let _ = diesel_migrations::run_pending_migrations(&amp;*conn);<br>}</pre><pre>pub fn establish_connection() -&gt; DbPool {<br>    if cfg!(test) {<br>        let manager = ConnectionManager::&lt;SqliteConnection&gt;::new(&quot;:memory:&quot;);<br>        let pool = r2d2::Pool::builder().build(manager).expect(&quot;Failed to create DB pool.&quot;);<br>        <br>        run_migrations(&amp;pool.get().unwrap());</pre><pre>        pool<br>    } else {<br>        dotenv().ok();<br>    <br>        let database_url = env::var(&quot;DATABASE_URL&quot;).expect(&quot;DATABASE_URL must be set&quot;);<br>        let manager = ConnectionManager::&lt;SqliteConnection&gt;::new(&amp;database_url);<br>        <br>        r2d2::Pool::builder().build(manager).expect(&quot;Failed to create DB pool.&quot;)<br>    }<br>}</pre><p>We also separate creating a test connection pool from running migrations.</p><p>In each of our models test, we change the way we get connections from</p><pre>let conn = establish_connection();</pre><p>to</p><pre>let conn = establish_connection().get().unwrap();</pre><p>Create a service module src/services.rs and paste:</p><pre>// src/services.rs<br>pub mod user;</pre><pre>#[cfg(test)]<br>mod user_test;</pre><p>Then we create the user service file src/services/user.rs and paste:</p><pre>// src/services/user.rs<br>use actix_web::{HttpResponse, web};<br>use serde::{Serialize, Deserialize};</pre><pre>use crate::db::{DbPool, models::User};</pre><pre>#[derive(Serialize, Deserialize)]<br>pub struct UserForm {<br>    email: Option&lt;String&gt;,<br>    phone: Option&lt;String&gt;,<br>}</pre><pre>pub fn create(user_form: web::Json&lt;UserForm&gt;, pool: web::Data&lt;DbPool&gt;) -&gt; HttpResponse {<br>    let conn = pool.get().unwrap();</pre><pre>    match User::create(user_form.email.as_deref(), user_form.phone.as_deref(), &amp;conn) {<br>        Some(user) =&gt; HttpResponse::Ok().json(user),<br>        _ =&gt; HttpResponse::InternalServerError().json(&quot;Could not create user&quot;)<br>    }<br>}</pre><pre>pub fn index(pool: web::Data&lt;DbPool&gt;) -&gt; HttpResponse {<br>    let conn = pool.get().unwrap();</pre><pre>    HttpResponse::Ok().json(User::list(&amp;conn))<br>}</pre><pre>pub fn get(id: web::Path&lt;String&gt;, pool: web::Data&lt;DbPool&gt;) -&gt; HttpResponse {<br>    let conn = pool.get().unwrap();</pre><pre>    match User::by_id(&amp;id, &amp;conn) {<br>        Some(user) =&gt; HttpResponse::Ok().json(user),<br>        _ =&gt; HttpResponse::NotFound().json(&quot;Not Found&quot;)<br>    }<br>}</pre><pre>pub fn init_routes(cfg: &amp;mut web::ServiceConfig) {<br>    /* <br>     * index: curl -i -X GET -H &quot;Content-Type: application/json&quot; http://localhost:5000/users<br>     * get: curl -i -X GET -H &quot;Content-Type: application/json&quot; http://localhost:5000/users/&lt;id&gt;<br>     * post: curl -i -X POST -H &quot;Content-Type: application/json&quot; -d &#39;{&quot;email&quot;:&quot;xxx&quot;, &quot;phone&quot;: &quot;yyy&quot;}&#39; http://localhost:5000/users<br>     */<br>    <br>    cfg.service(<br>        web::resource(&quot;/users&quot;)<br>            .route(web::post().to(create))<br>            .route(web::get().to(index))<br>    )<br>    .service(<br>        web::scope(&quot;/users&quot;)<br>            .route(&quot;/{id}&quot;, web::get().to(get)),<br>    );<br>}</pre><p>create(), index() and get() handle creating, listing and getting a user by id.<br>init_routes() adds our routes to the web server.</p><p>We then update src/main.rs to start our web server:</p><pre>// src/main.rs</pre><pre>// ...<br>#[macro_use]<br>extern crate serde_json;<br>extern crate r2d2_diesel;<br></pre><pre>// ...<br>mod services;<br></pre><pre>#[actix_rt::main]<br>async fn main() -&gt; std::io::Result&lt;()&gt; {<br>    use actix_web::{App, HttpServer, web::JsonConfig};</pre><pre>    let conn_pool = db::establish_connection();</pre><pre>    HttpServer::new(move || {<br>        App::new()<br>            .data(conn_pool.clone())<br>            .data(JsonConfig::default().limit(4096))<br>            .configure(services::user::init_routes)<br>    })<br>    .bind(&quot;0.0.0.0:5000&quot;)?<br>    .run()<br>    .await<br>}</pre><p>With that update, our service is ready to receive and serve requests.</p><p>Let’s add tests so we can have some assurance that our service does what it is billed to do.<br>In src/services/user_test.rs, paste:</p><pre>// src/services/user_test.rs<br>use actix_web::{<br>    App,<br>    test::{read_body_json, read_body, init_service, TestRequest}<br>};</pre><pre>use crate::{db::{models::User, establish_connection}, services::user::init_routes};</pre><pre>#[actix_rt::test]<br>async fn create_user_from_api() {<br>    let test_email   = &quot;test@email.com&quot;;<br>    let test_phone   = &quot;123456789&quot;;<br>    let request_body = json!({ &quot;email&quot;: test_email, &quot;phone&quot;: test_phone });<br>    let conn_pool    = establish_connection();<br>    let mut app      = init_service(App::new().data(conn_pool.clone()).configure(init_routes)).await;</pre><pre>    let resp = TestRequest::post()<br>      .uri(&quot;/users&quot;)<br>      .set_json(&amp;request_body)<br>      .send_request(&amp;mut app)<br>      .await;</pre><pre>    assert!(resp.status().is_success(), &quot;Failed to create user&quot;);</pre><pre>    let user: User = read_body_json(resp).await;</pre><pre>    assert_eq!(user.email.unwrap(), test_email);<br>    assert_eq!(user.phone.unwrap(), test_phone);<br>}</pre><pre>#[actix_rt::test]<br>async fn get_user_from_api_by_id() {<br>    let test_email   = &quot;test@email.com&quot;;<br>    let test_phone   = &quot;123456789&quot;;<br>    let request_body = json!({ &quot;email&quot;: test_email, &quot;phone&quot;: test_phone });<br>    let conn_pool    = establish_connection();<br>    let mut app      = init_service(App::new().data(conn_pool.clone()).configure(init_routes)).await;</pre><pre>    let create_resp = TestRequest::post()<br>      .uri(&quot;/users&quot;)<br>      .set_json(&amp;request_body)<br>      .send_request(&amp;mut app)<br>      .await;</pre><pre>    assert!(create_resp.status().is_success(), &quot;Failed to create user&quot;);</pre><pre>    let created_user: User = read_body_json(create_resp).await;<br>    println!(&quot;/users/{}&quot;, created_user.id);<br>    <br>    let resp = TestRequest::get()<br>      .uri(format!(&quot;/users/{}&quot;, created_user.id).as_str())<br>      .send_request(&amp;mut app)<br>      .await;</pre><pre>    assert!(resp.status().is_success(), &quot;Failed to get user&quot;);</pre><pre>    let retrieved_user: User = read_body_json(resp).await;</pre><pre>    assert_eq!(created_user.id, retrieved_user.id);<br>}</pre><pre>#[actix_rt::test]<br>async fn list_users_from_api() {<br>    let test_email   = &quot;test@email.com&quot;;<br>    let test_phone   = &quot;123456789&quot;;<br>    let request_body = json!({ &quot;email&quot;: test_email, &quot;phone&quot;: test_phone });<br>    let conn_pool    = establish_connection();<br>    let mut app      = init_service(App::new().data(conn_pool.clone()).configure(init_routes)).await;</pre><pre>    let mut list_resp = TestRequest::get().uri(&quot;/users&quot;).send_request(&amp;mut app).await;<br>    <br>    assert!(list_resp.status().is_success(), &quot;Failed to list users&quot;);</pre><pre>    let mut body = read_body(list_resp).await;  <br>    let mut retrieved_users: Vec&lt;User&gt; = serde_json::from_slice::&lt;Vec&lt;User&gt;&gt;(&amp;body).unwrap();</pre><pre>    assert_eq!(retrieved_users.len(), 0);</pre><pre>    let create_resp = TestRequest::post()<br>      .uri(&quot;/users&quot;)<br>      .set_json(&amp;request_body)<br>      .send_request(&amp;mut app)<br>      .await;</pre><pre>    assert!(create_resp.status().is_success(), &quot;Failed to create user&quot;);<br>    <br>    list_resp = TestRequest::get().uri(&quot;/users&quot;).send_request(&amp;mut app).await;</pre><pre>    assert!(list_resp.status().is_success(), &quot;Failed to list users&quot;);</pre><pre>    body = read_body(list_resp).await;    <br>    retrieved_users = serde_json::from_slice::&lt;Vec&lt;User&gt;&gt;(&amp;body).unwrap();</pre><pre>    assert_eq!(retrieved_users.len(), 1);<br>}</pre><p>The complete code can be found <a href="https://github.com/ukchukx/diesel-sqlite">here</a>.</p><h3>Credits</h3><p>Photo by <a href="https://unsplash.com/@markuswinkler">Markus Winkler</a> on Unsplash.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=11a935ac3d95" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/using-sqlite-with-rust-and-actix-web-with-tests-11a935ac3d95">Using SQLite with Rust and Actix Web (with Tests)</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Using RocksDB with Rust and Actix-Web]]></title>
            <link>https://levelup.gitconnected.com/using-rocksdb-with-rust-and-actix-web-98507c9db267?source=rss-5114de41076a------2</link>
            <guid isPermaLink="false">https://medium.com/p/98507c9db267</guid>
            <category><![CDATA[rocksdb]]></category>
            <category><![CDATA[rust]]></category>
            <category><![CDATA[actix-web]]></category>
            <dc:creator><![CDATA[Uk Chukundah]]></dc:creator>
            <pubDate>Sun, 19 Apr 2020 12:38:06 GMT</pubDate>
            <atom:updated>2021-07-15T03:21:27.393Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*8OQeNhpbozNyLRkH" /><figcaption>Photo by <a href="https://unsplash.com/@joeriromer?utm_source=medium&amp;utm_medium=referral">Joeri Römer</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>To aid in my learning of Rust, I decided to implement the <a href="https://medium.com/@ukchukx/99cb1c43a834">Java RocksDB example</a> in Rust seeing it is simple enough.</p><p>It didn’t turn out as simple as I hoped owing to Rust’s strict borrowing and lifetime concepts — which almost everyone trips over sooner or later. I originally wanted to directly store json::value::JsonValue enums serialized with <a href="https://crates.io/crates/bincode">bincode</a>. The main errors I encountered were:</p><pre>the trait `serde::ser::Serialize` is not implemented for `json::value::JsonValue`<br>...<br>the trait `serde::de::Deserialize&lt;&#39;_&gt;` is not implemented for `json::value::JsonValue`</pre><p>I’m sure I could have implemented the traits for that enum if I put in the effort, but seeing as this was supposed to be a simple throwaway example it was fast becoming more than I signed up for.<br>I decided to work with strings at the repository layer and leave de/serialization to users because I’m lazy like that. ¯\_(ツ)_/¯</p><p>We only need json, actix-web, bytes (to read POST bodies) and rocksdb as dependencies:</p><pre>[dependencies]<br>actix-rt = &quot;1.0&quot;<br>actix-web = &quot;2.0&quot;<br>bytes = &quot;0.5.2&quot;<br>env_logger = &quot;0.7.1&quot;<br>json = &quot;0.12&quot;<br>rocksdb = &quot;0.13.0&quot;</pre><p>Then we create our repository module src/kv.rs:</p><pre>// src/kv.rs<br>use rocksdb::DB;<br>use std::sync::Arc;</pre><pre>pub trait KVStore {<br>    fn init(file_path: &amp;str) -&gt; Self;<br>    fn save(&amp;self, k: &amp;str, v: &amp;str) -&gt; bool;<br>    fn find(&amp;self, k: &amp;str) -&gt; Option&lt;String&gt;;<br>    fn delete(&amp;self, k: &amp;str) -&gt; bool;<br>}</pre><pre>#[derive(Clone)]<br>pub struct RocksDB {<br>    db: Arc&lt;DB&gt;,<br>}<br></pre><pre>impl KVStore for RocksDB {<br>    fn init(file_path: &amp;str) -&gt; Self {<br>        RocksDB { db: Arc::new(DB::open_default(file_path).unwrap()) }<br>    }</pre><pre>    fn save(&amp;self, k: &amp;str, v: &amp;str) -&gt; bool {<br>        self.db.put(k.as_bytes(), v.as_bytes()).is_ok()<br>    }</pre><pre>    fn find(&amp;self, k: &amp;str) -&gt; Option&lt;String&gt; {<br>        match self.db.get(k.as_bytes()) {<br>            Ok(Some(v)) =&gt; {<br>                let result = String::from_utf8(v).unwrap();<br>                println!(&quot;Finding &#39;{}&#39; returns &#39;{}&#39;&quot;, k, result);<br>                Some(result)<br>            },<br>            Ok(None) =&gt; {<br>                println!(&quot;Finding &#39;{}&#39; returns None&quot;, k);<br>                None<br>            },<br>            Err(e) =&gt; {<br>                println!(&quot;Error retrieving value for {}: {}&quot;, k, e);<br>                None<br>            }<br>        }<br>    }</pre><pre>    fn delete(&amp;self, k: &amp;str) -&gt; bool {<br>        self.db.delete(k.as_bytes()).is_ok()<br>    }<br>}</pre><p>We declare our key-value repository interface (or traits in Rust) KVStore. The RocksDB struct is to hold the opened database we&#39;ll be working with. We wrap DB in Arc so it can be shared safely across threads. We want Actix-web to pass our database handle to our route handlers when they&#39;re called, but DB does not implement Clone, and so has to be wrapped in Arc to work.</p><p>We then move on to implement our trait (or interface) for RocksDB. RocksDB only works with bytes so we have to convert our string keys and values to bytes.</p><p>Next, we’ll write our route handler module src/kv_handler.rs:</p><pre>// src/kv_handler.rs<br>use actix_web::{web::{Data, Path}, HttpResponse};<br>use bytes::Bytes;<br>use json::parse;</pre><pre>use crate::kv::{KVStore, RocksDB};</pre><pre>// curl -i -X GET -H &quot;Content-Type: application/json&quot; http://localhost:8080/api/foo<br>pub async fn get(key: Path&lt;String&gt;, db: Data&lt;RocksDB&gt;) -&gt; HttpResponse {<br>    match &amp;db.find(&amp;key.into_inner()) {<br>        Some(v) =&gt; {<br>            parse(v)<br>                .map(|obj| HttpResponse::Ok().content_type(&quot;application/json&quot;).body(obj.dump()))<br>                .unwrap_or(HttpResponse::InternalServerError().content_type(&quot;application/json&quot;).finish())<br>        }<br>        None    =&gt; HttpResponse::NotFound().content_type(&quot;application/json&quot;).finish()<br>    }<br>}</pre><pre>// curl -i -X POST -H &quot;Content-Type: application/json&quot; -d &#39;{&quot;bar&quot;:&quot;baz&quot;}&#39; http://localhost:8080/api/foo<br>pub async fn post(key:  Path&lt;String&gt;,<br>                  db:   Data&lt;RocksDB&gt;,<br>                  body: Bytes) -&gt; HttpResponse {<br>    match String::from_utf8(body.to_vec()) {<br>        Ok(body) =&gt; match &amp;db.save(&amp;key.into_inner(), &amp;body) {<br>            true  =&gt; {<br>                parse(&amp;body)<br>                    .map(|obj| HttpResponse::Ok().content_type(&quot;application/json&quot;).body(obj.dump()))<br>                    .unwrap_or(HttpResponse::InternalServerError().content_type(&quot;application/json&quot;).finish())<br>            }<br>            false =&gt; HttpResponse::InternalServerError().content_type(&quot;application/json&quot;).finish()<br>        }<br>        Err(_) =&gt; HttpResponse::InternalServerError().content_type(&quot;application/json&quot;).finish(),<br>    }<br>}</pre><pre>// curl -i -X DELETE -H &quot;Content-Type: application/json&quot; http://localhost:8080/api/foo<br>pub async fn delete(key: Path&lt;String&gt;, db: Data&lt;RocksDB&gt;) -&gt; HttpResponse {<br>    match &amp;db.delete(&amp;key.into_inner()) {<br>        true  =&gt; HttpResponse::NoContent().content_type(&quot;application/json&quot;).finish(),<br>        false =&gt; HttpResponse::InternalServerError().content_type(&quot;application/json&quot;).finish()<br>    }<br>}</pre><p>Each route takes the key path param and a handle to the database handle we opened earlier.</p><p>When we receive a GET request, we query RocksDB with the provided key. If a value is returned, we parse it to JSON and return. We return 404 if we found nothing.</p><p>When we receive a POST request, we convert the supplied body to a string and store in RocksDB. We then parse the body to JSON and send back as response.</p><p>For DELETE requests, we return 204 if we were able to delete the key-value pair or 500 otherwise.</p><p>All that’s left is to initialize our database and register our route handlers. Let’s handle that in src/main.rs:</p><pre>// src/main.rs<br>mod kv;<br>mod kv_handler;<br></pre><pre>#[actix_rt::main]<br>async fn main() -&gt; std::io::Result&lt;()&gt; {<br>    use actix_web::{<br>        middleware::Logger,<br>        web::{scope, resource, get, post, delete},<br>        App,<br>        HttpServer<br>    };</pre><pre>    let db: kv::RocksDB = kv::KVStore::init(&quot;/tmp/rocks/actix-db&quot;);</pre><pre>    std::env::set_var(&quot;RUST_LOG&quot;, &quot;actix_web=info,actix_server=info&quot;);<br>    env_logger::init();</pre><pre>    HttpServer::new(move || {<br>        App::new()<br>            .data(db.clone())<br>            .wrap(Logger::default())<br>            .service(<br>                scope(&quot;/api&quot;)<br>                .service(<br>                    resource(&quot;/{key}&quot;)<br>                        .route(get().to(kv_handler::get))<br>                        .route(post().to(kv_handler::post))<br>                        .route(delete().to(kv_handler::delete)),<br>                ),<br>            )<br>    })<br>    .bind(&quot;0.0.0.0:8080&quot;)?<br>    .run()<br>    .await<br>}</pre><p>The source code can be found <a href="https://github.com/ukchukx/rocksdb-rust">here</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=98507c9db267" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/using-rocksdb-with-rust-and-actix-web-98507c9db267">Using RocksDB with Rust and Actix-Web</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Using RocksDB with Spring Boot and Java]]></title>
            <link>https://levelup.gitconnected.com/using-rocksdb-with-spring-boot-and-java-99cb1c43a834?source=rss-5114de41076a------2</link>
            <guid isPermaLink="false">https://medium.com/p/99cb1c43a834</guid>
            <category><![CDATA[rocksdb]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[Uk Chukundah]]></dc:creator>
            <pubDate>Sat, 18 Apr 2020 12:46:56 GMT</pubDate>
            <atom:updated>2021-07-15T03:22:19.395Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*uKk2beL5neN8ls2T" /><figcaption>Photo by <a href="https://unsplash.com/@arstyy?utm_source=medium&amp;utm_medium=referral">Austin Neill</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p><a href="https://rocksdb.org/">RocksDB</a> is an embedded key-value store by Facebook, which is a fork of <a href="https://github.com/google/leveldb">LevelDB</a> by Google. It is used as a storage layer for a number of databases e.g. <a href="https://www.cockroachlabs.com/">CockroachDB</a>. You can use it as an embedded store, a cache (instead of Redis), as a storage layer for your own custom database, file system or storage solution etc.</p><blockquote><em>TL; DR: Here’s the </em><a href="https://github.com/ukchukx/rocksdb-example"><em>code</em></a><em>.</em></blockquote><p>In your pom.xml, add the following dependency to bring in RocksDB:</p><pre>&lt;dependency&gt;                           <br>    &lt;groupId&gt;org.rocksdb&lt;/groupId&gt; <br>    &lt;artifactId&gt;rocksdbjni&lt;/artifactId&gt;  <br>    &lt;version&gt;6.6.4&lt;/version&gt;   <br>&lt;/dependency&gt;</pre><p>If you use Gradle…you’ll have to fend for yourself, I’m sorry. ¯\_(ツ)_/¯</p><p>For reference, you can look at my own <a href="https://github.com/ukchukx/rocksdb-example/blob/master/pom.xml">pom.xml</a>.</p><p>After that, we want to describe a repository interface through which our app can interact with storage services in general, and RocksDB in particular.</p><pre>import java.util.Optional;</pre><pre>public interface KVRepository&lt;K, V&gt; {<br>  boolean save(K key, V value);<br>  Optional&lt;V&gt; find(K key);<br>  boolean delete(K key);<br>}</pre><p>Saving, finding, and deleting are the basics we require from any key-value store, so we define that. With this interface, we can use any key-value store without changing other parts of our app which is good design.<br>Next, we create our RocksDB repository as an implementation of this interface:</p><pre>import lombok.extern.slf4j.Slf4j;<br>import org.rocksdb.Options;<br>import org.rocksdb.RocksDB;<br>import org.rocksdb.RocksDBException;<br>import org.springframework.stereotype.Repository;<br>import org.springframework.util.SerializationUtils;</pre><pre>import javax.annotation.PostConstruct;<br>import java.io.File;<br>import java.io.IOException;<br>import java.nio.file.Files;<br>import java.util.Optional;</pre><pre>@Slf4j<br>@Repository<br>public class RocksDBRepository implements KVRepository&lt;String, Object&gt; {<br>  private final static String FILE_NAME = &quot;spring-boot-db&quot;;<br>  File baseDir;<br>  RocksDB db;</pre><pre>  @PostConstruct // execute after the application starts.<br>  void initialize() {<br>    RocksDB.loadLibrary();<br>    final Options options = new Options();<br>    options.setCreateIfMissing(true);<br>    baseDir = new File(&quot;/tmp/rocks&quot;, FILE_NAME);</pre><pre>    try {<br>      Files.createDirectories(baseDir.getParentFile().toPath());<br>      Files.createDirectories(baseDir.getAbsoluteFile().toPath());<br>      db = RocksDB.open(options, baseDir.getAbsolutePath());</pre><pre>      log.info(&quot;RocksDB initialized&quot;);<br>    } catch(IOException | RocksDBException e) {<br>      log.error(&quot;Error initializng RocksDB. Exception: &#39;{}&#39;, message: &#39;{}&#39;&quot;, e.getCause(), e.getMessage(), e);<br>    }<br>  }</pre><pre>  @Override<br>  public synchronized boolean save(String key, Object value) {<br>    log.info(&quot;saving value &#39;{}&#39; with key &#39;{}&#39;&quot;, value, key);</pre><pre>    try {<br>      db.put(key.getBytes(), SerializationUtils.serialize(value));<br>    } catch (RocksDBException e) {<br>      log.error(&quot;Error saving entry. Cause: &#39;{}&#39;, message: &#39;{}&#39;&quot;, e.getCause(), e.getMessage());</pre><pre>      return false;<br>    }</pre><pre>    return true;<br>  }</pre><pre>  @Override<br>  public synchronized Optional&lt;Object&gt; find(String key) {<br>    Object value = null;</pre><pre>    try {<br>      byte[] bytes = db.get(key.getBytes());<br>      if (bytes != null) value = SerializationUtils.deserialize(bytes);<br>    } catch (RocksDBException e) {<br>      log.error(<br>        &quot;Error retrieving the entry with key: {}, cause: {}, message: {}&quot;, <br>        key, <br>        e.getCause(), <br>        e.getMessage()<br>      );<br>    }</pre><pre>    log.info(&quot;finding key &#39;{}&#39; returns &#39;{}&#39;&quot;, key, value);</pre><pre>    return value != null ? Optional.of(value) : Optional.empty();<br>  }</pre><pre>  @Override<br>  public synchronized boolean delete(String key) {<br>    log.info(&quot;deleting key &#39;{}&#39;&quot;, key);</pre><pre>    try {<br>      db.delete(key.getBytes());<br>    } catch (RocksDBException e) {<br>      log.error(&quot;Error deleting entry, cause: &#39;{}&#39;, message: &#39;{}&#39;&quot;, e.getCause(), e.getMessage());</pre><pre>      return false;<br>    }</pre><pre>    return true;<br>  }<br>}</pre><p>We initialize our database when the app starts in initialize(). RocksDB is a low-level store, so we need to serialize our key-value pairs to bytes before interacting with it in save(), find() and delete().</p><p>That’s all there is to it…really.</p><p>At this stage, our repository is done but not very usable. Let’s add a controller to enable us interact with the repository:</p><pre>import com.ukchukx.rocksdbexample.repository.KVRepository;<br>import lombok.extern.slf4j.Slf4j;<br>import org.springframework.http.MediaType;<br>import org.springframework.http.ResponseEntity;<br>import org.springframework.http.HttpStatus;<br>import org.springframework.web.bind.annotation.DeleteMapping;<br>import org.springframework.web.bind.annotation.GetMapping;<br>import org.springframework.web.bind.annotation.PathVariable;<br>import org.springframework.web.bind.annotation.PostMapping;<br>import org.springframework.web.bind.annotation.RequestBody;<br>import org.springframework.web.bind.annotation.RequestMapping;<br>import org.springframework.web.bind.annotation.RestController;</pre><pre>import java.util.Optional;</pre><pre>@Slf4j<br>@RestController<br>@RequestMapping(&quot;/api&quot;)<br>public class Api {<br>  private final KVRepository&lt;String, Object&gt; repository;</pre><pre>  public Api(KVRepository&lt;String, Object&gt; repository) {<br>    this.repository = repository;<br>  }</pre><pre>  // curl -iv -X POST -H &quot;Content-Type: application/json&quot; -d &#39;{&quot;bar&quot;:&quot;baz&quot;}&#39; http://localhost:8080/api/foo<br>  @PostMapping(value = &quot;/{key}&quot;, <br>              consumes = MediaType.APPLICATION_JSON_VALUE, <br>              produces = MediaType.APPLICATION_JSON_VALUE)<br>  public ResponseEntity&lt;Object&gt; save(@PathVariable(&quot;key&quot;) String key, @RequestBody Object value) {<br>    return repository.save(key, value) <br>      ? ResponseEntity.ok(value) <br>      : ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();<br>  }</pre><pre>  // curl -iv -X GET -H &quot;Content-Type: application/json&quot; http://localhost:8080/api/foo<br>  @GetMapping(value = &quot;/{key}&quot;, produces = MediaType.APPLICATION_JSON_VALUE)<br>  public ResponseEntity&lt;Object&gt; find(@PathVariable(&quot;key&quot;) String key) {<br>    return ResponseEntity.of(repository.find(key));<br>  }</pre><pre>  // curl -iv -X DELETE -H &quot;Content-Type: application/json&quot; http://localhost:8080/api/foo<br>  @DeleteMapping(value = &quot;/{key}&quot;, produces = MediaType.APPLICATION_JSON_VALUE)<br>  public ResponseEntity&lt;Object&gt; delete(@PathVariable(&quot;key&quot;) String key) {<br>    return repository.delete(key) <br>      ? ResponseEntity.noContent().build() <br>      : ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();<br>  }<br>}</pre><p>We declare a simple REST controller that exposes save, find and delete endpoints. That’s all there is to it.</p><p>Go ahead and save, find and delete items to your heart’s content using either cURL or Postman.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=99cb1c43a834" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/using-rocksdb-with-spring-boot-and-java-99cb1c43a834">Using RocksDB with Spring Boot and Java</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[User authentication in Rust]]></title>
            <link>https://medium.com/swlh/user-authentication-in-rust-ee8116934d73?source=rss-5114de41076a------2</link>
            <guid isPermaLink="false">https://medium.com/p/ee8116934d73</guid>
            <category><![CDATA[self-contained-services]]></category>
            <category><![CDATA[actix-web]]></category>
            <category><![CDATA[rust]]></category>
            <dc:creator><![CDATA[Uk Chukundah]]></dc:creator>
            <pubDate>Sat, 11 Apr 2020 18:05:45 GMT</pubDate>
            <atom:updated>2020-04-25T23:46:09.657Z</atom:updated>
            <content:encoded><![CDATA[<p>This is the final part of our exploratory series on creating a web service with Rust. Our exploration is broken down into distinct steps to make it easier for you to follow along:</p><ul><li><a href="https://medium.com/@ukchukx/55d0b0a848d">Setup</a>.</li><li><a href="https://medium.com/@ukchukx/162667ee40f6">Sending a confirmation email</a>.</li><li>User account creation and authentication (you are here).</li></ul><h3>Creating a password via API</h3><p>We need a new error type for cases where resources are not found.</p><pre>// src/errors.rs<br>//...</pre><pre>#[derive(Clone, Debug, Display)]<br>pub enum AuthError {<br>   // ...</pre><pre>    #[display(fmt = &quot;NotFound: {}&quot;, _0)]<br>    NotFound(String),<br>}<br></pre><pre>impl ResponseError for AuthError {<br>    fn error_response(&amp;self) -&gt; HttpResponse {<br>        match self { <br>            // ...</pre><pre>            AuthError::NotFound(ref message) =&gt; HttpResponse::NotFound().json(message),<br>        }<br>    }<br>}<br>// ...</pre><p>In main.rs, let&#39;s add a handler that would take a confirmation id and password and create a user account.</p><pre>// src/main.rs<br>// ...<br>mod password_handler;<br></pre><pre>#[actix_rt::main]<br>async fn main() -&gt; std::io::Result&lt;()&gt; {<br>    // ...</pre><pre>    // Start http server<br>    HttpServer::new(move || {<br>        App::new()<br>            // ...<br>            // Routes<br>            .service(<br>                web::scope(&quot;/&quot;)<br>                    // ...<br>                    .service(<br>                        web::resource(&quot;/register/{path_id}&quot;)<br>                            .route(web::post().to(password_handler::create_account)),<br>                    ),<br>            )<br>    })<br>    // ...<br>}</pre><p>We then create src/password_handler.rs which will contain our handler:</p><pre>// src/password_handler.rs<br>use actix_web::{error::BlockingError, web, HttpResponse};<br>use actix_session::Session;<br>use diesel::prelude::*;<br>use serde::Deserialize;</pre><pre>use crate::{<br>    models::{Confirmation, Pool, SessionUser, User}, <br>    errors::AuthError, <br>    schema::{<br>      confirmations::dsl::{id, confirmations},<br>      users::dsl::users<br>    },<br>    utils::{hash_password, is_signed_in, set_current_user}<br>};<br></pre><pre>#[derive(Debug, Deserialize)]<br>pub struct PasswordData {<br>    pub password: String,<br>}</pre><pre>pub async fn create_account(session: Session,<br>                          path_id: web::Path&lt;String&gt;,<br>                          data: web::Json&lt;PasswordData&gt;,<br>                          pool: web::Data&lt;Pool&gt;) -&gt; Result&lt;HttpResponse, AuthError&gt; {<br>    if is_signed_in(&amp;session) {<br>        return Ok(HttpResponse::BadRequest().finish());<br>    }</pre><pre>    let result = web::block(move || create_user(&amp;path_id.into_inner(), &amp;data.into_inner().password, &amp;pool)).await;</pre><pre>    match result {<br>        Ok(user) =&gt; {<br>            set_current_user(&amp;session, &amp;user);</pre><pre>            Ok(HttpResponse::Created().json(&amp;user))<br>        },<br>        Err(err) =&gt; match err {<br>            BlockingError::Error(auth_error) =&gt; Err(auth_error),<br>            BlockingError::Canceled =&gt; Err(AuthError::GenericError(String::from(&quot;Could not complete the process&quot;))),<br>        },<br>    }<br>}<br></pre><pre>fn create_user(path_id: &amp;str, password: &amp;str, pool: &amp;web::Data&lt;Pool&gt;) -&gt; Result&lt;SessionUser, AuthError&gt; {<br>    let path_uuid = uuid::Uuid::parse_str(path_id)?;<br>    let conn = &amp;pool.get().unwrap();</pre><pre>    confirmations<br>        .filter(id.eq(path_uuid))<br>        .load::&lt;Confirmation&gt;(conn)<br>        .map_err(|_db_error| AuthError::NotFound(String::from(&quot;Confirmation not found&quot;)))<br>        .and_then(|mut result| {<br>            if let Some(confirmation) = result.pop() {<br>                if confirmation.expires_at &gt; chrono::Local::now().naive_local() { // confirmation has not expired<br>                    let password: String = hash_password(password)?;<br>                    let user: User = diesel::insert_into(users)<br>                                            .values(&amp;User::from(confirmation.email, password))<br>                                            .get_result(conn)?;</pre><pre>                    return Ok(user.into());<br>                }<br>            }</pre><pre>            Err(AuthError::AuthenticationError(String::from(&quot;Invalid confirmation&quot;)))<br>        })<br>}</pre><p>In create_account(), we terminate the request if the user is signed in, create a user account, sign the user in if the account creation was successful and return a response.</p><p>The create_user() support function parses the id as a UUID, queries the confirmation record and if found, creates and returns a user record.</p><p>Before we move on, we have some housecleaning to do.</p><p>In errors.rs, change plain_text and html_text to:</p><pre>let html_text = format!(<br>      &quot;Please click on the link below to complete registration. &lt;br/&gt;<br>       &lt;a href=\&quot;{domain}/register/{id}\&quot;&gt;Complete registration&lt;/a&gt; &lt;br/&gt;<br>      This link expires on &lt;strong&gt;{expires}&lt;/strong&gt;&quot;,<br>      domain=domain_url,<br>      id=confirmation.id,<br>      expires=expires<br>  );<br>  let plain_text = format!(<br>      &quot;Please visit the link below to complete registration:\n<br>      {domain}/register/{id}\n<br>      This link expires on {expires}.&quot;,<br>      domain=domain_url,<br>      id=confirmation.id,<br>      expires=expires<br>  );</pre><p>In main.rs, delete .allowed_origin(&quot;*&quot;) and add OPTIONS to the list of allowed headers in the CORs configuration.</p><h3>Allow password creation from a browser</h3><p>Create a new template templates/pages/password.hbs:</p><pre>{{#&gt; layouts/base title = &quot;Auth Service | Set password&quot; }}</pre><pre>  {{#if error.is_some() }}<br>  {{&gt; includes/message success = false, message = error.as_ref().unwrap() }}<br>  {{/if}}</pre><pre>  &lt;div&gt;<br>    &lt;h2 class=&quot;mt-6 text-center text-3xl leading-9 font-extrabold text-gray-900&quot;&gt;<br>      Complete account creation<br>    &lt;/h2&gt;<br>  &lt;/div&gt;<br>  <br>  &lt;form class=&quot;mt-8&quot; action=&quot;/register2/{{ path_id }}&quot; method=&quot;POST&quot;&gt;<br>    &lt;div class=&quot;rounded-md shadow-sm&quot;&gt;<br>      &lt;div&gt;<br>        &lt;input <br>          aria-label=&quot;Email address&quot; <br>          type=&quot;email&quot; <br>          disabled<br>          readonly<br>          value=&quot;{{ email }}&quot; <br>          class=&quot;appearance-none rounded-none relative block w-full px-3 py-2 border border-gray-300 placeholder-gray-500 text-gray-900 rounded-t-md focus:outline-none focus:shadow-outline-blue focus:border-blue-300 focus:z-10 sm:text-sm sm:leading-5&quot; <br>        /&gt;<br>      &lt;/div&gt;</pre><pre>      &lt;div class=&quot;-mt-px&quot;&gt;<br>        &lt;input aria-label=&quot;Password&quot; name=&quot;password&quot; type=&quot;password&quot; required class=&quot;appearance-none rounded-none relative block w-full px-3 py-2 border border-gray-300 placeholder-gray-500 text-gray-900 rounded-b-md focus:outline-none focus:shadow-outline-blue focus:border-blue-300 focus:z-10 sm:text-sm sm:leading-5&quot; placeholder=&quot;Password&quot; /&gt;<br>      &lt;/div&gt; <br>    &lt;/div&gt;</pre><pre>    &lt;div class=&quot;mt-6&quot;&gt;<br>      &lt;button type=&quot;submit&quot; class=&quot;group relative w-full flex justify-center py-2 px-4 border border-transparent text-sm leading-5 font-medium rounded-md text-white bg-indigo-600 hover:bg-indigo-500 focus:outline-none focus:border-indigo-700 focus:shadow-outline-indigo active:bg-indigo-700 transition duration-150 ease-in-out&quot;&gt;<br>        &lt;span class=&quot;absolute left-0 inset-y-0 flex items-center pl-3&quot;&gt;<br>          &lt;svg class=&quot;h-5 w-5 text-indigo-500 group-hover:text-indigo-400 transition ease-in-out duration-150&quot; fill=&quot;currentColor&quot; viewBox=&quot;0 0 20 20&quot;&gt;<br>            &lt;path fill-rule=&quot;evenodd&quot; d=&quot;M5 9V7a5 5 0 0110 0v2a2 2 0 012 2v5a2 2 0 01-2 2H5a2 2 0 01-2-2v-5a2 2 0 012-2zm8-2v2H7V7a3 3 0 016 0z&quot; clip-rule=&quot;evenodd&quot; /&gt;<br>          &lt;/svg&gt;<br>        &lt;/span&gt;<br>        Create password<br>      &lt;/button&gt;<br>    &lt;/div&gt;<br>  &lt;/form&gt;<br>  <br>{{~/layouts/base }}</pre><p>We then add a struct for the above template in src/templates.rs:</p><pre>// src/templates.rs<br>// ...</pre><pre>#[derive(Template)]<br>#[template(path = &quot;pages/password.hbs&quot;)]<br>pub struct Password {<br>    pub email: String,<br>    pub path_id: String,<br>    pub error: Option&lt;String&gt;<br>}</pre><p>In main.rs, we update our route specification to include routes for setting password through a browser:</p><pre>// ...<br>web::scope(&quot;/&quot;)<br>                    .service(<br>                        web::resource(&quot;/register&quot;)<br>                            .route(web::get().to(register_handler::show_confirmation_form))<br>                            .route(web::post().to(register_handler::send_confirmation)),<br>                    )<br>                    .service(<br>                        web::resource(&quot;/register/{path_id}&quot;)<br>                            .route(web::get().to(password_handler::show_password_form))<br>                            .route(web::post().to(password_handler::create_account)),<br>                    )<br>                    .route(&quot;/register2/{path_id}&quot;, web::post().to(password_handler::create_account_for_browser))<br>                    .route(&quot;/register2&quot;, web::post().to(register_handler::send_confirmation_for_browser)),</pre><p>In src/password_handler.rs, we add the corresponding route handlers:</p><pre>// src/password_handler.rs<br>use actix_web::{/*...,*/ http::header::LOCATION};<br>use uuid::Uuid;<br>use yarte::Template;<br>use crate::{<br>    // ...<br>    templates::Password,<br>    utils::{/*...,*/ to_home}<br>};<br>// ...<br>pub async fn show_password_form(session: Session, <br>                                path_id: web::Path&lt;String&gt;,<br>                                pool: web::Data&lt;Pool&gt;) -&gt; Result&lt;HttpResponse, AuthError&gt; {<br>    if is_signed_in(&amp;session) {<br>        Ok(to_home())<br>    } else {<br>        let id_str = path_id.into_inner();</pre><pre>        match get_invitation(&amp;id_str, &amp;pool) {<br>            Ok(Confirmation { email, .. }) =&gt; {<br>                let t = Password { path_id: id_str, email, error: None };</pre><pre>                Ok(HttpResponse::Ok().content_type(&quot;text/html; charset=utf-8&quot;).body(t.call().unwrap()))<br>            },<br>            Err(_) =&gt; Ok(HttpResponse::MovedPermanently().header(LOCATION, &quot;/register&quot;).finish()),<br>        }<br>    }<br>}</pre><pre>pub async fn create_account_for_browser(path_id: web::Path&lt;String&gt;,<br>                                        data: web::Form&lt;PasswordData&gt;,<br>                                        session: Session,<br>                                        pool: web::Data&lt;Pool&gt;) -&gt; Result&lt;HttpResponse, AuthError&gt; {<br>    let id_str = path_id.into_inner();<br>    let id_str2 = String::from(id_str.as_str());<br>    let result = web::block(move || create_user(&amp;id_str, &amp;data.into_inner().password, &amp;pool)).await;</pre><pre>    match result {<br>        Ok(user) =&gt; {<br>            set_current_user(&amp;session, &amp;user);</pre><pre>            Ok(to_home())<br>        },<br>        Err(_) =&gt; {<br>            let t = Password { <br>                path_id: id_str2, <br>                email: String::from(&quot;unknown@email.com&quot;), <br>                error: Some(String::from(&quot;Invalid/expired confirmation id&quot;))<br>            };</pre><pre>            Ok(HttpResponse::Ok().content_type(&quot;text/html; charset=utf-8&quot;).body(t.call().unwrap()))<br>        },<br>    }<br>}<br></pre><pre>fn get_invitation(path_id: &amp;str, pool: &amp;web::Data&lt;Pool&gt;) -&gt; Result&lt;Confirmation, AuthError&gt; {<br>    let path_uuid = Uuid::parse_str(path_id)?;</pre><pre>    if let Ok(record) = confirmations.find(path_uuid).get_result::&lt;Confirmation&gt;(&amp;pool.get().unwrap()) {<br>        Ok(record)<br>    } else {<br>        Err(AuthError::AuthenticationError(String::from(&quot;Invalid confirmation&quot;)))<br>    }<br>}<br>//...</pre><p>In show_password_form() we redirect the user to their home page if they&#39;re signed in. We then try to find the supplied confirmation id; if found we render a password, else we redirect the user to register page.</p><p>In create_account_for_browser() we create the user account. If we succeed, we set the current user in the session and redirect to their home page. If anything goes wrong, we re-render the password form.</p><p>For some reason, CookieSession cannot set cookies on my test browsers (Chrome and Firefox), though curl works ok. I noticed that RedisSession does not have that problem, so we&#39;re switching.</p><p>Add actix-redis = { version = &quot;0.8.0&quot;, features = [&quot;web&quot;] } to your dependencies in Cargo.toml.</p><p>Modify the cookie setup in main.rs:</p><pre>// src/main.rs<br>// ...<br></pre><pre>#[actix_rt::main]<br>async fn main() -&gt; std::io::Result&lt;()&gt; {<br>    //...<br>    use actix_redis::RedisSession;</pre><pre>    // Start http server<br>    HttpServer::new(move || {<br>        App::new()<br>            // ...<br>            // Enable sessions<br>            .wrap(RedisSession::new(&quot;127.0.0.1:6379&quot;, &amp;[0; 32]))<br>            // ...<br>    })<br>    // ...<br>}</pre><p>With that, our sessions should work without hiccups.</p><h3>Showing the current user</h3><p>After successfully signing in from a browser, you notice that it redirects to a non-existent home page. Let’s fix that.</p><p>We’ll be using the same route handler for API and browser requests. In main.rs, we register our new modules as well as the route handler that will return the currently signed in user or render the user&#39;s home page depending on the nature of the request.</p><pre>// src/main.rs<br>// ...</pre><pre>mod auth_handler;<br>// ...<br></pre><pre>#[actix_rt::main]<br>async fn main() -&gt; std::io::Result&lt;()&gt; {<br>    // ...</pre><pre>    // Start http server<br>    HttpServer::new(move || {<br>        App::new()<br>            // ...<br>            // Routes<br>            .service(<br>                web::scope(&quot;/&quot;)<br>                    // ...<br>                    .route(&quot;/me&quot;, web::get().to(auth_handler::me)),<br>    })<br>    .bind(format!(&quot;{}:{}&quot;, vars::domain(), vars::port()))?<br>    .run()<br>    .await<br>}</pre><p>Next, we’ll create the template that will be rendered to the browser. Modify src/templates.rs:</p><pre>// src/templates.rs<br>// ...</pre><pre>use crate::models::SessionUser;<br>// ...</pre><pre>#[derive(Template)]<br>#[template(path = &quot;pages/me.hbs&quot;)]<br>pub struct Me {<br>    pub user: SessionUser,<br>}</pre><p>Create the template file that will be rendered, templates/pages/me.hbs:</p><pre>&lt;!-- templates/pages/me.hbs --&gt;<br>{{#&gt; layouts/base title = &quot;Auth Service | User page&quot; }}<br>  &lt;div&gt;<br>    &lt;h2 class=&quot;mt-6 text-center text-3xl leading-9 font-extrabold text-gray-900&quot;&gt;<br>      Your email: {{ user.email }}<br>    &lt;/h2&gt;<br>  &lt;/div&gt;<br>  &lt;p class=&quot;mt-6 text-center leading-9&quot;&gt;<br>    &lt;a class=&quot;underline&quot; href=&quot;/signout&quot;&gt;Sign out →&lt;/a&gt;<br>  &lt;/p&gt;</pre><pre>{{~/layouts/base }}</pre><p>Create src/auth_handler.rs if you haven&#39;t already and add the route handler:</p><pre>// src/auth_handler.rs<br>use actix_session::Session;<br>use actix_web::{<br>    http::header::LOCATION,<br>    HttpRequest,<br>    HttpResponse,<br>    web<br>};<br>use diesel::prelude::*;<br>use serde::Deserialize;<br>use yarte::Template;</pre><pre>use crate::{<br>    models::{Pool, SessionUser, User},<br>    errors::AuthError,<br>    utils::{is_json_request, get_current_user, is_signed_in, set_current_user, to_home, verify}, <br>    templates::Me<br>};</pre><pre>pub async fn me(session: Session, req: HttpRequest) -&gt; HttpResponse {<br>    let user_result = dbg!(get_current_user(&amp;session));</pre><pre>    match is_json_request(&amp;req) {<br>        true =&gt; {<br>            user_result.map_or(HttpResponse::Unauthorized().json(&quot;Unauthorized&quot;), |user| HttpResponse::Ok().json(user))<br>        },<br>        false =&gt; {<br>            user_result.map_or(<br>                HttpResponse::MovedPermanently().header(LOCATION, &quot;/signin&quot;).finish(), <br>                |user| {<br>                    let t = Me { user };<br>            <br>                    HttpResponse::Ok().content_type(&quot;text/html; charset=utf-8&quot;).body(t.call().unwrap())<br>                }<br>            )<br>        }<br>    }<br>}</pre><p>Inside the handler, we first check if this is an API request by calling is_json_request(). If it is, we send back the user record if the user is signed in. Otherwise, we send back a 401 error response.</p><p>For browser requests we redirect to the sign in page if the user is not signed in. If the user is signed in, we render the user’s home page.</p><p>Oh, and the dbg! macro is to print out the contents of the variable to the console.</p><h3>Signing out</h3><p>First we register the handlers in main.rs:</p><pre>//src/main.rs<br>//...</pre><pre>#[actix_rt::main]<br>async fn main() -&gt; std::io::Result&lt;()&gt; {<br>    //...</pre><pre>    // Start http server<br>    HttpServer::new(move || {<br>        App::new()<br>            //...<br>            // Routes<br>            .service(<br>                web::scope(&quot;/&quot;)<br>                    //...<br>                    .service(<br>                        web::resource(&quot;/signout&quot;)<br>                            .route(web::get().to(auth_handler::sign_out))<br>                            .route(web::delete().to(auth_handler::sign_out)),<br>                    ),<br>            )<br>    })<br>    // ...<br>}</pre><p>In auth_handler::sign_out(), we clear the session and redirect to the sign in page for browser requests or return a No Content response for API requests.</p><pre>// src/auth_handler.rs<br>// ...</pre><pre>pub async fn sign_out(session: Session, req: HttpRequest) -&gt; HttpResponse {<br>    session.clear();<br>    <br>    match is_json_request(&amp;req) {<br>        true =&gt; HttpResponse::NoContent().finish(),<br>        false =&gt; HttpResponse::MovedPermanently().header(LOCATION, &quot;/signin&quot;).finish(),<br>    }<br>}</pre><h3>Signing in via API</h3><p>We first register the route handler in main.rs:</p><pre>// src/main.rs<br>// ...</pre><pre>#[actix_rt::main]<br>async fn main() -&gt; std::io::Result&lt;()&gt; {<br>    // ...</pre><pre>    // Start http server<br>    HttpServer::new(move || {<br>        App::new()<br>            // ...<br>            // Routes<br>            .service(<br>                web::scope(&quot;/&quot;)<br>                    // ...<br>                    .service(<br>                        web::resource(&quot;/signin&quot;)<br>                            .route(web::post().to(auth_handler::sign_in)),<br>                    ),<br>            )<br>    })<br>    // ...<br>}</pre><p>We then implement the handler we’ve registered in src/auth_handler.rs:</p><pre>// src/auth_handler.rs<br>// ...</pre><pre>#[derive(Debug, Deserialize)]<br>pub struct AuthData {<br>    pub email: String,<br>    pub password: String,<br>}</pre><pre>pub async fn sign_in(data: web::Json&lt;AuthData&gt;, <br>                  session: Session, <br>                  req: HttpRequest,<br>                  pool: web::Data&lt;Pool&gt;) -&gt; Result&lt;HttpResponse, AuthError&gt; {<br>    match is_signed_in(&amp;session) {<br>        true =&gt; {<br>            let response = get_current_user(&amp;session).map(|user| HttpResponse::Ok().json(user)).unwrap();</pre><pre>            Ok(response)<br>        },<br>        false =&gt; handle_sign_in(data.into_inner(), &amp;session, &amp;req, &amp;pool)<br>    }<br>}</pre><pre>fn handle_sign_in(data: AuthData, <br>                session: &amp;Session, <br>                req: &amp;HttpRequest,<br>                pool: &amp;web::Data&lt;Pool&gt;) -&gt; Result&lt;HttpResponse, AuthError&gt; {<br>    let result = find_user(data, pool);<br>    let is_json = is_json_request(req);</pre><pre>    match result {<br>        Ok(user) =&gt; {<br>            set_current_user(&amp;session, &amp;user);</pre><pre>            if is_json {<br>                Ok(HttpResponse::Ok().json(user))<br>            } else {<br>                Ok(to_home())<br>            }<br>        },<br>        Err(err) =&gt; {<br>            if is_json {<br>                Ok(HttpResponse::Unauthorized().json(err.to_string()))<br>            } else {<br>                let t = SignIn { error: Some(err.to_string()) };<br>    <br>                Ok(HttpResponse::Ok().content_type(&quot;text/html; charset=utf-8&quot;).body(t.call().unwrap()))<br>            }<br>        },<br>    }<br>}</pre><pre>fn find_user(data: AuthData, pool: &amp;web::Data&lt;Pool&gt;) -&gt; Result&lt;SessionUser, AuthError&gt; {<br>    use crate::schema::users::dsl::{email, users};<br>    <br>    let mut items = users<br>        .filter(email.eq(&amp;data.email))<br>        .load::&lt;User&gt;(&amp;pool.get().unwrap())?;</pre><pre>    if let Some(user) = items.pop() {<br>        if let Ok(matching) = verify(&amp;user.hash, &amp;data.password) {<br>            if matching {<br>                return Ok(user.into());<br>            }<br>        }<br>    }</pre><pre>    Err(AuthError::NotFound(String::from(&quot;User not found&quot;)))<br>}</pre><p>As usual, we first check if the user is signed in and return the user’s record. We’ve abstracted the bulk of the procedure into handle_sign_in() because we want to use it for browser sign in as well.</p><p>In handle_sign_in(), we call find_user() to retrieve the user record from the database if it exists and based on that create a session and return the user record or an error.</p><h3>Signing in from a browser</h3><p>We want to show a form when the user visits /signin and run the sign in process when the form is submitted to /signin2.</p><p>Since we’ve abstracted the sign in process into a private function let’s add the browser handlers in src/auth_handler.rs:</p><pre>// src/auth_handler.rs<br>// ...<br>use crate::{<br>    // ...<br>    templates::{SignIn, Me}<br>};</pre><pre>// ...</pre><pre>pub async fn show_sign_in_form(session: Session) -&gt; Result&lt;HttpResponse, AuthError&gt; {<br>    match is_signed_in(&amp;session) {<br>        true =&gt; Ok(to_home()),<br>        false =&gt; {<br>            let t = SignIn { error: None };</pre><pre>            Ok(HttpResponse::Ok().content_type(&quot;text/html; charset=utf-8&quot;).body(t.call().unwrap()))<br>        }<br>    }<br>}</pre><pre>pub async fn sign_in_for_browser(data: web::Form&lt;AuthData&gt;, <br>                                session: Session, <br>                                req: HttpRequest,<br>                                pool: web::Data&lt;Pool&gt;) -&gt; Result&lt;HttpResponse, AuthError&gt; {<br>    handle_sign_in(data.into_inner(), &amp;session, &amp;req, &amp;pool)<br>}</pre><p>In src/templates.rs, we declare the sign in template:</p><pre>// src/templates.rs<br>// ...</pre><pre>#[derive(Template)]<br>#[template(path = &quot;pages/sign_in.hbs&quot;)]<br>pub struct SignIn {<br>    pub error: Option&lt;String&gt;,<br>}</pre><p>In our template pages directory, create sign_in.hbs and paste in:</p><pre>&lt;!--templates/pages/sign_in.hbs --&gt;<br>{{#&gt; layouts/base title = &quot;Auth Service | Sign in&quot; }}</pre><pre>  {{#if error.is_some() }}<br>  {{&gt; includes/message success = false, message = error.as_ref().unwrap() }}<br>  {{/if}}</pre><pre>  &lt;div&gt;<br>    &lt;h2 class=&quot;mt-6 text-center text-3xl leading-9 font-extrabold text-gray-900&quot;&gt;<br>      Sign in<br>    &lt;/h2&gt;<br>  &lt;/div&gt;<br>  <br>  &lt;form class=&quot;mt-8&quot; action=&quot;/signin2&quot; method=&quot;POST&quot;&gt;<br>    &lt;div class=&quot;rounded-md shadow-sm&quot;&gt;<br>      &lt;div&gt;<br>        &lt;input <br>          placeholder=&quot;Email address&quot; <br>          type=&quot;email&quot; <br>          name=&quot;email&quot;<br>          class=&quot;appearance-none rounded-none relative block w-full px-3 py-2 border border-gray-300 placeholder-gray-500 text-gray-900 rounded-t-md focus:outline-none focus:shadow-outline-blue focus:border-blue-300 focus:z-10 sm:text-sm sm:leading-5&quot; <br>        /&gt;<br>      &lt;/div&gt;</pre><pre>      &lt;div class=&quot;-mt-px&quot;&gt;<br>        &lt;input aria-label=&quot;Password&quot; name=&quot;password&quot; type=&quot;password&quot; required class=&quot;appearance-none rounded-none relative block w-full px-3 py-2 border border-gray-300 placeholder-gray-500 text-gray-900 rounded-b-md focus:outline-none focus:shadow-outline-blue focus:border-blue-300 focus:z-10 sm:text-sm sm:leading-5&quot; placeholder=&quot;Password&quot; /&gt;<br>      &lt;/div&gt; <br>    &lt;/div&gt;</pre><pre>    &lt;div class=&quot;mt-6&quot;&gt;<br>      &lt;button type=&quot;submit&quot; class=&quot;group relative w-full flex justify-center py-2 px-4 border border-transparent text-sm leading-5 font-medium rounded-md text-white bg-indigo-600 hover:bg-indigo-500 focus:outline-none focus:border-indigo-700 focus:shadow-outline-indigo active:bg-indigo-700 transition duration-150 ease-in-out&quot;&gt;<br>        &lt;span class=&quot;absolute left-0 inset-y-0 flex items-center pl-3&quot;&gt;<br>          &lt;svg class=&quot;h-5 w-5 text-indigo-500 group-hover:text-indigo-400 transition ease-in-out duration-150&quot; fill=&quot;currentColor&quot; viewBox=&quot;0 0 20 20&quot;&gt;<br>            &lt;path fill-rule=&quot;evenodd&quot; d=&quot;M5 9V7a5 5 0 0110 0v2a2 2 0 012 2v5a2 2 0 01-2 2H5a2 2 0 01-2-2v-5a2 2 0 012-2zm8-2v2H7V7a3 3 0 016 0z&quot; clip-rule=&quot;evenodd&quot; /&gt;<br>          &lt;/svg&gt;<br>        &lt;/span&gt;<br>        Sign in<br>      &lt;/button&gt;<br>    &lt;/div&gt;<br>  &lt;/form&gt;<br>  <br>{{~/layouts/base }}</pre><p>Finally, register the route handlers in main.rs:</p><pre>// src/main.rs<br>// ...<br></pre><pre>#[actix_rt::main]<br>async fn main() -&gt; std::io::Result&lt;()&gt; {<br>    // ...</pre><pre>    // Start http server<br>    HttpServer::new(move || {<br>        App::new()<br>            // ...<br>            // Routes<br>            .service(<br>                web::scope(&quot;/&quot;)<br>                    // ...<br>                    .service(<br>                        web::resource(&quot;/signin&quot;)<br>                            .route(web::get().to(auth_handler::show_sign_in_form))<br>                            .route(web::post().to(auth_handler::sign_in)),<br>                    )<br>                    .route(&quot;/signin2&quot;, web::post().to(auth_handler::sign_in_for_browser)),<br>            )<br>    })<br>    // ...<br>}</pre><p>With that, we should be able to sign in from a browser.</p><p>The complete source code can be seen on <a href="https://github.com/ukchukx/rust_auth_service">GitHub</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ee8116934d73" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/user-authentication-in-rust-ee8116934d73">User authentication in Rust</a> was originally published in <a href="https://medium.com/swlh">The Startup</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Sending emails with Rust]]></title>
            <link>https://medium.com/swlh/sending-emails-with-rust-162667ee40f6?source=rss-5114de41076a------2</link>
            <guid isPermaLink="false">https://medium.com/p/162667ee40f6</guid>
            <category><![CDATA[self-contained-services]]></category>
            <category><![CDATA[rust]]></category>
            <category><![CDATA[actix-web]]></category>
            <dc:creator><![CDATA[Uk Chukundah]]></dc:creator>
            <pubDate>Sat, 11 Apr 2020 18:02:10 GMT</pubDate>
            <atom:updated>2020-04-25T23:46:12.282Z</atom:updated>
            <content:encoded><![CDATA[<p>This is the second part of our exploratory series on creating a web service with Rust. Our exploration is broken down into distinct steps to make it easier for you to follow along:</p><ul><li><a href="https://medium.com/@ukchukx/55d0b0a848d">Setup</a>.</li><li>Sending a confirmation email (you are here).</li><li><a href="https://medium.com/@ukchukx/ee8116934d73">User account creation and authentication.</a></li></ul><p>In this article, we’ll be looking at sending a confirmation link to the user’s email address during the registration process.</p><h3>Sending a confirmation link via API</h3><p>Let’s attend to the API case first.</p><p>Create src/register_handler.rs and paste in the following:</p><pre>// src/register_handler.rs<br>use actix_web::{error::BlockingError, http, web, HttpResponse};<br>use actix_session::Session;<br>use diesel::prelude::*;<br>use serde::Deserialize;<br>use yarte::Template;</pre><pre>use crate::{<br>    email_service::send_confirmation_mail, <br>    errors::AuthError, <br>    models::{Confirmation, Pool},<br>    utils::is_signed_in<br>};<br></pre><pre>#[derive(Deserialize)]<br>pub struct RegisterData {<br>    pub email: String,<br>}</pre><pre>pub async fn send_confirmation(session: Session,<br>                              data: web::Json&lt;RegisterData&gt;,<br>                              pool: web::Data&lt;Pool&gt;) -&gt; Result&lt;HttpResponse, AuthError&gt; {<br>    if (is_signed_in(&amp;session)) {<br>      return Ok(HttpResponse::BadRequest().finish());<br>    }<br>            <br>    let result = web::block(move || create_confirmation(data.into_inner().email, &amp;pool)).await;</pre><pre>    match result {<br>        Ok(_) =&gt; Ok(HttpResponse::Ok().finish()),<br>        Err(err) =&gt; match err {<br>            BlockingError::Error(auth_error) =&gt; Err(auth_error),<br>            BlockingError::Canceled =&gt; Err(AuthError::GenericError(String::from(&quot;Could not complete the process&quot;))),<br>        },<br>    }<br>}<br></pre><pre>fn create_confirmation(email: String, pool: &amp;web::Data&lt;Pool&gt;) -&gt; Result&lt;(), AuthError&gt; {<br>    let confirmation = insert_record(email, pool)?;</pre><pre>    send_confirmation_mail(&amp;confirmation)<br>}</pre><pre>fn insert_record(email: String, pool: &amp;web::Data&lt;Pool&gt;) -&gt; Result&lt;Confirmation, AuthError&gt; {<br>    use crate::schema::confirmations::dsl::confirmations;</pre><pre>    let new_record : Confirmation = email.into();</pre><pre>    let inserted_record = diesel::insert_into(confirmations)<br>                                .values(&amp;new_record)<br>                                .get_result(&amp;pool.get().unwrap())?;</pre><pre>    Ok(inserted_record)<br>}</pre><p>send_confirmation is our route handler which we&#39;ll register in main.rs. It first checks if the user is signed in and if not, then calls create_confirmation which creates the database record and passes the record to the email service to send the confirmation email.</p><p>The email service is contained in src/email_service.rs:</p><pre>// src/email_service.rs<br>use lettre::{<br>  Email, <br>  SmtpClient, <br>  ClientSecurity, <br>  ClientTlsParameters,<br>  Transport, <br>  smtp::{<br>      ConnectionReuseParameters, <br>      authentication::{Credentials, Mechanism}<br>  }<br>};<br>use native_tls::{Protocol, TlsConnector};</pre><pre>use crate::{models::Confirmation, errors::AuthError, vars};<br></pre><pre>pub fn send_confirmation_mail(confirmation: &amp;Confirmation) -&gt; Result&lt;(), AuthError&gt; {<br>  let domain_url = vars::domain_url();<br>  let expires = confirmation.expires_at.format(&quot;%I:%M %p %A, %-d %B, %C%y&quot;).to_string();<br>  let html_text = format!(<br>      &quot;Please click on the link below to complete registration. &lt;br/&gt;<br>       &lt;a href=\&quot;{domain}/register?id={id}&amp;email={email}\&quot;&gt;Complete registration&lt;/a&gt; &lt;br/&gt;<br>      This link expires on &lt;strong&gt;{expires}&lt;/strong&gt;&quot;,<br>      domain=domain_url,<br>      id=confirmation.id,<br>      email=confirmation.email,<br>      expires=expires<br>  );<br>  let plain_text = format!(<br>      &quot;Please visit the link below to complete registration:\n<br>      {domain}/register.html?id={id}&amp;email={email}\n<br>      This link expires on {expires}.&quot;,<br>      domain=domain_url,<br>      id=confirmation.id,<br>      email=confirmation.email,<br>      expires=expires<br>  );</pre><pre>  let email = Email::builder()<br>                    .to(confirmation.email.clone())<br>                    .from((&quot;noreply@auth-service.com&quot;, vars::smtp_sender_name()))<br>                    .subject(&quot;Complete your registration on our one-of-a-kind Auth Service&quot;)<br>                    .text(plain_text)<br>                    .html(html_text)<br>                    .build()<br>                    .unwrap();</pre><pre>  let smtp_host = vars::smtp_host();<br>  let mut tls_builder = TlsConnector::builder();<br>  tls_builder.min_protocol_version(Some(Protocol::Tlsv10));<br>  let tls_parameters = ClientTlsParameters::new(smtp_host.clone(), tls_builder.build().unwrap());</pre><pre>  let mut mailer = SmtpClient::new((smtp_host.as_str(), vars::smtp_port()), ClientSecurity::Required(tls_parameters))<br>                              .unwrap()<br>                              .authentication_mechanism(Mechanism::Login)<br>                              .credentials(Credentials::new(vars::smtp_username(), vars::smtp_password()))<br>                              .connection_reuse(ConnectionReuseParameters::ReuseUnlimited)<br>                              .transport();</pre><pre>  let result = mailer.send(email);</pre><pre>  if result.is_ok() {<br>      println!(&quot;Email sent&quot;);<br>      <br>      Ok(())<br>  } else {<br>      println!(&quot;Could not send email: {:?}&quot;, result);</pre><pre>      Err(AuthError::ProcessError(String::from(&quot;Could not send confirmation email&quot;)))<br>  }<br>}</pre><p>Let’s also create src/utils.rs to house is_signed_in and other authentication utility functions:</p><pre>// src/utils.rs<br>use argonautica::{Hasher, Verifier};<br>use actix_session::Session;<br>use actix_web::{http::header::CONTENT_TYPE, HttpRequest};</pre><pre>use crate::{errors::AuthError, vars, models::SessionUser};<br></pre><pre>pub fn hash_password(password: &amp;str) -&gt; Result&lt;String, AuthError&gt; {<br>  Hasher::default()<br>      .with_password(password)<br>      .with_secret_key(vars::secret_key().as_str())<br>      .hash()<br>      .map_err(|_| AuthError::AuthenticationError(String::from(&quot;Could not hash password&quot;)))<br>}</pre><pre>pub fn verify(hash: &amp;str, password: &amp;str) -&gt; Result&lt;bool, AuthError&gt; {<br>  Verifier::default()<br>      .with_hash(hash)<br>      .with_password(password)<br>      .with_secret_key(vars::secret_key().as_str())<br>      .verify()<br>      .map_err(|_| AuthError::AuthenticationError(String::from(&quot;Could not verify password&quot;)))<br>}</pre><pre>pub fn is_json_request(req: &amp;HttpRequest) -&gt; bool {<br>    req<br>      .headers()<br>      .get(CONTENT_TYPE)<br>      .map_or(<br>        false,<br>        |header| header.to_str().map_or(false, |content_type| &quot;application/json&quot; == content_type)<br>      )<br>}</pre><pre>pub fn is_signed_in(session: &amp;Session) -&gt; bool {<br>  match get_current_user(session) {<br>      Ok(_) =&gt; true,<br>      _ =&gt; false,<br>  }<br>}</pre><pre>pub fn set_current_user(session: &amp;Session, user: &amp;SessionUser) -&gt; () {<br>    // serializing to string is alright for this case, <br>    // but binary would be preferred in production use-cases.<br>    session.set(&quot;user&quot;, serde_json::to_string(user).unwrap()).unwrap();<br>}</pre><pre>pub fn get_current_user(session: &amp;Session) -&gt; Result&lt;SessionUser, AuthError&gt; {<br>    let err = AuthError::AuthenticationError(String::from(&quot;Could not retrieve user from session&quot;));<br>    let session_result = session.get::&lt;String&gt;(&quot;user&quot;); // Returns Result&lt;Option&lt;String&gt;, Error&gt;</pre><pre>    if session_result.is_err() {<br>        return Err(err);<br>    }</pre><pre>    session_result<br>        .unwrap()<br>        .map_or(<br>          Err(err.clone()),<br>          |user_str| serde_json::from_str(&amp;user_str).or_else(|_| Err(err)) <br>        ) <br>}</pre><p>Then in src/errors.rs we make AuthError clonable, and add 2 more error types:</p><pre>// src/errors.rs<br>// ...</pre><pre>#[derive(Clone, Debug, Display)]<br>pub enum AuthError {<br>    // ...</pre><pre>    #[display(fmt = &quot;ProcessFailed: {}&quot;, _0)]<br>    ProcessError(String),</pre><pre>    #[display(fmt = &quot;AuthenticationError: {}&quot;, _0)]<br>    AuthenticationError(String),<br>}<br></pre><pre>impl ResponseError for AuthError {<br>    fn error_response(&amp;self) -&gt; HttpResponse {<br>        match self { <br>            // ...</pre><pre>            AuthError::ProcessError(ref message) =&gt; HttpResponse::InternalServerError().json(message),</pre><pre>            AuthError::AuthenticationError(ref message) =&gt; HttpResponse::Unauthorized().json(message),<br>        }<br>    }<br>}<br></pre><pre>// ...</pre><p>To tie everything together, we need to register our new modules and route handler in main.rs:</p><pre>// src/main.rs</pre><pre>// ...</pre><pre>mod email_service;<br>mod register_handler;<br>mod utils;<br></pre><pre>#[actix_rt::main]<br>async fn main() -&gt; std::io::Result&lt;()&gt; {<br>    // ...</pre><pre>    // Start http server<br>    HttpServer::new(move || {<br>        App::new()<br>            // ...<br>            .service(Files::new(&quot;/assets&quot;, &quot;./templates/assets&quot;))<br>            // Routes<br>            .service(<br>                web::scope(&quot;/&quot;)<br>                    .service(<br>                        web::resource(&quot;/register&quot;)<br>                            .route(web::post().to(register_handler::send_confirmation)),<br>                    ),<br>            )<br>    })<br>    // ...<br>}</pre><p>With the above changes, we can now send confirmation links to new email addresses.</p><h3>Sending a confirmation link from a browser</h3><p>Before writing our handlers, we need to setup the templates we’ll be working with.</p><p>First, create yarte.toml in the root directory:</p><pre># yarte.toml<br>[main]<br>dir = &quot;templates&quot;</pre><pre>[partials]<br>layouts = &quot;./layouts&quot;<br>includes = &quot;./includes&quot;</pre><p>In the templates directory, create 3 subdirectories: includes, layouts and pages. The contents of the supporting files are given below:</p><pre>&lt;!-- includes/head.hbs --&gt;<br>&lt;head&gt;<br>  &lt;meta charset=&quot;utf-8&quot;/&gt;<br>  &lt;title&gt;{{ title }}&lt;/title&gt;<br>  &lt;link rel=&quot;stylesheet&quot; href=&quot;/assets/css/tailwind-1.2.0.min.css&quot;&gt;<br>&lt;/head&gt;<br></pre><pre>&lt;!-- includes/message.hbs --&gt;<br>{{#if success }}<br>&lt;div class=&quot;bg-teal-100 border-t-4 border-teal-100 rounded-b text-teal-900 px-4 py-3 shadow-md&quot; role=&quot;alert&quot;&gt;<br>  &lt;div class=&quot;flex&quot;&gt;<br>    &lt;div class=&quot;py-1&quot;&gt;&lt;svg class=&quot;fill-current h-6 w-6 text-teal-500 mr-4&quot; xmlns=&quot;http://www.w3.org/2000/svg&quot; viewBox=&quot;0 0 20 20&quot;&gt;&lt;path d=&quot;M2.93 17.07A10 10 0 1 1 17.07 2.93 10 10 0 0 1 2.93 17.07zm12.73-1.41A8 8 0 1 0 4.34 4.34a8 8 0 0 0 11.32 11.32zM9 11V9h2v6H9v-4zm0-6h2v2H9V5z&quot;/&gt;&lt;/svg&gt;&lt;/div&gt;<br>    &lt;div&gt;<br>      &lt;p class=&quot;font-bold&quot;&gt;{{ message }}&lt;/p&gt;<br>    &lt;/div&gt;<br>  &lt;/div&gt;<br>&lt;/div&gt;<br>{{else}}<br>&lt;div class=&quot;bg-red-100 border-t-4 border-red-100 rounded-b text-red-900 px-4 py-3 shadow-md&quot; role=&quot;alert&quot;&gt;<br>  &lt;div class=&quot;flex&quot;&gt;<br>    &lt;div class=&quot;py-1&quot;&gt;&lt;svg class=&quot;fill-current h-6 w-6 text-red-500 mr-4&quot; xmlns=&quot;http://www.w3.org/2000/svg&quot; viewBox=&quot;0 0 20 20&quot;&gt;&lt;path d=&quot;M2.93 17.07A10 10 0 1 1 17.07 2.93 10 10 0 0 1 2.93 17.07zm12.73-1.41A8 8 0 1 0 4.34 4.34a8 8 0 0 0 11.32 11.32zM9 11V9h2v6H9v-4zm0-6h2v2H9V5z&quot;/&gt;&lt;/svg&gt;&lt;/div&gt;<br>    &lt;div&gt;<br>      &lt;p class=&quot;font-bold&quot;&gt;{{ message }}&lt;/p&gt;<br>    &lt;/div&gt;<br>  &lt;/div&gt;<br>&lt;/div&gt;<br>{{/if}}<br></pre><pre>&lt;!-- layouts/base.hbs --&gt;<br>&lt;!DOCTYPE html&gt;<br>&lt;html&gt;<br>  {{&gt; includes/head }}<br>  &lt;body&gt;<br>    &lt;div class=&quot;min-h-screen flex items-center justify-center bg-gray-50 py-12 px-4 sm:px-6 lg:px-8&quot;&gt;<br>      &lt;div class=&quot;max-w-md w-full&quot;&gt;<br>        {{&gt; @partial-block }}<br>      &lt;/div&gt;<br>    &lt;/div&gt;<br>  &lt;/body&gt;<br>&lt;/html&gt;</pre><p>Our first page, templates/pages/register.hbs contains the following template:</p><pre>{{#&gt; layouts/base title = &quot;Auth Service | Register&quot; }}</pre><pre>  {{#if sent }}<br>  {{&gt; includes/message success = sent, message = &quot;A confirmation email has been sent to your mailbox&quot; }}<br>  {{else if error.is_some() }}<br>  {{&gt; includes/message success = sent, message = error.as_ref().unwrap() }}<br>  {{/if}}</pre><pre>  &lt;div&gt;<br>    &lt;h2 class=&quot;mt-6 text-center text-3xl leading-9 font-extrabold text-gray-900&quot;&gt;<br>      Create an account<br>    &lt;/h2&gt;<br>  &lt;/div&gt;</pre><pre>  &lt;form class=&quot;mt-8&quot; action=&quot;/register2&quot; method=&quot;POST&quot;&gt;<br>    &lt;div class=&quot;rounded-md shadow-sm&quot;&gt;<br>      &lt;div&gt;<br>        &lt;input <br>          aria-label=&quot;Email address&quot; <br>          name=&quot;email&quot; <br>          type=&quot;email&quot; <br>          required <br>          class=&quot;appearance-none rounded-none relative block w-full px-3 py-2 border border-gray-300 placeholder-gray-500 text-gray-900 rounded-t-md focus:outline-none focus:shadow-outline-blue focus:border-blue-300 focus:z-10 sm:text-sm sm:leading-5&quot; <br>          placeholder=&quot;Email address&quot; /&gt;<br>      &lt;/div&gt;<br>    &lt;/div&gt;</pre><pre>    &lt;div class=&quot;mt-6&quot;&gt;<br>      &lt;button type=&quot;submit&quot; class=&quot;group relative w-full flex justify-center py-2 px-4 border border-transparent text-sm leading-5 font-medium rounded-md text-white bg-indigo-600 hover:bg-indigo-500 focus:outline-none focus:border-indigo-700 focus:shadow-outline-indigo active:bg-indigo-700 transition duration-150 ease-in-out&quot;&gt;<br>        &lt;span class=&quot;absolute left-0 inset-y-0 flex items-center pl-3&quot;&gt;<br>          &lt;svg class=&quot;h-5 w-5 text-indigo-500 group-hover:text-indigo-400 transition ease-in-out duration-150&quot; fill=&quot;currentColor&quot; viewBox=&quot;0 0 20 20&quot;&gt;<br>            &lt;path fill-rule=&quot;evenodd&quot; d=&quot;M5 9V7a5 5 0 0110 0v2a2 2 0 012 2v5a2 2 0 01-2 2H5a2 2 0 01-2-2v-5a2 2 0 012-2zm8-2v2H7V7a3 3 0 016 0z&quot; clip-rule=&quot;evenodd&quot; /&gt;<br>          &lt;/svg&gt;<br>        &lt;/span&gt;<br>        Send confirmation link<br>      &lt;/button&gt;<br>    &lt;/div&gt;<br>  &lt;/form&gt;<br>{{~/layouts/base }}</pre><p>We’re POSTing to /register2 as I do not know how to use the same route for handling web::Form&lt;RegisterData&gt; and web::Json&lt;RegisterData&gt; or if it is even possible. Now we&#39;ve created the HTML templates we&#39;ll need, let&#39;s write our handlers.</p><p>Create src/templates.rs and paste in:</p><pre>use yarte::Template;</pre><pre>#[derive(Template)]<br>#[template(path = &quot;pages/register.hbs&quot;)]<br>pub struct Register {<br>    pub sent: bool,<br>    pub error: Option&lt;String&gt;<br>}</pre><p>When a user visits /register in the browser, we want to show the registration form and send a confirmation code when the form is submitted.</p><p>Let’s start from main.rs and work down.</p><pre>// src/main.rs<br>// ...<br>mod templates;<br></pre><pre>#[actix_rt::main]<br>async fn main() -&gt; std::io::Result&lt;()&gt; {<br>    // ...</pre><pre>    // Start http server<br>    HttpServer::new(move || {<br>        App::new()<br>            // ...<br>            // Routes<br>            .service(<br>                web::scope(&quot;/&quot;)<br>                    .service(<br>                        web::resource(&quot;/register&quot;)<br>                            .route(web::get().to(register_handler::show_confirmation_form))<br>                            .route(web::post().to(register_handler::send_confirmation)),<br>                    )<br>                    .route(&quot;/register2&quot;, web::post().to(register_handler::send_confirmation_for_browser)),<br>            )<br>    })<br>    // ...<br>}</pre><p>We then update src/register_handler.rs with the new handlers:</p><pre>// src/register_handler.rs<br>// ...</pre><pre>use crate::{<br>    email_service::send_confirmation_mail, <br>    errors::AuthError, <br>    models::{Confirmation, Pool},<br>    templates::Register,<br>    utils::{is_signed_in, to_home}<br>};<br>// ...</pre><pre>pub async fn show_confirmation_form(session: Session) -&gt; Result&lt;HttpResponse, AuthError&gt; {<br>    if is_signed_in(&amp;session) {<br>        Ok(to_home())<br>    } else {<br>        let template = Register { sent: false, error: None };</pre><pre>        Ok(HttpResponse::Ok().content_type(&quot;text/html; charset=utf-8&quot;).body(template.call().unwrap()))<br>    }<br>}</pre><pre>pub async fn send_confirmation_for_browser(data: web::Form&lt;RegisterData&gt;,<br>                                          pool: web::Data&lt;Pool&gt;) -&gt; Result&lt;HttpResponse, AuthError&gt; {<br>    let result = web::block(move || create_confirmation(data.into_inner().email, &amp;pool)).await;<br>    let template = match result {<br>        Ok(_) =&gt; Register { sent: true, error: None },<br>        Err(err) =&gt; match err {<br>            BlockingError::Error(auth_error) =&gt; Register { sent: false, error: Some(auth_error.to_string()) },<br>            BlockingError::Canceled =&gt; {<br>                Register { sent: false, error: Some(String::from(&quot;Could not complete the process&quot;)) }<br>            }<br>        },<br>    };</pre><pre>    Ok(HttpResponse::Ok().content_type(&quot;text/html; charset=utf-8&quot;).body(template.call().unwrap()))<br>}<br></pre><pre>// ...</pre><p>When a user visits /register, we first check if the user is signed in in show_confirmation_form() and redirect them to their home page if they are. Otherwise, we render the form.</p><p>When the form is submitted to send_confirmation_for_browser(), we do the same thing we did in the API handler. The difference is we re-render the form with the result of the process displayed in an alert instead of returning a JSON response.</p><p>To complete this part, we need to implement the to_home() utility function for redirecting users to their home page.</p><pre>// src/utils.rs<br>// ...<br>use actix_web::{<br>  http::header::{CONTENT_TYPE, LOCATION}, <br>  HttpRequest, <br>  HttpResponse<br>};</pre><pre>// ...</pre><pre>pub fn to_home() -&gt; HttpResponse {<br>  HttpResponse::Found().header(LOCATION, &quot;/me&quot;).finish()<br>}</pre><p>Now we’ve successfully sent a confirmation link to the user. When they follow the link (browser) or send the id to the assigned route (API), we need to complete the <a href="https://medium.com/@ukchukx/ee8116934d73">creation of the user acount</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=162667ee40f6" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/sending-emails-with-rust-162667ee40f6">Sending emails with Rust</a> was originally published in <a href="https://medium.com/swlh">The Startup</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Creating a web and API authentication service in Rust]]></title>
            <link>https://medium.com/swlh/creating-a-web-and-api-authentication-service-in-rust-55d0b0a848d?source=rss-5114de41076a------2</link>
            <guid isPermaLink="false">https://medium.com/p/55d0b0a848d</guid>
            <category><![CDATA[self-contained-services]]></category>
            <category><![CDATA[actix-web]]></category>
            <category><![CDATA[rust]]></category>
            <dc:creator><![CDATA[Uk Chukundah]]></dc:creator>
            <pubDate>Sat, 11 Apr 2020 18:00:18 GMT</pubDate>
            <atom:updated>2020-04-24T23:27:32.794Z</atom:updated>
            <content:encoded><![CDATA[<p>To improve my understanding of Rust, I’m going to be creating an authentication service that can be used via a browser or an API. This is complex enough to be useful while being simple enough for me not to get lost. I also want to extend the concepts covered <a href="https://gill.net.in/posts/auth-microservice-rust-actix-web1.0-diesel-complete-tutorial/">here</a> (which only deals with the API part).</p><blockquote><em>Disclaimer: I’ve been learning Rust for all of 2 months now so the code may not be idiomatic or elegant…but it works, which is the most important thing, after all. Also, some of what I’ll write might not be accurate since I’m still getting the hang of the Rust way of doing things.</em></blockquote><p>Our service will allow people to register, verify their email addresses, sign in and sign out.</p><p>Wait a minute! Where’s password recovery, 2-factor authentication, social login and other features of a production-grade self-respecting authentication service, you ask? Well, hold your horses. We’re only trying to improve our familiarity with Rust. We’re not trying to build the next SaaS unicorn.</p><p>I’ll be assuming you’ve already set up your system for creating Rust apps. If you haven’t, see how to <a href="https://www.rust-lang.org/tools/install">here</a>. Our exploration is broken down into distinct steps to make it easier for you to follow along:</p><ul><li>Setup (you are here).</li><li><a href="https://medium.com/@ukchukx/162667ee40f6">Sending a confirmation email</a>.</li><li><a href="https://medium.com/@ukchukx/ee8116934d73">User account creation and authentication</a>.</li></ul><h3>Creating the app</h3><p>We’ll be using <a href="https://github.com/rust-lang/cargo">Cargo</a>, which is to Rust what NPM is to Javascript, to help us along.</p><pre>$ cargo new auth_service<br>$ cd auth_service</pre><p>The first command creates the app while the second changes to the app directory.</p><p>Next, we’ll install cargo-watch to recompile and run our app when a file changes:</p><pre>$ cargo install cargo-watch</pre><p>Run the command below to start the app. You should see the world-famous “Hello, world!” output.</p><pre>$ cargo-watch -x run</pre><p>Add the following dependencies in Cargo.toml file:</p><pre>[dependencies]<br>actix-files = &quot;0.2.1&quot;<br>actix-rt = &quot;1.0&quot;<br>actix-session = &quot;0.3&quot;<br>actix-web = &quot;2.0&quot;<br>argonautica = &quot;0.2.0&quot;<br>chrono = { version = &quot;0.4.11&quot;, features = [&quot;serde&quot;] }<br>derive_more = &quot;0.99.5&quot;<br>diesel = { version = &quot;1.4.4&quot;, features = [&quot;postgres&quot;, &quot;uuidv07&quot;, &quot;r2d2&quot;, &quot;chrono&quot;] }<br>dotenv = &quot;0.15.0&quot;<br>env_logger = &quot;0.7.1&quot;<br>lettre = { git = &quot;https://github.com/lettre/lettre&quot; }<br>native-tls = &quot;0.2.4&quot;<br>r2d2 = &quot;0.8.8&quot;<br>serde = { version = &quot;1.0&quot;, features = [&quot;derive&quot;] }<br>serde_json = &quot;1.0&quot;<br>uuid = { version = &quot;0.8&quot;, features = [&quot;serde&quot;, &quot;v4&quot;] }<br>yarte = { version = &quot;0.7&quot;, features = [&quot;with-actix-web&quot;]  }</pre><pre>[build-dependencies]<br>yarte = { version = &quot;0.7&quot;, features = [&quot;with-actix-web&quot;]  }</pre><p>We’ll be using:</p><ul><li>PostgreSQL as our database.</li><li>d<a href="http://diesel.rs/">iesel</a> as our ORM.</li><li>a<a href="https://actix.rs/">ctix-web</a> as our webserver.</li><li><a href="https://crates.io/crates/actix-files">actix-files</a> to serve static files (we’ll use it to serve our CSS file).</li><li><a href="https://crates.io/crates/actix-session">actix-session</a> for…do I really need to explain this one?</li><li>y<a href="https://github.com/botika/yarte">arte</a> for compiling HTML templates (currently the fastest of the bunch).</li><li><a href="https://crates.io/crates/serde">serde</a> for JSON serialization (which I always call Sade for some reason).</li><li><a href="https://crates.io/crates/r2d2">r2d2</a> for (database) connection pooling.</li><li><a href="https://crates.io/crates/dotenv">dotenv</a> for reading variables from .env files.</li><li><a href="https://crates.io/crates/lettre">lettre</a> for sending e-mails.</li><li><a href="https://crates.io/crates/argonautica">argonautica</a> for password hashing.</li></ul><p>Create a .env file in the project directory with the following keys in KEY=value format:</p><ul><li>DATABASE_URL which will contain the value postgres://&lt;user&gt;:&lt;password&gt;@&lt;host&gt;/auth_service.</li><li>DOMAIN. I use 0.0.0.0.</li><li>PORT. I use 3000.</li><li>HOST. I use <a href="http://localhost:3000.">http://localhost:3000.</a></li><li>SECRET_KEY.</li><li>SMTP_SENDER_NAME, SMTP_USERNAME, SMTP_PASSWORD, SMTP_HOST and SMTP_PORT. I use <a href="https://mailtrap.io/">Mailtrap</a> to test email in development. You can use any SMTP provider you choose.</li></ul><p>Follow the instructions <a href="https://crates.io/crates/diesel_cli">here</a> to install <a href="https://crates.io/crates/diesel_cli">diesel_cli</a>.</p><h3>Create database and start the webserver</h3><p>Create a directory for the <a href="https://unpkg.com/tailwindcss@%5E1.0/dist/tailwind.min.css">Tailwind</a> CSS file we’ll be using for the templates:</p><pre>$ mkdir -p templates/assets/css</pre><p>Then put the downloaded CSS file there. Note that this is not the recommended way of using Tailwind, but it’s sufficient for this example.</p><p>I’m a fan of doing things in one place and using it everywhere else. Let’s create a file src/vars.rs that will supply our environment variables to the rest of the app. Paste this code in:</p><pre>use dotenv::dotenv;</pre><pre>use std::env::var;<br></pre><pre>pub fn database_url() -&gt; String {<br>  dotenv().ok();</pre><pre>  var(&quot;DATABASE_URL&quot;).expect(&quot;DATABASE_URL is not set&quot;)<br>}</pre><pre>pub fn secret_key() -&gt; String {<br>  dotenv().ok();</pre><pre>  var(&quot;SECRET_KEY&quot;).unwrap_or_else(|_| &quot;0123&quot;.repeat(8))<br>}</pre><pre>pub fn domain() -&gt; String {<br>  dotenv().ok();</pre><pre>  var(&quot;DOMAIN&quot;).unwrap_or_else(|_| &quot;localhost&quot;.to_string())<br>}</pre><pre>pub fn port() -&gt; u16 {<br>  dotenv().ok();</pre><pre>  var(&quot;PORT&quot;).expect(&quot;PORT is not set&quot;).parse::&lt;u16&gt;().ok().expect(&quot;PORT should be an integer&quot;)<br>}</pre><pre>pub fn domain_url() -&gt; String {<br>  dotenv().ok();</pre><pre>  var(&quot;DOMAIN_URL&quot;).unwrap_or_else(|_| &quot;http://localhost:3000&quot;.to_string())<br>}</pre><pre>pub fn smtp_username() -&gt; String {<br>  dotenv().ok();</pre><pre>  var(&quot;SMTP_USERNAME&quot;).expect(&quot;SMTP_USERNAME is not set&quot;)<br>}</pre><pre>pub fn smtp_password() -&gt; String {<br>  dotenv().ok();</pre><pre>  var(&quot;SMTP_PASSWORD&quot;).expect(&quot;SMTP_PASSWORD is not set&quot;)<br>}</pre><pre>pub fn smtp_host() -&gt; String {<br>  dotenv().ok();</pre><pre>  var(&quot;SMTP_HOST&quot;).expect(&quot;SMTP_HOST is not set&quot;)<br>}</pre><pre>pub fn smtp_port() -&gt; u16 {<br>  dotenv().ok();</pre><pre>  var(&quot;SMTP_PORT&quot;).expect(&quot;SMTP_PORT is not set&quot;).parse::&lt;u16&gt;().ok().expect(&quot;SMTP_PORT should be an integer&quot;)<br>}</pre><pre>#[allow(dead_code)]<br>pub fn smtp_sender_name() -&gt; String {<br>  dotenv().ok();</pre><pre>  var(&quot;SMTP_SENDER_NAME&quot;).expect(&quot;SMTP_SENDER_NAME is not set&quot;)<br>}</pre><p>To be able to use anywhere in our app, we have to mod vars.rs; before the main() in src/main.rs.</p><p>Create a file src/models.rs and paste in:</p><pre>use diesel::{r2d2::ConnectionManager, PgConnection};</pre><pre>// type alias to reduce verbosity<br>pub type Pool = r2d2::Pool&lt;ConnectionManager&lt;PgConnection&gt;&gt;;</pre><p>Then, create the database (if it doesn’t exist) and setup migrations by running:</p><pre>$ diesel setup</pre><p>Add actix-cors = &quot;0.2.0&quot; to our dependencies, then start the webserver by modifying src/main.rs to:</p><pre>#[macro_use]<br>extern crate diesel;<br>extern crate serde_json;<br>extern crate lettre;<br>extern crate native_tls;<br></pre><pre>mod models;<br>mod vars;<br></pre><pre>#[actix_rt::main]<br>async fn main() -&gt; std::io::Result&lt;()&gt; {<br>    use actix_cors::Cors;<br>    use actix_files::Files;<br>    use actix_session::CookieSession;<br>    use actix_web::{middleware, web, App, HttpServer, http::header};<br>    use diesel::{<br>        prelude::*, <br>        r2d2::{self, ConnectionManager}<br>    };</pre><pre>    std::env::set_var(&quot;RUST_LOG&quot;, &quot;actix_web=info,actix_server=info&quot;);<br>    env_logger::init();</pre><pre>    // create a database connection pool<br>    let manager = ConnectionManager::&lt;PgConnection&gt;::new(vars::database_url());<br>    let pool: models::Pool = r2d2::Pool::builder()<br>        .build(manager)<br>        .expect(&quot;Failed to create a database connection pool.&quot;);</pre><pre>    // Start http server<br>    HttpServer::new(move || {<br>        App::new()<br>            .data(pool.clone())<br>            // enable logger<br>            .wrap(middleware::Logger::default())<br>            // Enable sessions<br>            .wrap(<br>                CookieSession::signed(&amp;[0; 32])<br>                    .domain(vars::domain_url().as_str())<br>                    .name(&quot;auth&quot;)<br>                    .secure(false))<br>            .wrap(<br>                Cors::new()<br>                    .allowed_origin(&quot;*&quot;)<br>                    .allowed_methods(vec![&quot;GET&quot;, &quot;POST&quot;, &quot;DELETE&quot;])<br>                    .max_age(3600)<br>                    .finish())<br>            .service(Files::new(&quot;/assets&quot;, &quot;./templates/assets&quot;))<br>    })<br>    .bind(format!(&quot;{}:{}&quot;, vars::domain(), vars::port()))?<br>    .run()<br>    .await<br>}</pre><p>Wow, we went from 0 to 100 real quick. Let’s go over what we just did. We declare some external dependencies so we can use it in our app. Don&#39;t ask me why, that&#39;s how it is. Currently, Rust doesn&#39;t need that for every external crate but some crates haven&#39;t gotten the memo. We add an attribute to the extern statement for Diesel to enable the use of macros. Diesel comes with a lot of macros and is probably not very unusable without them, so we have to turn it on.</p><p>We add another attribute above main() to mark it as our main function for actix-web. You might also notice the function header changed from the simple fn main()... to what we have above. Actix-web is an async framework, so our main has to be asynchronous. We&#39;ll be seeing more async functions as we go along. In lines 14-21, we import a bunch of stuff we&#39;ll use. We create a connection pool in lines 27-30. Lines 33-56 configure and start our server. Let&#39;s look inside: we create an app (L34), store our pool so it can be available to our handlers (L35), configure session support (39-43) and CORS (44-49), serve our static resources from our templates/assets directory (50) and bind to the domain and port declared in our .env files (52).</p><h3>Adding our models</h3><p>We’ll create two models: User to hold our user records after registration and Confirmation which holds our user information during the registration process.</p><pre>$ diesel migration generate users<br>$ diesel migration generate confirmations</pre><p>The directories migrations/TIMESTAMP_users and migrations/TIMESTAMP_invitations contains the up and down migration SQL files for our user and invitation tables respectively.</p><p>Let’s fill out the four files:</p><pre>--migrations/TIMESTAMP_users/up.sql<br>CREATE TABLE users (<br>  id UUID NOT NULL PRIMARY KEY,<br>  email VARCHAR(50) NOT NULL UNIQUE,<br>  hash VARCHAR(150) NOT NULL,<br>  created_at TIMESTAMP NOT NULL<br>);</pre><pre>--migrations/TIMESTAMP_users/down.sql<br>DROP TABLE users;</pre><pre>--migrations/TIMESTAMP_confirmations/up.sql<br>CREATE TABLE confirmations (<br>  id UUID NOT NULL PRIMARY KEY,<br>  email VARCHAR(50) NOT NULL UNIQUE,<br>  expires_at TIMESTAMP NOT NULL<br>);</pre><pre>--migrations/TIMESTAMP_confirmations/down.sql<br>DROP TABLE confirmations;</pre><p>To create the tables in the database (and also create a src/schema.rs file), run:</p><pre>$ diesel migration run</pre><p>Like we did for var.rs and models.rs, add mod schema.rs to our main.rs file.</p><p>Update src/models.rs to:</p><pre>// src/models.rs<br>use diesel::{r2d2::ConnectionManager, PgConnection};<br>use serde::{Deserialize, Serialize};<br>use uuid::Uuid;</pre><pre>use super::schema::*;</pre><pre>// type alias to reduce verbosity<br>pub type Pool = r2d2::Pool&lt;ConnectionManager&lt;PgConnection&gt;&gt;;</pre><pre>#[derive(Debug, Serialize, Deserialize, Queryable, Insertable)]<br>#[table_name = &quot;confirmations&quot;]<br>pub struct Confirmation {<br>    pub id: Uuid,<br>    pub email: String,<br>    pub expires_at: chrono::NaiveDateTime,<br>}</pre><pre>#[derive(Debug, Serialize, Deserialize, Queryable, Insertable)]<br>#[table_name = &quot;users&quot;]<br>pub struct User {<br>    pub id: Uuid,<br>    pub email: String,<br>    pub hash: String,<br>    pub created_at: chrono::NaiveDateTime,<br>}</pre><pre>#[derive(Debug, Serialize, Deserialize)]<br>pub struct SessionUser {<br>    pub id: Uuid,<br>    pub email: String,<br>}</pre><pre>// any type that implements Into&lt;String&gt; can be used to create a Confirmation<br>impl&lt;T&gt; From&lt;T&gt; for Confirmation where<br>T: Into&lt;String&gt; {<br>     fn from(email: T) -&gt; Self {<br>        Confirmation {<br>            id: Uuid::new_v4(),<br>            email: email.into(),<br>            expires_at: chrono::Local::now().naive_local() + chrono::Duration::hours(24),<br>        }<br>    }<br>}</pre><pre>impl From&lt;User&gt; for SessionUser {<br>    fn from(User { email, id, .. }: User) -&gt; Self {<br>        SessionUser { email, id }<br>    }<br>}</pre><pre>impl User {<br>    pub fn from&lt;S: Into&lt;String&gt;, T: Into&lt;String&gt;&gt;(email: S, pwd: T) -&gt; Self {<br>        User {<br>            id: Uuid::new_v4(),<br>            email: email.into(),<br>            hash: pwd.into(),<br>            created_at: chrono::Local::now().naive_local(),<br>        }<br>    }<br>}</pre><p>Confirmation and User are structs for our database models, SessionUser is for use within the app and the impl blocks are for transforming one to the other.</p><p>The table_name attributes should be self-explanatory. The derive traits on line 10 &quot;pairs&quot; our struct with various traits: Debug to enable printing to the console, Serialize and Deserialize to enable conversion to and from JSON, Queryable and Insertable to enable storing into and retrieving from the database.</p><h3>Add an error model</h3><p>We need a way to express the different errors that could arise in our app. This way, we can tailor our response to the specific error.</p><p>Create src/errors.rs and add mod errors; in main.rs. Paste the following code into src/errors.rs:</p><pre>// src/errors.rs<br>use actix_web::{HttpResponse, ResponseError};<br>use derive_more::Display;<br>use diesel::result::{DatabaseErrorKind, Error as DBError};<br>use std::convert::From;<br>use uuid::Error as UuidError;</pre><pre>#[derive(Debug, Display)]<br>pub enum AuthError {<br>    #[display(fmt = &quot;DuplicateValue: {}&quot;, _0)]<br>    DuplicateValue(String),</pre><pre>    #[display(fmt = &quot;BadId&quot;)]<br>    BadId,</pre><pre>    #[display(fmt = &quot;GenericError: {}&quot;, _0)]<br>    GenericError(String),<br>}<br></pre><pre>impl ResponseError for AuthError {<br>    fn error_response(&amp;self) -&gt; HttpResponse {<br>        match self { <br>            AuthError::BadId =&gt; HttpResponse::BadRequest().json(&quot;Invalid ID&quot;),</pre><pre>            AuthError::DuplicateValue(ref message) =&gt; HttpResponse::BadRequest().json(message),</pre><pre>            AuthError::GenericError(ref message) =&gt; HttpResponse::BadRequest().json(message),<br>        }<br>    }<br>}<br></pre><pre>impl From&lt;UuidError&gt; for AuthError {<br>    fn from(_: UuidError) -&gt; AuthError {<br>        AuthError::BadId<br>    }<br>}</pre><pre>impl From&lt;DBError&gt; for AuthError {<br>    fn from(error: DBError) -&gt; AuthError {<br>        // We only care about UniqueViolations<br>        match error {<br>            DBError::DatabaseError(kind, info) =&gt; {<br>                let message = info.details().unwrap_or_else(|| info.message()).to_string();</pre><pre>                match kind {<br>                    DatabaseErrorKind::UniqueViolation =&gt; AuthError::DuplicateValue(message),<br>                    _ =&gt; AuthError::GenericError(message)<br>                }                <br>            }<br>            _ =&gt; AuthError::GenericError(String::from(&quot;Some database error occured&quot;)),<br>        }<br>    }<br>}</pre><p>We declare an enumeration of our errors AuthError which will grow over time as potential error conditions multiply. At L20 we convert our errors into a HTTP response. At L33 we convert any UuidError into a BadId. At L39 we handle database errors. Other than a UniqueViolation, we return a GenericError for any other error.</p><h3>Process flow</h3><p>The registration flow we’ll implement is:</p><ol><li>The user sends a request with a new email address.</li><li>We then send a confirmation link to the email address.</li><li>The user then creates a password using the link to complete the registration process.</li></ol><p>To sign in, the user sends their email address and password combination. If the combination is valid, we create a session for the user and send them to their home page (web) or return a session cookie (API).</p><p>For signing out, we just delete the user’s session.</p><p>Now we’ve defined what our service will do, let’s look at the first step which is <a href="https://medium.com/@ukchukx/162667ee40f6">sending a confirmation link</a> to the user.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=55d0b0a848d" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/creating-a-web-and-api-authentication-service-in-rust-55d0b0a848d">Creating a web and API authentication service in Rust</a> was originally published in <a href="https://medium.com/swlh">The Startup</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Creating an inline editable component in React and publishing to NPM]]></title>
            <link>https://medium.com/@ukchukx/creating-an-inline-editable-component-in-react-and-publishing-to-npm-1fdcf0050aec?source=rss-5114de41076a------2</link>
            <guid isPermaLink="false">https://medium.com/p/1fdcf0050aec</guid>
            <category><![CDATA[inline-editor]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[input-field]]></category>
            <dc:creator><![CDATA[Uk Chukundah]]></dc:creator>
            <pubDate>Sat, 18 Jan 2020 12:23:48 GMT</pubDate>
            <atom:updated>2020-01-18T12:23:48.877Z</atom:updated>
            <content:encoded><![CDATA[<blockquote><em>We previously created this component in </em><a href="https://medium.com/@ukchukx/creating-an-inline-editable-component-in-vue-and-publishing-to-npm-ad7ef6403694"><em>Vue</em></a><em> and </em><a href="https://medium.com/@ukchukx/creating-an-inline-input-component-in-svelte-and-publishing-to-npm-84274be1aa73"><em>Svelte</em></a><em> ; now we’ll explore creating it in React.</em></blockquote><p>While squashing some bugs on and making some updates to my <a href="https://github.com/ukchukx/address-book">address book</a>, I decided to change the input fields to the inline editable style found on Trello (show below), Google Sheets, etc.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/280/0*SSYv6SG9l9CYFLjQ.gif" /></figure><p>I’d like to use this component in other apps so we’ll be making it a standalone component in this tutorial.</p><p>Since this is a single component, it’s easier testing in an online sandbox like <a href="https://codesandbox.io/s/rl74rn6q7q">this one on Sandbox.io</a> instead of creating a full-fledged app.</p><p>To start, let’s create the needed files:</p><pre>$ mkdir react-inline-input; cd react-inline-input<br>$ touch package.json .gitignore .babelrc<br>$ mkdir src; touch src/InlineInput.js</pre><p>Let’s fill out package.json:</p><pre>d{<br>  &quot;name&quot;: &quot;react-inline-input&quot;,<br>  &quot;version&quot;: &quot;1.0.0&quot;,<br>  &quot;description&quot;: &quot;A React component for inline editable inputs.&quot;,<br>  &quot;main&quot;: &quot;dist/index.js&quot;,<br>  &quot;scripts&quot;: {<br>    &quot;build&quot;: &quot;./node_modules/.bin/babel src --out-file dist/index.js&quot;<br>  },<br>  &quot;repository&quot;: {<br>    &quot;type&quot;: &quot;git&quot;,<br>    &quot;url&quot;: &quot;git+https://github.com/ukchukx/react-inline-input&quot;<br>  },<br>  &quot;keywords&quot;: [<br>    &quot;react&quot;,<br>    &quot;inline&quot;,<br>    &quot;editable&quot;,<br>    &quot;input&quot;<br>  ],<br>  &quot;files&quot;: [<br>    &quot;dist&quot;,<br>    &quot;src&quot;<br>  ],<br>  &quot;author&quot;: &quot;Uk Chukundah&quot;,<br>  &quot;license&quot;: &quot;MIT&quot;,<br>  &quot;peerDependencies&quot;: {<br>    &quot;react&quot;: &quot;^16.12.0&quot;,<br>    &quot;react-dom&quot;: &quot;^16.12.0&quot;<br>  },<br>  &quot;devDependencies&quot;: {<br>    &quot;@babel/cli&quot;: &quot;^7.8.3&quot;,<br>    &quot;@babel/core&quot;: &quot;^7.8.3&quot;,<br>    &quot;@babel/preset-env&quot;: &quot;^7.8.3&quot;,<br>    &quot;@babel/preset-react&quot;: &quot;^7.8.3&quot;,<br>    &quot;react&quot;: &quot;^16.12.0&quot;,<br>    &quot;react-dom&quot;: &quot;^16.12.0&quot;<br>  }<br>}</pre><p>And.babelrc:</p><pre>{<br>  &quot;presets&quot;: [&quot;@babel/preset-react&quot;, &quot;@babel/preset-env&quot;]<br>}</pre><p>For now our .gitignore will only exclude the obligatory node_modules directory:</p><pre>node_modules</pre><p>Let’s go ahead and create our first <a href="https://github.com/ukchukx/react-inline-input/commit/160234fd75742fc0e11ff1cd29f93f2612ffb4bc">commit</a>.</p><p>Before writing out our component, let’s install prop-types to help validate our component props:</p><pre>$ npm i -D prop-types</pre><p>The default state of an inline editable component is to display a static element. When the component is clicked, it transforms into an input field that accepts user input. When focus goes away from the element, it toggles back to a static element.</p><p>Our component will handle text, number, select and textarea inputs.</p><p>We’ll leave styling up to users. At the least, you should show a pointer cursor when the mouse hovers over the static element.</p><h3>Number and text input</h3><pre>import React, { Component } from &#39;react&#39;;<br>import PropTypes from &#39;prop-types&#39;;</pre><pre>export default class InlineInput extends Component {<br>  static propTypes = {<br>    value:  PropTypes.oneOfType([<br>      PropTypes.string,<br>      PropTypes.number<br>    ]),<br>    type: PropTypes.string,<br>    placeholder: PropTypes.string,<br>    labelClasses: PropTypes.string,<br>    inputClasses: PropTypes.string,<br>    onInput: PropTypes.func.isRequired<br>  };</pre><pre>  static defaultProps = {<br>    value: &#39;&#39;,<br>    type: &#39;text&#39;,<br>    placeholder: &#39;text&#39;,<br>    labelClasses: &#39;&#39;,<br>    inputClasses: &#39;&#39;<br>  };</pre><pre>  state = {<br>    editing: false,<br>    inputEl: React.createRef(),<br>    isText: this.props.type === &#39;text&#39;,<br>    isNumber: this.props.type === &#39;number&#39;<br>  };</pre><pre>  static getDerivedStateFromProps(nextProps, prevState) {<br>    const { type } = nextProps;</pre><pre>    return {<br>      isText: type === &#39;text&#39;,<br>      isNumber: type === &#39;number&#39;<br>    };<br>  }</pre><pre>  toggle = () =&gt; {<br>    this.setState({ editing: !this.state.editing }, () =&gt; {<br>      const { editing, inputEl } = this.state;<br>      <br>      if (editing) inputEl.current.focus();<br>    });<br>  };</pre><pre>  handleEnter = (e) =&gt; {<br>    if (e.keyCode === 13) this.state.inputEl.current.blur();<br>  };</pre><pre>  handleBlur = () =&gt; {<br>    this.toggle();<br>  };</pre><pre>  handleInput = (e) =&gt; {<br>    this.emitValue(this.state.isNumber ? +e.target.value : e.target.value);<br>  };</pre><pre>  emitValue = (value) =&gt; {<br>    this.props.onInput(value);<br>  };</pre><pre>  computeLabel = () =&gt; {<br>    const { state: { isNumber, isText }, props: { value, placeholder } } = this;</pre><pre>    if (isNumber) return value === &#39;&#39; ? placeholder : value;<br>    if (isText) return value ? value : placeholder;<br>  };</pre><pre>  render() {<br>    const { state: { editing, isText, isNumber } } = this;</pre><pre>      return (<br>        editing &amp;&amp; (isText || isNumber)<br>          ? this._renderInput()<br>          : this._renderLabel()<br>      );<br>  }</pre><pre>  _renderLabel = () =&gt; {<br>    const { props: { labelClasses }, toggle, computeLabel } = this;<br>    <br>    return (<br>      &lt;span className={labelClasses} onClick={toggle}&gt;<br>        {computeLabel()}<br>      &lt;/span&gt;<br>    );<br>  };</pre><pre>  _renderInput = () =&gt; {<br>    const { <br>      props: { inputClasses, placeholder, type, value }, <br>      handleBlur, <br>      handleEnter, <br>      handleInput, <br>      state: { inputEl } <br>    } = this;<br>    <br>    return (<br>      &lt;input <br>        ref={inputEl}<br>        type={type} <br>        defaultValue={value} <br>        className={inputClasses} <br>        placeholder={placeholder}<br>        onBlur={handleBlur}<br>        onKeyUp={handleEnter}<br>        onInput={handleInput} /&gt;<br>    );<br>  };<br>}</pre><p>Our default state is a static element. We’ll use a span as our static element. When the span is clicked, we hide the span and show our input element (via the onClick handler on the span).</p><p>When the span is clicked, toggle() is called which does two things. It hides the span by setting editing to true and it places the focus on our input so it can accept user input without the user needed to click on the input again. That&#39;s one of the reasons we&#39;re holding a ref to the input via inputEl; the other is to take away focus when the Enter key is pressed.</p><p>When focus leaves the input, we handle the DOM blur event fired via handleBlur(). This function calls toggle() to hide the input and show the span.</p><p>We also want to toggle the component when the user presses the Enter key. We handle that via handleEnter() which just takes away focus from the input element which will cause handleBlur() to be called.</p><p>When the user changes the input value, we call handleInput(). It reads the current input value, converts it to a number if type has been set to number, and calls emitValue().</p><p>emitValue() sends the value it receives to the parent component via the event handler passed into the onInput prop.</p><p>The inputClasses and labelClasses props are to give the user full control over styling as we&#39;re not going to do any styling.</p><p>computeLabel() controls what is shown as the static element text. For number inputs, we only show placeholder when no input has been provided; otherwise we show the user input (this ensures that 0 is shown, for example). For text inputs, we show placeholder if value is empty.</p><p>That’s all that’s needed for text and number input. We’ll go ahead and create a commit <a href="https://github.com/ukchukx/react-inline-input/commit/d7903d3f857785aa87514f6c2f3325bc1b64228f">here</a>.</p><h3>Textarea</h3><pre>import React, { Component } from &#39;react&#39;;<br>import PropTypes from &#39;prop-types&#39;;</pre><pre>export default class InlineInput extends Component {<br>  static propTypes = {<br>    // ...<br>    cols: PropTypes.number,<br>    rows: PropTypes.number<br>  };</pre><pre>  static defaultProps = {<br>    // ...<br>    cols: 20,<br>    rows: 2<br>  };</pre><pre>  state = {<br>    // ...<br>    isTextArea: this.props.type === &#39;textarea&#39;<br>  };</pre><pre>  static getDerivedStateFromProps(nextProps, _) {<br>    // ...</pre><pre>    return {<br>      // ...<br>      isTextArea: type === &#39;textarea&#39;<br>    };<br>  }</pre><pre>  // ...</pre><pre>  computeLabel = () =&gt; {<br>    const { state: { isNumber, isText, isTextArea }, props: { value, placeholder } } = this;</pre><pre>    if (isNumber) return value === &#39;&#39; ? placeholder : value;<br>    if (isText || isTextArea) return value ? value : placeholder;<br>  };</pre><pre>  render() {<br>    const { <br>      state: { editing, isText, isNumber, isTextArea },<br>      _renderInput,<br>      _renderLabel,<br>      _renderTextArea<br>    } = this;<br>    const shouldShowNumberOrText = editing &amp;&amp; (isText || isNumber);<br>    const shouldShowTextArea = editing &amp;&amp; isTextArea;</pre><pre>      return (<br>        shouldShowNumberOrText<br>          ? _renderInput()<br>          : (shouldShowTextArea <br>              ? _renderTextArea() <br>              : _renderLabel()<br>            )<br>      );<br>  }</pre><pre>  // ...</pre><pre>  _renderTextArea = () =&gt; {<br>    const { <br>      handleBlur, <br>      handleEnter, <br>      handleInput, <br>      props: { cols, inputClasses, placeholder, rows, type, value }, <br>      state: { inputEl } <br>    } = this;</pre><pre>    return (<br>      &lt;textarea <br>        ref={inputEl}<br>        value={value} <br>        className={inputClasses} <br>        placeholder={placeholder}<br>        onBlur={handleBlur}<br>        onInput={handleInput}<br>        rows={rows}<br>        cols={cols}&gt;<br>      &lt;/textarea&gt;<br>    );<br>  };<br>}</pre><p>In textareas, Enter is a normal input and it would be bad UX to toggle the component when Enter is pressed. That’s the reason Enter is handled separately in handleEnter() so we can use handleInput() to handle text area input without modification.</p><p>The only addition is the rows and cols props to give the parent component control over sizing. They are initialized to their HTML default values if no values are supplied.</p><p>A text area label is computed the same way as a text input label, so we just modify the conditional test for text inputs in computeLabel().</p><p>That’s all that’s needed to support textareas. Let’s commit our <a href="https://github.com/ukchukx/react-inline-input/commit/04664ef720aa55a18b3c0dbb141c66970914420b">work</a>.</p><h3>Select</h3><pre>import React, { Component } from &#39;react&#39;;<br>import PropTypes from &#39;prop-types&#39;;</pre><pre>export default class InlineInput extends Component {<br>  static propTypes = {<br>    // ...<br>    options: PropTypes.array,<br>    renderSelectLabel: PropTypes.func<br>  };</pre><pre>  static defaultProps = {<br>    // ...<br>    options: [],<br>    renderSelectLabel: null<br>  };</pre><pre>  state = { <br>      /*...*/<br>  };</pre><pre>  static getDerivedStateFromProps(nextProps, _) {<br>    const { type } = nextProps;</pre><pre>    return {<br>      // ...<br>      isSelect: type === &#39;select&#39;<br>    };<br>  }</pre><pre>  // ...</pre><pre>  handleChange = (e) =&gt; {<br>    const selectedIndex = this.props.placeholder ? e.target.selectedIndex - 1 : e.target.selectedIndex;</pre><pre>    this.setState({ selectedIndex }, () =&gt; {<br>      this.emitValue(this.props.options[selectedIndex].value);<br>    });<br>  };</pre><pre>  // ...</pre><pre>  computeLabel = () =&gt; {<br>    const { state: { isNumber, isText, isTextArea, selectedIndex }, props: { value, placeholder, options } } = this;</pre><pre>    if (isNumber) return value === &#39;&#39; ? placeholder : value;<br>    if (isText || isTextArea) return value ? value : placeholder;<br>    // Select<br>    return selectedIndex === -1 ? placeholder : options[selectedIndex].label;<br>  };</pre><pre>  render() {<br>    const { <br>      state: { editing, isNumber, isSelect, isText, isTextArea },<br>      _renderInput,<br>      _renderLabel,<br>      _renderSelect,<br>      _renderTextArea<br>    } = this;<br>    const shouldShowNumberOrText = editing &amp;&amp; (isText || isNumber);<br>    const shouldShowTextArea = editing &amp;&amp; isTextArea;<br>    const shouldShowSelect = editing &amp;&amp; isSelect;</pre><pre>      return (<br>        shouldShowNumberOrText<br>          ? _renderInput()<br>          : (shouldShowTextArea <br>              ? _renderTextArea() <br>              : (shouldShowSelect <br>                  ? _renderSelect()<br>                  : _renderLabel()<br>                )<br>            )<br>      );<br>  }</pre><pre>  _renderLabel = () =&gt; {<br>    const { <br>      props: { labelClasses, renderSelectLabel }, <br>      toggle, <br>      computeLabel,<br>      _renderSelectLabel<br>    } = this;<br>    const selectLabelRenderFn = renderSelectLabel ? renderSelectLabel : _renderSelectLabel;<br>    <br>    return (<br>      &lt;span className={labelClasses} onClick={toggle}&gt;<br>        {computeLabel()}<br>        {selectLabelRenderFn()}<br>      &lt;/span&gt;<br>    );<br>  };</pre><pre>  // ...</pre><pre>  _renderSelect = () =&gt; {<br>    const { <br>      handleBlur, <br>      handleChange,<br>      props: { inputClasses, options, placeholder, value }, <br>      state: { inputEl } <br>    } = this;</pre><pre>    return (<br>      &lt;select <br>        ref={inputEl}<br>        class={inputClasses}<br>        defaultValue={value}<br>        onChange={handleChange}<br>        onBlur={handleBlur}&gt;<br>        {placeholder<br>          ? &lt;option disabled value&gt;{placeholder}&lt;/option&gt;<br>          : &#39;&#39;}<br>        {options.map(({ label, value }, i) =&gt; (<br>          &lt;option <br>            key={i}<br>            value={value}&gt;<br>            {label}<br>          &lt;/option&gt;<br>        ))}<br>      &lt;/select&gt;<br>    );<br>  };</pre><pre>  _renderSelectLabel = () =&gt; this.state.isSelect ? (&lt;span&gt;&amp;#9660;&lt;/span&gt;) : &#39;&#39;;<br>}</pre><p>For selects we need an array of options which is supplied through the options prop, which is an array of objects that have label and value keys.</p><p>In the span element we show a caret to indicate that it’s a select and we provide a way for it to be customized using the renderSelectLabel prop.</p><p>In our label computed prop, for selects we display the label of the currently selected value.</p><p>With that, we have added support for select inputs. Let&#39;s commit our <a href="https://github.com/ukchukx/react-inline-input/commit/85400d607c52dafbc97d09667e7ad5428de88858">changes</a>.</p><h3>Notifying parent components on blur</h3><p>Since we our components handle blur event for it’s input elements, let’s pass that along to the parent component as well. That’s trivial to support because of how we organized our component:</p><pre>import React, { Component } from &#39;react&#39;;<br>import PropTypes from &#39;prop-types&#39;;</pre><pre>export default class InlineInput extends Component {<br>  static propTypes = {<br>    // ...<br>    onBlur: PropTypes.func<br>  };</pre><pre>  static defaultProps = {<br>    // ...<br>    onBlur: null<br>  };</pre><pre>  // ...</pre><pre>  handleBlur = () =&gt; {<br>    const { onBlur } = this.props;</pre><pre>    this.toggle();<br>    if (onBlur) onBlur();<br>  };</pre><pre>  // ...<br>}</pre><p>Whenever we receive a blur event from an input element, we call the passed event handler.</p><p>Don’t remember to commit your <a href="https://github.com/ukchukx/react-inline-input/commit/bb59e765c4c90679673b5d74a75d2f814eec90ca">changes</a>.</p><h3>Publishing to NPM</h3><p>Before we publish, we need to fill our README with helpful text and build the component.</p><p>To build the component, run:</p><pre>$ npm run build</pre><p>See the changes made <a href="https://github.com/ukchukx/react-inline-input/commit/df41a5e4b1055be0b8c3142b42cb1ae7fc63b633">here</a>.</p><p>To publish, I first login to my NPM <a href="https://www.npmjs.com/~ukchukx">account</a> with:</p><pre>$ npm login</pre><p>Then, from the root directory I run:</p><pre>$ npm publish</pre><p>After successfully publishing, we can use our component in React projects by installing it with:</p><pre>$ npm install react-inline-input</pre><p>or in the browser using <a href="https://unpkg.com/react-inline-input">https://unpkg.com/react-inline-input</a>.</p><p>Visit the GitHub repository <a href="https://github.com/ukchukx/react-inline-input">here</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1fdcf0050aec" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Creating an inline input component in Svelte and publishing to NPM]]></title>
            <link>https://medium.com/@ukchukx/creating-an-inline-input-component-in-svelte-and-publishing-to-npm-84274be1aa73?source=rss-5114de41076a------2</link>
            <guid isPermaLink="false">https://medium.com/p/84274be1aa73</guid>
            <category><![CDATA[inline-editor]]></category>
            <category><![CDATA[svelte]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Uk Chukundah]]></dc:creator>
            <pubDate>Mon, 13 Jan 2020 10:27:42 GMT</pubDate>
            <atom:updated>2020-01-13T10:33:39.256Z</atom:updated>
            <content:encoded><![CDATA[<h3>Creating an inline editable component in Svelte and publishing to NPM</h3><blockquote><em>We previously created this component in Vue </em><a href="https://medium.com/@ukchukx/creating-an-inline-editable-component-in-vue-and-publishing-to-npm-ad7ef6403694"><em>here</em></a><em>; now we’ll explore creating it in </em><a href="https://svelte.dev/"><em>Svelte</em></a><em> — a nice and tiny framework which compiles components and does not require a runtime.</em></blockquote><p>While squashing some bugs on and making some updates to my <a href="https://github.com/ukchukx/address-book">address book</a>, I decided to change the input fields to the inline editable style found on Trello (show below), Google Sheets, etc.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/280/0*s4G3Dbrs06GgMpg6.gif" /></figure><p>I’d like to use this component in other apps so we’ll be making it a standalone component in this tutorial.</p><p>Since this is a single component, it’s easier testing in an online sandbox like <a href="https://codesandbox.io/s/svelte">this one on Sandbox.io</a> instead of creating a full-fledged app.</p><p>Svelte provides a <a href="https://github.com/sveltejs/component-template">base</a> for building shareable components and we’ll make use of it.</p><p>To start, I’ll run:</p><pre>$ npx degit sveltejs/component-template svelte-inline-input<br>$ cd svelte-inline-input<br>$ npm install</pre><p>In package.json, we change the name to svelte-inline-inputand rename src/Component.svelte to src/InlineInput.svelte. We also update the reference in src/index.js.</p><p>Initialize Git and create a <a href="https://github.com/ukchukx/svelte-inline-input/commit/0eefb07f3b5ef337c27b19811f49151468aedfa0">commit</a>.</p><p>The default state of an inline editable component is to display a static element. When the component is clicked, it transforms into an input field that accepts user input. When focus goes away from the element, it toggles back to a static element.</p><p>Our component will handle text, number, select and textarea inputs.</p><p>We’ll leave styling up to users. At the least, you should show a pointer cursor when the mouse hovers over the static element.</p><h3>Number and text</h3><pre>&lt;script&gt;<br>import { tick } from &#39;svelte&#39;;</pre><pre>// Props<br>export let value = &#39;&#39;;<br>export let type = &#39;text&#39;;<br>export let placeholder = &#39;&#39;;<br>export let labelClasses = &#39;&#39;;<br>export let inputClasses = &#39;&#39;;</pre><pre>let editing = false;<br>let inputEl;<br>let label;</pre><pre>// Computed<br>$: isText = type === &#39;text&#39;;<br>$: isNumber = type === &#39;number&#39;;<br>$: if (isNumber) {<br>      label = value === &#39;&#39; ? placeholder : value;<br>    } else if (isText) {<br>      label = value ? value : placeholder;<br>    }</pre><pre>const toggle = async (_) =&gt; {<br>  editing = !editing;</pre><pre>  if (editing) {<br>    await tick();<br>    inputEl.focus();<br>  }<br>};</pre><pre>const handleInput = (e) =&gt; {<br>  value = isNumber ? +e.target.value : e.target.value;<br>};</pre><pre>const handleEnter = (e) =&gt; {<br>  if (e.keyCode === 13) inputEl.blur();<br>};</pre><pre>const handleBlur = (_) =&gt; {<br>  toggle();<br>};<br>&lt;/script&gt;</pre><pre>{#if editing &amp;&amp; (isText || isNumber)}<br>  &lt;input <br>    class={inputClasses}<br>    bind:this={inputEl}<br>    {type}<br>    {value}<br>    {placeholder}<br>    on:input={handleInput}<br>    on:keyup={handleEnter}<br>    on:blur={handleBlur}&gt;<br>{:else}<br>  &lt;span <br>    class={labelClasses}<br>    on:click={toggle}&gt;<br>  {label}<br>  &lt;/span&gt;<br>{/if}</pre><p>Our default state is a static element. We’ll use a span as our static element. When the span is clicked, we hide the span and show our input element.</p><p>At lines 5–9, we declare our props (i.e. variables we expect from parent components) and set their default values. Lines 11–13 declare our internal variables. Lines 16–22 contain our reactive declarations (i.e. Svelte equivalent of Vue’s computed properties).</p><p>When the span is clicked, toggle() is called which does two things. It hides the span by setting editing to true and it places the focus on our input so it can accept user input without the user needed to click on the input again. That&#39;s one of the reasons we&#39;re holding a ref to the input via inputEl; the other is to take the focus away from the input.</p><p>When focus leaves the input, we handle the blur event fired via handleBlur(). This function calls toggle() to hide the input and show the span.</p><p>We also want to toggle the component when the user presses the Enter key. We handle that via handleEnter() which just takes away focus from the input element which will cause handleBlur() to be called.</p><p>When the user changes the input value, we call handleInput(). It checks if the type prop is a number and if it is, converts the event value to a number and updates value.</p><p>If you’ve seen the <a href="https://bowlsofsalt.com/inline-input-component-vue-npm/">Vue version</a>, you might be wondering where emitValue() is. Since Svelte supports two-way data binding with the bind directive, emitValue() is not needed. We just need to bind to value in our parent components like so:</p><pre>&lt;InlineInput bind:value={yourVariable} /&gt;</pre><p>If your variable is named value, then you could do:</p><pre>&lt;InlineInput bind:value /&gt;</pre><p>The inputClasses and labelClasses props are to give the user full control over styling as we&#39;re not going to do any styling.</p><p>Our label computed prop controls what is displayed when the static element is shown. For number inputs, we only display placeholder when nothing has been input; otherwise we display the user input (this ensures that 0 is displayed). For text inputs, we display placeholder if value is empty.</p><p>On line 50, notice the {type} binding. This is shorthand for type={type}, which is equivalent to :type=&quot;type&quot; in Vue.</p><p>That’s all that’s needed for text and number input. We’ll go ahead and create a commit <a href="https://github.com/ukchukx/svelte-inline-input/commit/68c6fbe9e4805f148fcda5fcc2a4e023f453c4c8">here</a>.</p><h3>Textarea</h3><pre>&lt;script&gt;<br>// ...</pre><pre>// Props<br>// ...<br>export let rows = 2;<br>export let cols = 20;</pre><pre>// ...</pre><pre>// Computed<br>// ...<br>$: isTextArea = type === &#39;textarea&#39;;<br>$: if (isNumber) {<br>      label = value === &#39;&#39; ? placeholder : value;<br>    } else if (isText || isTextArea) {<br>      label = value ? value : placeholder;<br>    }</pre><pre>// ...<br>&lt;/script&gt;</pre><pre>{#if editing &amp;&amp; (isText || isNumber)}<br> &lt;!-- --&gt;<br>{:else if editing &amp;&amp; isTextArea}<br>  &lt;textarea<br>    class={inputClasses}<br>    bind:this={inputEl}<br>    {placeholder}<br>    {value}<br>    {rows}<br>    {cols}<br>    on:input={handleInput}<br>    on:blur={handleBlur} /&gt;<br>{:else}<br>  &lt;!-- --&gt;<br>{/if}</pre><p>In textareas, Enter is a normal input and it would be bad UX to toggle the component when Enter is pressed. That&#39;s the reason we handled Enter separately from other inputs. This way, we only have to not add the handler to the textarea, instead of modifying handleInput() to differentiate Enters from other input and textareas for number and text. This would make our function more complex and more error-prone.</p><p>The only addition is the rows and cols props to give the parent component control over sizing. They are initialized to their HTML default values if the parent component does not supply values.</p><p>That’s all that’s needed to support textareas. Let’s make a commit <a href="https://github.com/ukchukx/svelte-inline-input/commit/cc1c86d279a2b084374f100a856adfb207646cda">here</a>.</p><h3>Select</h3><pre>&lt;script&gt;<br>// ...</pre><pre>// Props<br>// ...<br>export let options = [];</pre><pre>// ...<br>let selectedIndex = options.findIndex(o =&gt; o.value === value);</pre><pre>// Computed<br>// ...<br>$: isSelect = type === &#39;select&#39;;<br>$: if (isNumber) {<br>      label = value === &#39;&#39; ? placeholder : value;<br>    } else if (isText || isTextArea) {<br>      label = value ? value : placeholder;<br>    } else { // Select<br>      label = selectedIndex === -1 ? placeholder : options[selectedIndex].label;<br>    }</pre><pre>// ...</pre><pre>const handleChange = (e) =&gt; {<br>  selectedIndex = placeholder ? e.target.selectedIndex - 1 : e.target.selectedIndex;<br>  value = options[selectedIndex].value;<br>};<br>&lt;/script&gt;</pre><pre>{#if editing &amp;&amp; (isText || isNumber)}<br>  &lt;!-- --&gt;<br>{:else if editing &amp;&amp; isTextArea}<br>  &lt;!-- --&gt;<br>{:else if editing &amp;&amp; isSelect}<br>  &lt;select <br>    class={inputClasses}<br>    bind:this={inputEl}<br>    {value}<br>    on:blur={handleBlur}&gt;<br>    {#if placeholder}<br>      &lt;option selected value disabled&gt;{placeholder}&lt;/option&gt;<br>    {/if}<br>    {#each options as { label, value }, i}<br>      &lt;option <br>        key={i}<br>        {value}&gt;<br>        {label}<br>      &lt;/option&gt;<br>    {/each}<br>  &lt;/select&gt;<br>{:else}<br>  &lt;span <br>    class={labelClasses}<br>    on:click={toggle}&gt;<br>    {label}<br>    &lt;slot name=&quot;selectCaret&quot;&gt;<br>      {#if isSelect}<br>        &lt;span&gt;&amp;#9660;&lt;/span&gt;<br>      {/if}<br>    &lt;/slot&gt;<br>  &lt;/span&gt;<br>{/if}</pre><p>For selects we need an array of options which is supplied through the options prop, which is an array of objects that have label and value keys.</p><p>In the span element we show a caret to indicate that it’s a select. We added the caret in a named slot to enable the user change the default.</p><p>In our label computed prop, for selects we display the label of the currently selected value, if any or the supplied placeholder.</p><p>When a selection is made, we get the index of the selected option (which is one less if a placeholder was supplied). We then update value.</p><p>With that, we have added support for select inputs. As we&#39;ve done previously, we make a commit <a href="https://github.com/ukchukx/svelte-inline-input/commit/190c2973365ee5a846048c290aab61d1946b16f4">here</a>.</p><h3>Publishing to NPM</h3><p>Before we publish, we need to a README with helpful text and build the component.</p><p>To build the component, run:</p><pre>$ npm run build</pre><p>In this case, we only build when publishing the component using the prepublishOnly hook in our package.json scripts declaration.</p><p>Our README content:</p><pre># svelte-inline-input</pre><pre>&gt; An inline editable input component for Svelte.</pre><pre>Displays as text and becomes editable by clicking or tapping.</pre><pre>## Installation</pre><pre>```js<br>npm install svelte-inline-input<br>```</pre><pre>### Browser</pre><pre>```html<br>&lt;script type=&quot;text/javascript&quot; src=&quot;https://unpkg.com/svelte-inline-input/dist/index.mjs&quot;&gt;&lt;/script&gt;<br>```</pre><pre>### Module</pre><pre>```js<br>import InlineInput from &#39;svelte-inline-input&#39;;<br>```</pre><pre>## Usage</pre><pre>Once installed, it can be used in a template as:</pre><pre>```html<br>&lt;InlineInput bind:value /&gt;<br>```</pre><pre>See the props table below for the available options.</pre><pre>### Props</pre><pre>| Property | Type | Description | Default |<br>|:--|:--|:--|:--|<br>| type | string | The input type. Could be text, number, textarea or select | text |<br>| placeholder | string | Text to be shown as a placeholder while there is no input |  empty string |<br>| labelClasses | string | CSS classes for the label element | empty string |<br>| inputClasses | string | CSS classes for the input element | empty string |<br>| rows | integer | Textarea rows | 2 |<br>| cols | integer | Textarea columns | 20 |<br>| options | array | Provides the options for selects. Each object should have the format `{label: x, value: x}` | [] |</pre><pre>## License</pre><pre>[MIT](http://opensource.org/licenses/MIT)</pre><p>We then add some more information in our package.json that are needed to publish the component. After that, we commit the <a href="https://github.com/ukchukx/svelte-inline-input/commit/bbfb5f7a36cb4c7533a0307db854f605a61f38f1">changes</a>.</p><p>To publish, I first login to my NPM <a href="https://www.npmjs.com/~ukchukx">account</a> with:</p><pre>$ npm login</pre><p>Then, from the root directory I run:</p><pre>$ npm publish</pre><p>After successfully publishing, we can use our component in Node.js projects by installing it with:</p><pre>$ npm install svelte-inline-input</pre><p>or in the browser using <a href="https://unpkg.com/svelte-inline-input">https://unpkg.com/svelte-inline-input</a>.</p><p>The GitHub repository can be found <a href="https://github.com/ukchukx/svelte-inline-input">here</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=84274be1aa73" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Creating an inline editable component in Vue and publishing to NPM]]></title>
            <link>https://medium.com/@ukchukx/creating-an-inline-editable-component-in-vue-and-publishing-to-npm-ad7ef6403694?source=rss-5114de41076a------2</link>
            <guid isPermaLink="false">https://medium.com/p/ad7ef6403694</guid>
            <category><![CDATA[vue]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[components]]></category>
            <category><![CDATA[inline-editor]]></category>
            <dc:creator><![CDATA[Uk Chukundah]]></dc:creator>
            <pubDate>Mon, 13 Jan 2020 00:04:13 GMT</pubDate>
            <atom:updated>2020-01-13T00:15:25.355Z</atom:updated>
            <content:encoded><![CDATA[<p>While squashing some bugs on and making some updates to my <a href="https://github.com/ukchukx/address-book">address book</a>, I decided to change the input fields to the inline editable style found on Trello (show below), Google Sheets, etc.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/280/0*YKWiXkXkkdv_a7Ha.gif" /></figure><p>I’d like to use this component in other apps so we’ll be making it a standalone component in this tutorial.</p><p>Since this is a single component, it’s easier testing in an online sandbox like <a href="https://codesandbox.io/s/vue">this one on Sandbox.io</a> instead of creating a full-fledged app.</p><p>Firstly, we’ll create the folder and files we need by running the following commands:</p><pre>$ mkdir vue-inline-input<br>$ cd vue-inline-input<br>$ mkdir src build<br>$ touch .gitignore package.json build/rollup.config.js src/entry.js src/InlineInput.vue README.md</pre><p>Before jumping into writing the actual component, let’s take care of the git and build configurations.</p><p>The only thing we need to ignore in our .gitignore is the node_modules directory, so add it to the .gitignore file.</p><p>Our package.jsonwill contain:</p><pre>{<br>  &quot;name&quot;: &quot;vue-inline-input&quot;,<br>  &quot;version&quot;: &quot;1.0.0&quot;,<br>  &quot;description&quot;: &quot;A Vue component for inline editable inputs.&quot;,<br>  &quot;main&quot;: &quot;dist/vue-inline-input.ssr.js&quot;,<br>  &quot;module&quot;: &quot;dist/vue-inline-input.esm.js&quot;,<br>  &quot;unpkg&quot;: &quot;dist/vue-inline-input.min.js&quot;,<br>  &quot;files&quot;: [<br>    &quot;dist/*&quot;,<br>    &quot;src/**/*.vue&quot;<br>  ],<br>  &quot;scripts&quot;: {<br>    &quot;build&quot;: &quot;cross-env NODE_ENV=production rollup --config build/rollup.config.js&quot;,<br>    &quot;build:ssr&quot;: &quot;cross-env NODE_ENV=production rollup --config build/rollup.config.js --format cjs&quot;,<br>    &quot;build:es&quot;: &quot;cross-env NODE_ENV=production rollup --config build/rollup.config.js --format es&quot;,<br>    &quot;build:unpkg&quot;: &quot;cross-env NODE_ENV=production rollup --config build/rollup.config.js --format iife&quot;<br>  },<br>  &quot;author&quot;: &quot;Uk Chukundah&quot;,<br>  &quot;license&quot;: &quot;MIT&quot;,<br>  &quot;keywords&quot;: [<br>    &quot;vue&quot;,<br>    &quot;inline&quot;,<br>    &quot;input&quot;,<br>    &quot;editable&quot;<br>  ],<br>  &quot;repository&quot;: {<br>    &quot;type&quot;: &quot;git&quot;,<br>    &quot;url&quot;: &quot;git+https://github.com/ukchukx/vue-inline-input&quot;<br>  },<br>  &quot;devDependencies&quot;: {<br>    &quot;@rollup/plugin-buble&quot;: &quot;^0.21.0&quot;,<br>    &quot;@rollup/plugin-commonjs&quot;: &quot;^11.0.1&quot;,<br>    &quot;@rollup/plugin-replace&quot;: &quot;^2.3.0&quot;,<br>    &quot;core-js&quot;: &quot;^3.6.3&quot;,<br>    &quot;cross-env&quot;: &quot;^5.2.0&quot;,<br>    &quot;minimist&quot;: &quot;^1.2.0&quot;,<br>    &quot;rollup&quot;: &quot;^1.12.1&quot;,<br>    &quot;rollup-plugin-terser&quot;: &quot;^5.2.0&quot;,<br>    &quot;rollup-plugin-vue&quot;: &quot;^5.1.5&quot;,<br>    &quot;vue&quot;: &quot;^2.6.11&quot;,<br>    &quot;vue-template-compiler&quot;: &quot;^2.6.11&quot;<br>  }<br>}</pre><p>src/entry.js will have:</p><pre>// Import vue component<br>import component from &#39;./InlineInput.vue&#39;;</pre><pre>// install function executed by Vue.use()<br>function install(Vue) {<br>  if (install.installed) return;</pre><pre>  install.installed = true;<br>  Vue.component(&#39;InlineInput&#39;, component);<br>}</pre><pre>// Create module definition for Vue.use()<br>const plugin = { install };</pre><pre>// To auto-install when vue is found<br>/* global window global */<br>let GlobalVue = null;</pre><pre>if (typeof window !== &#39;undefined&#39;) {<br>  GlobalVue = window.Vue;<br>} else if (typeof global !== &#39;undefined&#39;) {<br>  GlobalVue = global.Vue;<br>}</pre><pre>if (GlobalVue) {<br>  GlobalVue.use(plugin);<br>}</pre><pre>// Inject install function into component - allows component<br>// to be registered via Vue.use() as well as Vue.component()<br>component.install = install;</pre><pre>// Export component by default<br>export default component;</pre><p>build/rollup.config.js will contain:</p><pre>// rollup.config.js<br>import vue from &#39;rollup-plugin-vue&#39;;<br>import buble from &#39;@rollup/plugin-buble&#39;;<br>import commonjs from &#39;@rollup/plugin-commonjs&#39;;<br>import replace from &#39;@rollup/plugin-replace&#39;;<br>import { terser } from &#39;rollup-plugin-terser&#39;;<br>import minimist from &#39;minimist&#39;;</pre><pre>const argv = minimist(process.argv.slice(2));</pre><pre>const baseConfig = {<br>  input: &#39;src/entry.js&#39;,<br>  plugins: {<br>    preVue: [<br>      replace({<br>        &#39;process.env.NODE_ENV&#39;: JSON.stringify(&#39;production&#39;),<br>      }),<br>      commonjs(),<br>    ],<br>    vue: {<br>      css: true,<br>      template: {<br>        isProduction: true,<br>      },<br>    },<br>    postVue: [<br>      buble(),<br>    ],<br>  },<br>};</pre><pre>// UMD/IIFE shared settings: externals and output.globals<br>// Refer to https://rollupjs.org/guide/en#output-globals for details<br>const external = [];<br>const globals = {<br>  // Provide global variable names to replace your external imports<br>  // eg. jquery: &#39;$&#39;<br>};</pre><pre>// Customize configs for individual targets<br>const buildFormats = [];<br>if (!argv.format || argv.format === &#39;es&#39;) {<br>  const esConfig = {<br>    ...baseConfig,<br>    output: {<br>      file: &#39;dist/vue-inline-input.esm.js&#39;,<br>      format: &#39;esm&#39;,<br>      exports: &#39;named&#39;,<br>    },<br>    plugins: [<br>      ...baseConfig.plugins.preVue,<br>      vue(baseConfig.plugins.vue),<br>      ...baseConfig.plugins.postVue,<br>      terser({<br>        output: {<br>          ecma: 6,<br>        },<br>      }),<br>    ],<br>  };<br>  buildFormats.push(esConfig);<br>}</pre><pre>if (!argv.format || argv.format === &#39;cjs&#39;) {<br>  const umdConfig = {<br>    ...baseConfig,<br>    external,<br>    output: {<br>      compact: true,<br>      file: &#39;dist/vue-inline-input.ssr.js&#39;,<br>      format: &#39;cjs&#39;,<br>      name: &#39;vue-inline-input&#39;,<br>      exports: &#39;named&#39;,<br>      globals,<br>    },<br>    plugins: [<br>      ...baseConfig.plugins.preVue,<br>      vue({<br>        ...baseConfig.plugins.vue,<br>        template: {<br>          ...baseConfig.plugins.vue.template,<br>          optimizeSSR: true,<br>        },<br>      }),<br>      ...baseConfig.plugins.postVue,<br>    ],<br>  };<br>  buildFormats.push(umdConfig);<br>}</pre><pre>if (!argv.format || argv.format === &#39;iife&#39;) {<br>  const unpkgConfig = {<br>    ...baseConfig,<br>    external,<br>    output: {<br>      compact: true,<br>      file: &#39;dist/vue-inline-input.min.js&#39;,<br>      format: &#39;iife&#39;,<br>      name: &#39;VueInlineInput&#39;,<br>      exports: &#39;named&#39;,<br>      globals,<br>    },<br>    plugins: [<br>      ...baseConfig.plugins.preVue,<br>      vue(baseConfig.plugins.vue),<br>      ...baseConfig.plugins.postVue,<br>      terser({<br>        output: {<br>          ecma: 5,<br>        },<br>      }),<br>    ],<br>  };<br>  buildFormats.push(unpkgConfig);<br>}</pre><pre>// Export config<br>export default buildFormats;</pre><p>Now we’re done with housekeeping, it’s time to dive into the actual component. This is a good place to create a <a href="https://github.com/ukchukx/vue-inline-input/commit/80e879c40043876ca0f1f94544b7384ad78870e1">commit</a>.</p><p>The default state of an inline editable component is to display a static element. When the component is clicked, it transforms into an input field that accepts user input. When focus goes away from the element, it toggles back to a static element.</p><p>Our component will handle text, number, select and textarea inputs.</p><p>We’ll leave styling up to users. At the least, you should show a pointer cursor when the mouse hovers over the static element.</p><h3>Number and text input</h3><pre>&lt;template&gt;<br>  &lt;input <br>    v-if=&quot;editing &amp;&amp; (isText || isNumber)&quot;<br>    :class=&quot;inputClasses&quot;<br>    :type=&quot;type&quot; <br>    :value=&quot;value&quot; <br>    :placeholder=&quot;placeholder&quot;<br>    ref=&quot;inputEl&quot;<br>    v-on:keyup.enter=&quot;handleEnter&quot;<br>    @input=&quot;handleInput&quot;<br>    @blur=&quot;handleBlur&quot;&gt;</pre><pre>  &lt;span :class=&quot;labelClasses&quot; v-else @click=&quot;toggle()&quot;&gt;<br>    {{ label }}<br>  &lt;/span&gt;<br>&lt;/template&gt;<br>&lt;script&gt;<br>export default {<br>  name: &#39;InlineInput&#39;,<br>  props: {<br>    value: {<br>      type: [Number, String],<br>      default: () =&gt; &#39;&#39; <br>    },<br>    type: {<br>      type: String,<br>      default: () =&gt; &#39;text&#39;<br>    },<br>    emitOnBlur: {<br>      type: Boolean,<br>      default: () =&gt; false<br>    },<br>    placeholder: {<br>      type: String,<br>      default: () =&gt; &#39;&#39;<br>    },<br>    labelClasses: {<br>      type: String,<br>      default: () =&gt; &#39;&#39;<br>    },<br>    inputClasses: {<br>      type: String,<br>      default: () =&gt; &#39;&#39;<br>    }<br>  },<br>  data() {<br>    return {<br>      editing: false<br>    };<br>  },<br>  computed: {<br>    isText() {<br>      return this.type === &#39;text&#39;;<br>    },<br>    isNumber() {<br>      return this.type === &#39;number&#39;;<br>    },<br>    label() {<br>      if (this.isNumber) return this.value === &#39;&#39; ? this.placeholder : this.value;<br>      if (this.isText) return this.value ? this.value : this.placeholder;<br>    }<br>  },<br>  methods: {<br>    toggle() {<br>      this.editing = !this.editing;<br>      <br>      if (this.editing) {<br>        this.$nextTick(() =&gt; {<br>          this.$refs.inputEl.focus();<br>        });<br>      }<br>    },<br>    handleEnter() {<br>      this.$refs.inputEl.blur();<br>    },<br>    handleBlur() {<br>      this.toggle();<br>      this.emitValue();<br>    },<br>    handleInput() {<br>      if (!this.emitOnBlur) this.emitValue();<br>    },<br>    handleChange() {<br>      this.emitValue();<br>    },<br>    emitValue() {<br>      this.$emit(&#39;input&#39;, this.isNumber ? parseFloat(this.$refs.inputEl.value) : this.$refs.inputEl.value);<br>    }<br>  }<br>};<br>&lt;/script&gt;</pre><p>Our default state is a static element. We’ll use a span as our static element. When the span is clicked, we hide the span and show our input element (via the @click handler on the span).</p><p>When the span is clicked, toggle() is called which does two things. It hides the span by setting editing to true and it places the focus on our input so it can accept user input without the user needed to click on the input again. That&#39;s one of the reasons we&#39;re holding a ref to the input via inputEl; the other reasons are to read its value directly (which is simpler than using v-model in this case) and take focus away from the input.</p><p>When focus leaves the input, we handle the blur event fired via handleBlur(). This function calls toggle() to hide the input and show the span and calls emitValue() to pass the input value back to the parent component.</p><p>We also want to toggle the component when the user presses the Enter key. We handle that via handleEnter() which just takes away focus from the input element which will cause handleBlur() to be called.</p><p>When the user changes the input value, we call handleInput(). It checks if the parent component wants us to only pass the input values after the user is done ( i.e. emitOnBlur is true) rather than in real-time (which is the default). If real-time updates are needed, we send the value to the parent component via emitValue().</p><p>handleChange() is for select inputs. It sends the selected value when the user makes a new selection.</p><p>emitValue() sends updates to the parent component by firing an input element. This enables the parent component to use the v-model directive to listen for updates. If type is set to number, we convert the value to a number before passing it along.</p><p>The inputClasses and labelClasses props are to give the user full control over styling as we&#39;re not going to do any styling.</p><p>Our label computed prop controls what is shown when the static element is shown. For number inputs, we only show placeholder when nothing has been input; otherwise we show the user input (this ensures that 0 is shown, for example). For text inputs, we show placeholder if value is empty.</p><p>That’s all that’s needed for text and number input. We’ll go ahead and create a commit <a href="https://github.com/ukchukx/vue-inline-input/commit/5cc167d7c7d698b3ec469243432f725c3e6fe45c">here</a>.</p><h3>Textarea</h3><pre>&lt;template&gt;<br>  &lt;!-- --&gt;</pre><pre>  &lt;textarea <br>    v-else-if=&quot;editing &amp;&amp; isTextArea&quot;<br>    :class=&quot;inputClasses&quot;<br>    :value=&quot;value&quot;<br>    :placeholder=&quot;placeholder&quot;<br>    ref=&quot;inputEl&quot;<br>    :rows=&quot;rows&quot;<br>    :cols=&quot;cols&quot;<br>    @input=&quot;handleInput&quot;<br>    @blur=&quot;handleBlur&quot;&gt;<br>  &lt;/textarea&gt;</pre><pre>  &lt;!-- --&gt;<br>&lt;/template&gt;<br>&lt;script&gt;<br>export default {<br>  // ...<br>  props: {<br>    // ...<br>    rows: {<br>      type: Number,<br>      default: () =&gt; 2<br>    },<br>    cols: {<br>      type: Number,<br>      default: () =&gt; 20<br>    }<br>  },<br>  // ...<br>  computed: {<br>    // ...<br>    isTextArea() {<br>      return this.type === &#39;textarea&#39;;<br>    },<br>    label() {<br>      // ...<br>      if (this.isText || this.isTextArea) return this.value ? this.value : this.placeholder;<br>    }<br>  },<br>  methods: {<br>  	// ...<br>  }<br>};<br>&lt;/script&gt;</pre><p>In textareas, Enter is a normal input and it would be bad UX to toggle the component when Enter is pressed. That’s the reason we handled Enter separately from other inputs. This way, we only have to not add the handler to the textarea, instead of modifying handleInput() to differentiate Enters from other input and textareas for number and text. This would make our function more complex and more error-prone.</p><p>The only addition is the rows and cols props to give the parent component control over sizing. They are initialized to their HTML default values if the parent component does not supply values.</p><p>That’s all that’s needed to support textareas. Let’s make a commit <a href="https://github.com/ukchukx/vue-inline-input/commit/ac26e632d46127c0bc84e2aaa037ecc7846db66a">here</a>.</p><h3>Select</h3><pre>&lt;template&gt;<br>  &lt;!-- --&gt;</pre><pre>  &lt;select <br>    v-else-if=&quot;editing &amp;&amp; isSelect&quot;<br>    :class=&quot;inputClasses&quot;<br>    :value=&quot;value&quot;<br>    ref=&quot;inputEl&quot; <br>    @change=&quot;handleChange&quot;<br>    @blur=&quot;handleBlur&quot;&gt;<br>    &lt;option v-if=&quot;placeholder&quot; disabled value&gt;{{ placeholder }}&lt;/option&gt;<br>    &lt;option <br>      :key=&quot;i&quot;<br>      v-for=&quot;(o, i) in options&quot; <br>      :value=&quot;o.value&quot;&gt;<br>      {{ o.label }}<br>    &lt;/option&gt;<br>  &lt;/select&gt;</pre><pre>  &lt;span v-else :class=&quot;labelClasses&quot; @click=&quot;toggle()&quot;&gt;<br>    {{ label }}<br>    &lt;slot name=&quot;selectCaret&quot;&gt;<br>      &lt;span v-if=&quot;isSelect&quot;&gt;&amp;#9660;&lt;/span&gt;<br>    &lt;/slot&gt;<br>  &lt;/span&gt;<br>&lt;/template&gt;<br>&lt;script&gt;<br>export default {<br>  name: &#39;InlineInput&#39;,<br>  props: {<br>    // ...<br>    options: {<br>      type: Array,<br>      default: () =&gt; []<br>    }<br>  },<br>  // ...<br>  computed: {<br>    // ...<br>    isSelect() {<br>      return this.type === &#39;select&#39;;<br>    },<br>    label() {<br>      // ...<br>      // Select<br>      return this.options<br>        .reduce((currLabel, { label, value }) =&gt; this.value === value ? label : currLabel, this.value);<br>    }<br>  },<br>  methods: {<br>  	// ...<br>  }<br>};<br>&lt;/script&gt;</pre><p>For selects we need an array of options which is supplied through the options prop, which is an array of objects that have label and value keys.</p><p>In the span element we show a caret to indicate that it’s a select. We added the caret in a named slot to enable the user change the default.</p><p>In our label computed prop, for selects we display the label of the currently selected value.</p><p>With that, we have added support for select inputs. As we&#39;ve done previously, we make a commit <a href="https://github.com/ukchukx/vue-inline-input/commit/44757696490fcdbc6839cdcb1b8f588b568f33a6">here</a>.</p><h3>Publishing to NPM</h3><p>Before we publish, we need to fill our README with helpful text and build the component.</p><p>To build the component, run:</p><pre>$ npm run build</pre><p>Our README content:</p><pre># vue-inline-input</pre><pre>&gt; An inline editable input component for Vue.</pre><pre>Displays as text and becomes editable by clicking or tapping.</pre><pre>## Installation</pre><pre>```js<br>npm install vue-inline-input<br>```</pre><pre>### Browser</pre><pre>```html<br>&lt;script type=&quot;text/javascript&quot; src=&quot;https://unpkg.com/vue&quot;&gt;&lt;/script&gt;<br>&lt;script type=&quot;text/javascript&quot; src=&quot;https://unpkg.com/vue-inline-input&quot;&gt;&lt;/script&gt;<br>&lt;script type=&quot;text/javascript&quot;&gt;<br>  Vue.use(InlineInput);<br>&lt;/script&gt;<br>```</pre><pre>### Module</pre><pre>```js<br>import InlineInput from &#39;vue-inline-input&#39;;<br>```</pre><pre>## Usage</pre><pre>Once installed, it can be used in a template as:</pre><pre>```html<br>&lt;inline-input v-model=&quot;amount&quot; /&gt;<br>```</pre><pre>See the props table below for the available options.</pre><pre>### Props</pre><pre>| Property | Type | Description | Default |<br>|:--|:--|:--|:--|<br>| type | string | The input type. Could be text, number, textarea or select | text |<br>| emit-on-blur | boolean | Save input changes only on blur | false |<br>| placeholder | string | Text to be shown as a placeholder while there is no input |  empty string |<br>| label-classes | string | CSS classes for the label element | empty string |<br>| input-classes | string | CSS classes for the input element | empty string |<br>| rows | integer | Textarea rows | 2 |<br>| cols | integer | Textarea columns | 20 |<br>| options | array | Provides the options for selects. Each object should have the format `{label: x, value: x}` | [] |</pre><pre>## Contribution<br>Install dependencies<br>```<br>npm install<br>```<br>When you&#39;re done, build the dist files<br>```<br>npm run build<br>```</pre><pre>## License</pre><pre>[MIT](http://opensource.org/licenses/MIT)</pre><p>Commit the <a href="https://github.com/ukchukx/vue-inline-input/commit/cdea413c39bfa667c6a91611309fafc29b29ea41">changes</a>.</p><p>To publish, I first login to my NPM <a href="https://www.npmjs.com/~ukchukx">account</a> with:</p><pre>$ npm login</pre><p>Then, from the root directory I run:</p><pre>$ npm publish</pre><p>After successfully publishing, we can use our component in Node.js projects by installing it with:</p><pre>$ npm install vue-inline-input</pre><p>or in the browser using <a href="https://unpkg.com/vue-inline-input">https://unpkg.com/vue-inline-input</a>.</p><p>The GitHub repository can be found <a href="https://github.com/ukchukx/vue-inline-input">here</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ad7ef6403694" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>