Monday, February 1, 2016

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

Secrets to Powerful Web Design Case Studies

If you don’t know about the power of case studies yet, pay close attention; they are about to become your best friend.

For the most part, case studies are a mainstay of nearly every industry. Companies of all types use case studies to show the world how they helped solve a problem or issue for one specific client.

Remember back in school when the teacher wanted you to show your work? A case study works on the same principle. Some clients want to get a “peek behind the curtain,” and see the processes involved in your work.

They want to see not only how the finished product looks, but also the entire process from start to finish.

  • How did you take a client’s problem and develop a solution?
  • How long did it take, and what was involved along the way?
  • What was your thought process, and what did you do in order to solve a client’s problem or achieve their goals?

These are some of the questions that are typically answered in case studies, and they provide a lot of insight for clients.

Case studies can also take many forms, and may not even be called case studies at all. For example, my website thedeependdesign.com refers to them as “Success Stories.” You can tailor your own phrase, creating something that’s engaging and works for you.

Regardless of titles, a case study tells the story of how you helped one specific client. This is important, because if a future client can identify with a past client – their problem, their goal, whatever it may be – they can see how you might help them in a similar way.

Strangely, very few freelancers seem to use case studies, while larger companies – especially in creative industries – are using them quite extensively. This is a real missed opportunity, but if you stop and think about it, this is great news for you.

If you are one of the only ones in your market to utilize case studies for your business, you can really stand out from the crowd. This will make you and your business that much more attractive to potential clients if you are one of the few people on board with using this technique.

By their nature, case studies also show that you understand and have experience in solving problems. They help show clients that you can take a unique situation, problem, or goal and create a process to help your client get exactly what they want.

Part 1: How to Craft a Compelling Web Design Case Study

Choose your subjects carefully.

The first step toward a great case study is choosing the right subject. If you have the luxury of a lot of past clients to choose from, it’s probably wise to choose an “everyman” client that the majority of your future clients can identify with. Someone that people can understand who has a problem or goal that a lot of other businesses share.

Highlight strong industry sectors.

Choosing a client from an obscure or complicated industry that will require lots of explanation will make it more difficult for potential clients to relate. If people can’t relate to your case studies, they're unlikely to be able to see you solving their problems.

Consumer-facing clients such as restaurants, retail shops or hotels often have easily recognizable goals and make for excellent case studies.

Also, keep in mind your target client base when picking your subject. Make sure you choose a candidate that will appeal to the types of clients you want to attract.

For example, if you happen to be successful in producing web design for the construction industry, try to stick to that area for your case study, or you run the risk of not relating to your bread-and-butter clients.

Being able to identify with the client in the case study is critical because we want the reader to be able to easily project themselves into the client’s shoes. You want them to read it, sit back and think ‘He did a great job for that guy, and I have similar issues. I bet he could help me too.’

However, if you’re newish business you may not have a long client list and so you won't be able to be as picky. But that’s okay – everyone starts somewhere, and as you gain more clients, you can write more and more case studies and get pickier as time progresses.

If you happen to be brand new, with no past clients to write a case study on, you can write a case study in real time. This can actually be a good thing, as you’ll be able to write the case study on a client you’re currently helping, and all the details will be fresh in your mind.

Get Writing!

Now that you have your client picked out, it’s time to start crafting. Remember, you want to tell a story from start to finish. Beginning with when your client first came to you –

+What was the problem or goal that drove them to you in the first place?

  • What did they need you to solve?
  • Did they need a logo designed, a press release written, or a brand new website designed?

Talk about any and all prerequisites that came with the project. For instance, a client may come to you wanting a website that can be easily updatable by their own staff, they want to bring in the colors and theme of their existing logo, or be able to collect email addresses.

These prerequisites all amount to limitations on your creativity. This is an excellent thing to show, as it tells future clients that you can operate within the boundaries of what your clients ask for.

You should also include other unspoken considerations that you took into account during the process. This could include industry-standard features that you happened to uncover in your research.

A good example of this would be if a new restaurant wanted you to build a website for them, and you found out during your research phase that most restaurants are using a service called “OpenTable” to take online reservations.

Talk about:

  • Everything that was required.
  • Everything they specifically asked for.
  • Things that you found out on your own.

Include how you took all these things into account as you came up with a solution for the final product. Explain your thought process behind your decisions and show how your decisions influenced and benefited the project and the client.

Quantify whenever you can.

Always include real, accurate numbers whenever you can. It’s one thing to say “My web design contributed to the construction firm’s success.’, but it’s much better to say ‘The website I designed for XYZ client gets 10,000 unique visitors a month, with 10% of them converted into sales leads.”

Laptop

These are quantifiable statistics that future clients can read and easily understand. Visitors don’t have to wonder what it actually means, or think about your statements in an abstract way – it’s real world data that is easily interpreted.

They want to know that if they hire you for a project, that you’ll get them results. And real results are measured in numbers, not in warm fuzzy feelings.

Part 2: How to Present Your Case Studies

One you've determined the content for an effective case study, it’s time to focus on the presentation. People aren't looking to read a 400-page novel about your past clients, so it’s important to present case studies in an easily digestible way and will make people want to read them.

First and foremost, you want to make sure your case studies are formatted correctly for the web, and specifically, for your website. Think about some of the blogs and other websites that present a large amount of information – most of them do an excellent job of being able to present it in such a way that’s easy to navigate and read. They do this by breaking up the content into bite-sized chunks.

Break it Up.

Breaking up paragraphs is an easy way to start. It looks much nicer to the reader’s eye, and it’s easier to read than just one giant wall of text. Too much text looks intimidating, and quite frankly like a chore to read.

Breaking it up into paragraphs makes it look much more accessible, and potential clients can jump around to see which paragraphs interest them the most if they don’t feel like reading the entire page.

Use headers.

Also, use headings and subheadings where appropriate. These allow you to break up your content even further, and also enhance a reader’s ability to scan and find exactly what interests them. For the most part, people aren’t usually going to read the entire case study. People’s reading habits online are actually pretty lazy – so most people are just going to scan the content and read what appeals to them specifically.

Use lists.

Do you have information is your case study that could be formatted as a list? Lists and bullet points are an effective way to make content easy to consume.

Bullet points are particularly well-suited for listing the specific requirements of the project, features you implemented, or statistics about how the project benefitted your client.

Use images.

Always use images wherever you can – show the different stages of the projects alongside your content if at all possible. Anytime you can show rather than tell, it’s a good thing.

[caption id="attachment_123752" align="aligncenter" width="1180"]Case study layout Credit: Forge and Smith[/caption]

If you can show your projects in as many stages as possible, do so. For instance, if you worked on a logo, you might want to show screenshots of your beginning sketches.

Continue reading %Secrets to Powerful Web Design Case Studies%


by Wes McDowell via SitePoint