Monday, February 1, 2016

PhoneGap Day US 2016 Resources

Adobe – Lehi, Utah

This year’s PhoneGap Day US event was held at the Adobe office in Lehi, Utah (just outside Salt Lake City) for the first time ever. The location offered beautiful scenery and provided attendees with a chance to ski or take in a film at the Sundance film festival. The event was truly awesome overall and I wanted to share some info and links to check out if you weren’t able to attend or want to review what you learned.

PhoneGap Day Workshops

The event started off with a day of sold out workshops. We had 3 tracks with a variety of workshops from members of the PhoneGap team, the community and sponsors. The day was packed with lots of material covered in a brief period of time. Below are some links to tutorials, slides and content (including from my own workshop).

Resources

PhoneGap Day Sessions

The PhoneGap Day event itself was also jam-packed with some really great speakers and presentations. Below are some links I managed to find and share from some of those sessions. Some of the links are also to projects mentioned in the talks so you can try them or read up further.

Resources

More to Come…

Videos from the event will be posted on the PhoneGap blog soon and I will link to them here too when available. Please post a comment with any more resources to share from the event as well.

Also, there’s still one more chance to catch a PhoneGap Day event this year. We’ll be hosting PhoneGap Day EU in Amsterdam May 19th/20th. Check out the website for details and registration links!

Sudance Mountain

sundance


by Holly Schinsky via Devgirl's Weblog

User Authentication with the MEAN Stack

In this article we’re going to look at managing user authentication in the MEAN stack. We’ll use the most common MEAN architecture of having an Angular single page app using a REST API built with Node, Express and MongoDB.

When thinking about user authentication, we need to tackle the following things:

  1. Let a user register
  2. Save their data, but never directly store their password
  3. Let a returning user log in
  4. Keep a logged in user’s session alive between page visits
  5. Have some pages that can only been seen by logged in users
  6. Change output to the screen depending on logged in status (e.g. a “login” button or a “my profile” button)

Before we dive into the code, let’s take a few minutes for a high level look at how authentication is going to work in the MEAN stack.

The MEAN Stack Authentication Flow

So what does authentication look like in the MEAN stack?

Still keeping this at a high level, these are the components of the flow:

  • User data is stored in MongoDB, with the passwords hashed
  • CRUD functions are built in an Express API - Create (register), Read (login, get profile), Update, Delete
  • An Angular application calls the API and deals with the responses
  • The Express API generates a JSON Web Token (JWT, pronounced “Jot”) upon registration or login, and passes this to the Angular application
  • The Angular application stores the JWT in order to maintain the user’s session
  • The Angular application checks the validity of the JWT when displaying protected views
  • The Angular application passes the JWT back to Express when calling protected API routes

JWTs are preferred over cookies for maintaining the session state in the browser; cookies are better for maintaining state when using a server-side application.

The Example Application

The code for this article is available on GitHub. To run the application, you will need to have Node.js installed, along with MongoDB (For instructions on how to install, please refer to Mongo’s official documentation — Windows, Linux, MacOS).

The Angular App

To keep the example in this article simple, we’ll start with an Angular SPA with four pages:

  1. Homepage
  2. Register page
  3. Login page
  4. Profile page

The pages are pretty basic and look like this to start with:

Screenshots of the app

The profile page will only be accessible to authenticated users. All of the files for the Angular app are in a folder inside the Express app called app_client, and is arranged like this:

Screenshot of app_client folder structure

There is a Gulp process to concatenate all of the JavaScript files into app.min.js.

The REST API

We’ll also start off with the skeleton of a REST API built with Node, Express and MongoDB, using Mongoose to manage the schemas. This API has three routes:

  1. /api/register (POST) - to handle new users registering
  2. /api/login (POST) - to handle returning users logging in
  3. /api/profile/USERID (GET) - to return profile details when given a USERID

The code for the API is all held in another folder inside the Express app, called app_api. This holds the routes, controllers and model, and is organized like this:

Screenshot of app_api folder structure

At this starting point each of the controllers simply responds with a confirmation, like this:

module.exports.register = function(req, res) {
  console.log("Registering user: " + req.body.email);
  res.status(200);
  res.json({
    "message" : "User registered: " + req.body.email
  });
};

Okay, let’s get on with the code, starting with the database.

Creating the MongoDB Data Schema with Mongoose

There’s a simple user schema defined in /app_api/models/users.js. It defines the need for an email address, a name, a hash and a salt - the hash and salt will be used instead of saving a password. The email is set to unique as we’ll use it for the login credentials. Here’s the schema.

var userSchema = new mongoose.Schema({
  email: {
    type: String,
    unique: true,
    required: true
  },
  name: {
    type: String,
    required: true
  },
  hash: String,
  salt: String
});

Managing the Password without Saving It

Saving user passwords is a big no-no. Should a hacker get a copy of your database you want to make sure that they can’t use it to log in to accounts. This is where the hash and salt come in.

The salt is a string of characters unique to each user. The hash is created by combining the password provided by the user and the salt, and then applying one-way encryption. As the hash cannot be decrypted, the only way to authenticate a user is to take the password, combine it with the salt and encrypt it again. If the output of this matches the hash, then the password must have been correct.

To do the setting and the checking of the password we can use Mongoose schema methods - these are essentially functions that you add to the schema. These will both make use of the Node.js crypto module.

At the top of the users.js model file, require crypto so that we can use it:

var crypto = require('crypto');

Nothing needs installing as crypto ships as part of Node. Crypto itself has several methods; we’re interested in randomBytes to create the random salt and pbkdf2Sync to create the hash (there’s much more about Crypto in the Node.js API docs).

Setting the Password

To save the reference to the password we can create a new method called setPassword on the userSchema schema that accepts a password parameter. The method will then use crypto.randomBytes to set the salt, and crypto.pbkdf2Sync to set the hash.

userSchema.methods.setPassword = function(password){
  this.salt = crypto.randomBytes(16).toString('hex');
  this.hash = crypto.pbkdf2Sync(password, this.salt, 1000, 64).toString('hex');
};

We’ll use this method when creating a user; instead of saving the password to a password path we will be able to pass it to the setPassword function to set the salt and hash paths in the user document.

Checking the Password

Checking the password is a similar process, but we already have the salt from the Mongoose model. This time we just want to encrypt the salt and the password and see if the output matches the stored hash.

Add another new method to the users.js model file, called validPassword.

userSchema.methods.validPassword = function(password) {
  var hash = crypto.pbkdf2Sync(password, this.salt, 1000, 64).toString('hex');
  return this.hash === hash;
};

Generating a JSON Web Token (JWT)

One more thing that the Mongoose model needs to be able to do is generate a JWT, so that the API can send it out as a response. A Mongoose method is ideal here too, as it means we can keep the code in one place and call it whenever needed - we’ll need to call it when a user registers and when a user logs in.

To create the JWT we’ll use a module called jsonwebtoken which needs to be installed in the application, so run this on the command line:

npm install jsonwebtoken --save

And then require this in the users.js model file:

var jwt = require('jsonwebtoken');

This module exposes a sign method that we can use to create a JWT, simply passing it the data we want to include in the token, plus a secret that the hashing algorithm will use. The data should be sent as a JavaScript object, and include an expiry date in an exp property.

Adding a generateJwt method to userSchema in order to return a JWT looks like this:

userSchema.methods.generateJwt = function() {
  var expiry = new Date();
  expiry.setDate(expiry.getDate() + 7);

  return jwt.sign({
    _id: this._id,
    email: this.email,
    name: this.name,
    exp: parseInt(expiry.getTime() / 1000),
  }, "MY_SECRET"); // DO NOT KEEP YOUR SECRET IN THE CODE!
};

Note: It is important that your secret is kept safe - only the originating server should know what it is. It is best practice to set the secret as an environment variable, and not have it in the source code, especially if your code is stored in version control somewhere.

That’s everything we need to do with the database.

Setup Passport to Handle the Express Authentication

Passport is a Node module that simplifies the process of handling authentication in Express. It provides a common gateway to work with many different authentication “strategies”, such as logging in with Facebook, Twitter or Oauth. The strategy we’ll use is called “local”, as it uses a username and password stored locally.

To use Passport, first install it and the strategy, saving them in package.json.

npm install passport --save
npm install passport-local --save

Configure Passport

Inside the app_api folder create a new folder config and create a file in there called passport.js. This is where we define the strategy.

Before defining the strategy this file needs to require Passport, the strategy, Mongoose and the User model.

var passport = require('passport');
var LocalStrategy = require('passport-local').Strategy;
var mongoose = require('mongoose');
var User = mongoose.model('User');

For a local strategy we essentially just need to write a Mongoose query on the User model. This query should find a user with the email address specified, and then call the validPassword method to see if the hashes match. Pretty simple.

There’s just one curiosity of Passport to deal with. Internally the local strategy for Passport expects two pieces of data called username and password. However we’re using email as our unique identifier, not username. This can be configured in an options object with a usernameField property in the strategy definition. After that, it’s over to the Mongoose query.

Continue reading %User Authentication with the MEAN Stack%


by Simon Holmes via SitePoint

Web Design Weekly #220

Headlines

Why I love working with the web

Remy Sharp shares his excitement about why he loves web work. Whilst reading this post I found myself agreeing with pretty much everything and feeling excited to be a web developer. A great reminder that we are truly lucky to be working in such a powerful space. (remysharp.com)

React and the economics of dynamic web interfaces (nczonline.net)

​Get multiple job offers from top companies with 1 application

​Web developers are in demand, so shouldn’t companies apply to you? On Hired, that’s exactly how it works. Get 5+ job offers from companies like Uber, Square, and Facebook with 1 application. Join Hired today and get a $1,000 bonus when you get a job! (hired.com)

Articles

The Year of Web Streams

A pretty bold call by Jake Archibald but a great introduction to what maybe a game changer, especially for improving the performance of content-heavy sites. (jakearchibald.com)

Aligning your Front End Process

Ashley Nolan shares some great advice to help keep projects and developers aligned and large codebases better structured. (ashleynolan.co.uk)

The state of hidden content support in 2016

Steve Faulkner quickly recaps on the current state of the ‘aria-hidden’ and the HTML5 ‘hidden’ attribute in all major browsers and screen readers. (paciellogroup.com)

Mood Driven Development (css-tricks.com)

Tools / Resources

Responsive Image Breakpoints Generator

This awesome tool enables you to upload your images and define settings to find matching image dimensions that fit in your graphic design requirements. If you are keen to find out more, Nadav Soferman’s and Jason Grigsby’s posts are worth reading. (responsivebreakpoints.com)

Vivus, bringing your SVGs to life

A lightweight JavaScript class (with no dependencies) that allows you to animate SVGs, giving them the appearance of being drawn. (github.io)

Performance Budget Builder

Brad Frost has created a very handy tool that helps visualise the performance budget of your site. To create your own, just ‘fork’ his CodePen demo. (bradfrost.com)

DevTools Author

If you use the Chrome DevTools as your front-end development environment, DevTools Author provides a small set of options to enhance your authoring experience that you might enjoy. (mikeking.io)

A Gulp-Based External SVG Symbol Sprite Icon System (una.im)

Hint.css – A CSS only tooltip library (kushagragour.in)

ES6 Cheatsheet (github.com)

React.js Best Practices for 2016 (risingstack.com)

Inspiration

The A11Y Project gets a major redesign

A great open source project that just got a fresh coat of paint. If you have time it is also worth reading about the decisions that went into it. (a11yproject.com)

The State of UX in 2016 (medium.com)

Jobs

Front End Developer – Xero

Located in Melbourne, the role of the Front End Developer exists to undertake software application development of new or improved features in Xero and its associated applications and service delivery systems. (Xero.com)

Design Engineer at Help Scout

As a design engineer at Help Scout, it’s your job to create not only a pixel-perfect experience for customers, but to do so by writing front-end code that’s clean, performant and consistent with the standards we’ve established as a team. Along with four other tight-knit designers on the team, you’ll be responsible for moving our brand and user experience forward. (helpscout.net)

Need to find passionate developers? Why not advertise in the next newsletter

Last but not least…

Disable npm progress to dramatically speed up installs (twitter.com)

Which cat is your JavaScript framework? (whichcatisyourjavascriptframework.com)

The post Web Design Weekly #220 appeared first on Web Design Weekly.


by Jake Bresnehan via Web Design Weekly

Publishing a Plugin to the WordPress Plugin Directory

In 2001, a blog tool called b2/cafelog was launched by Michel Valdrighi. Matt Mullenweg and Mike Little forked b2/cafelog and created WordPress in 2003. According to WordPress.org, “WordPress was born out of a desire for an elegant, well-architectured personal publishing system built on PHP and MySQL and licensed under the GPL”. In 2004, plugins were introduced to extend WordPress’ core functionality. Here’s what the WordPress Plugin Directory looked like in November 2004:

WP-Plugins.net; Old WordPress Plugin Directory November 2004
Source: http://ift.tt/1Q8hzVE

At that point in 2004, there were 46 plugins available for WordPress. In just under eleven years, there are now over 42,697 plugins available in the WordPress Plugin Directory and there have been over 1,161,033,914 plugin downloads. Here’s what the WordPress Plugin Directory looks like in January 2016:

WordPress Plugin Directory Jan 2016

All of the plugins that appear in the WordPress Plugin Directory are free to use and distribute. They are licensed under the General Public License (GPL). Many pioneers have published plugins in the WordPress Plugin Directory and my brother and I wanted to be a part of this exclusive club. We’ll give you an inside look at the WordPress Plugin Directory submission process by sharing our experience on deciding to create, creating, and publishing a plugin in the WordPress Plugin Directory. We'll also provide step-by-step instructions on how to add your plugin to WordPress’ central Subversion repository for both Mac and Windows users.

Continue reading %Publishing a Plugin to the WordPress Plugin Directory%


by Ben Shadle via SitePoint

Projects That Are Making Blazing Fast Ruby a Reality

Speed design over white background, vector illustration.

Ruby is still not big in the scientific computing or artificial intelligence communities. However, that could soon change as there are two major projects on the horizon that could give Ruby a pick-up in 2016.

OMR

The OMR project is an open source (soon) initiative to develop reusable and consumable components from the IBM J9 virtual machine. These components will be used for any desired language runtime, including Ruby. The hope is that this will lower the barrier of entry for implementing languages.

Here are some things the project plans to bring:

  1. JIT compiler
  2. Enterprise-grade garbage collector
  3. Method profiler

Right now speedups are modest - in the 1x - 3x range. However, IBM is focusing on compatibility, rather than performance, to ease adoption. Also, they claim to already be able to run Rails.

IBM has posted a technology preview of their OMR Ruby implementation to GitHub.

Continue reading %Projects That Are Making Blazing Fast Ruby a Reality%


by Robert Qualls via SitePoint

Watch: Canva vs Canva For Work

In this screencast, I'll explore Canva for Work, the paid, professional version of Canva, a free grapics creation application.

You'll learn what the key differences are between the standard, free version of Canva and the newer Canva for Work. You will discover how it can give your brand a more consistent look, while simultaneously helping your team to work more efficiently. New features such as the Team Stream and Brand Kit may prove pivotal to your team's collaboration on beautiful, on-brand graphics projects, quickly and effortlessly. Come away with a firm understanding of both products and their differences, and make an informed decision about which you need, confidently!

Loading the player...

Continue reading %Watch: Canva vs Canva For Work%


by Lisa Larson-Kelley via SitePoint

Building OctoberCMS Form Field Widgets like a Pro

OctoberCMS logo

Creating your business website with any CMS requires you to make the back-end user friendly, and that means making the forms meaningful and accessible. In this article, we’re going to explore OctoberCMS form widgets and create a widget called UniqueValue, which helps the user enter a unique value. This could be useful for entering emails, usernames, post slugs, etc. Let’s get started.

Available Form Widgets

OctoberCMS provides a list of simple field types like email input, password, dropdown options, etc. The documentation has a list of all available fields. Moreover, the CMS provides some custom widgets like the media manager widget which lets you select an item from your media library or the WYSIWYG editor, Markdown editor, etc.

An interesting widget we should mention here is the repeater widget. Let’s say you have a recipes website. The cook will enter the recipe name and start filling in the ingredients. You might ask the user “how many ingredients do you need?” and based on that, you can generate the form fields. Another clean way to do it is to have a button at the bottom of the form that says Add new ingredient, which will generate the necessary fields for the cook when needed.

Here is an example configuration for the recipe form:

// models/recipe/fields.yaml

fields:
    name:
        label: Name
        type: text
        required: true
    ingredients:
        label: Ingredients
        type: repeater
        prompt: Add new ingredient
        form:
            fields:
                ingredient:
                    label: Ingredient
                    type: text
                how_much:
                    label: How much
                    type: number
                unit:
                    label: Unit
                    type: dropdown
                    options:
                        spoon: Spoon
                        ounce: Ounce
                        # etc

ingredients

Continue reading %Building OctoberCMS Form Field Widgets like a Pro%


by Younes Rafie via SitePoint