• This repository has been archived on 09/Nov/2017
  • Stars
    star
    403
  • Rank 103,401 (Top 3 %)
  • Language
    JavaScript
  • License
    MIT License
  • Created over 10 years ago
  • Updated over 8 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Generate a Passport.js authentication layer for your Sails app that will Rock Your Socks™

image_squidhome@2x.png

sails-generate-auth

Release Code Climate Dependency Status Downloads

⚠️ OBS: This generator is not currently maintained. Check out https://github.com/tjwebb/sails-auth for an actively maintained project based on this generator.

A Passport.js-based authentication generator for use with the Sails command-line interface.

So, how easy is it to use? Say you wanted to add Twitter authentication to our app for example – this is all you'd need:

twitter: {
  name: 'Twitter',
  protocol: 'oauth',
  strategy: require('passport-twitter').Strategy,
  options: {
    consumerKey: 'your-consumer-key',
    consumerSecret: 'your-consumer-secret'
  }
}

This sets you up with an authentication endpoint at /auth/twitter as well as a callback at /auth/twitter/callback - easy, huh?

Behind the scenes, the service uses the concept of "Passports" to store everything related to user authentication. This allows you to keep your own models free of authentication-related bloat as well as help you optimize your application as the data is queried separately only when authentication happens.

I do encourage you to read through the entire source – everything's very well documented, so it should be an easy read.

Installation

Certain generators are installed by default in Sails, but they can be overridden. Check the Sails docs for information on installing generator overrides / custom generators.

In order to use a generator you will need the latest Sails, ~0.10, which can be installed with:

npm install sails -g

Once that's all set, install the generator:

$ npm install sails-generate-auth

Production Usage

On the command line
$ sails generate auth
In a node script
var path = require('path');
var sailsgen = require('sails-generate');
var scope = {
	rootPath: path.resolve(__dirname)
};
sailsgen(require('sails-generate-auth'), scope, function (err) {
	if (err) throw err;

	// It worked.
});
Requirements

The only requirements, besides running the generator and adding some providers in config/passport.js, is having a set of routes that exposes the authentication endpoints. You'll also need to load the Passport.js middleware for all your controllers and install the required npm packages. Lastly, you need to add a line to config/bootstrap.js to load your Passport providers on startup.

For the routes, this is what you'll need to add to your config/routes.js file:

'get /login': 'AuthController.login',
'post /logout': 'AuthController.logout',
'get /register': 'AuthController.register',

'post /auth/local': 'AuthController.callback',
'post /auth/local/:action': 'AuthController.callback',

'get /auth/:provider': 'AuthController.provider',
'get /auth/:provider/callback': 'AuthController.callback',
'get /auth/:provider/:action': 'AuthController.callback',

Next, change your config/bootstrap.js to load your Passport providers on startup by adding the following line:

sails.services.passport.loadStrategies();

All required Passport.js middleware is contained within the passport policy so all you need to do is load it before your controllers in config/policies.js:

'*': [ 'passport', /* your auth dependant policies go here */ ]

Lastly, you will need to install the passport, bcryptjs and validator packages from npm for everything to work correctly.

If you want to make use of the error messages, you'll also need to add the following locale definitions (example translations provided):

{
  "Error.Passport.Password.Invalid": "The provided password is invalid!",
  "Error.Passport.Password.Wrong": "Whoa, that password wasn't quite right!",
  "Error.Passport.Password.NotSet": "Oh no, you haven't set a password yet!",
  "Error.Passport.Username.NotFound": "Uhm, what's your name again?",
  "Error.Passport.User.Exists": "This username is already taken.",
  "Error.Passport.Email.NotFound": "That email doesn't seem right",
  "Error.Passport.Email.Missing": "You need to supply an email-address for verification",
  "Error.Passport.Email.Exists": "This email already exists. So try logging in.",
  "Error.Passport.Username.Missing": "You need to supply a username",
  "Error.Passport.Password.Missing": "Oh no, you haven't set a password yet!",
  "Error.Passport.Generic": "Snap. Something went wrong with authorization."
}

sails-generate-auth, by default doesn't deny access to controllers if the user is not logged in. For that, you can create another policy (for example: sessionAuth) in api/policies/ and add it to config/policies as follows:

 '*': ['passport', 'sessionAuth'],

 'auth': {
    '*': ['passport']
  }

This helps to restrict access to all the controller except auth controller actions such as login, logout and register, if the user is not logged in. See this issue and stackoverflow answer for more details.

For controller actions which are accessed via APIs, you can add bearerAuth (available in api/policies). This policy ensures that the API is secure and only requests containing a bearer token can access them.

Questions?

See FAQ.md.

More Resources


Copyright © 2014-2015 Kasper Kronborg Isager. Licensed under the terms of the MIT license.

More Repositories

1

php-dockerized

Dockerized PHP development stack: Nginx, MySQL, MongoDB, PHP-FPM, HHVM, Memcached, Redis, Elasticsearch and RabbitMQ
PHP
1,094
star
2

vanilla-bootstrap

Kickstart your Vanilla-powered community forums with a fresh and solid theme that is ready to be customized to your heart's desires.
CSS
175
star
3

picnic

Picnic is a gorgeous documentation template for Jekyll
CSS
71
star
4

vanilla-api

Extensible RESTful API shim for Vanilla that operates in JSON or XML with support for JSONP and CORS
PHP
49
star
5

swing-mvc

A simple example of a JavaFX-esque MVC micro-framework for Swing applications
Java
26
star
6

zsh-pure

Minimal Oh My Zsh theme based on the fantastic Pure prompt by Sindre Sorhus.
22
star
7

vanilla-ninja

Ninja is a super sneaky Node.js, Gulp, and Bower powered scaffold for building superb Vanilla themes, superseded by my Yeoman generator for Vanilla
CSS
20
star
8

hamming-lsh

An implementation of locality-sensitive hashing for Hamming space
JavaScript
15
star
9

vanilla-dockerized

A Dockerized single-node Vanilla Forums setup ready for take-off
PHP
12
star
10

vanilla-oembed

OEmbed enables you to embed content from a myriad of providers in Vanilla comments and discussions.
PHP
7
star
11

vanilla-apptastic

Experimental Vanilla theme built on Bootstrap.
CSS
7
star
12

generator-java

Generic Java generator with out-of-the-box support for Gradle, JUnit, Groovy Console, and Checkstyle
JavaScript
5
star
13

microstack

Automated, scalable, and secure infrastructure stack for microservies on DigitalOcean
SaltStack
5
star
14

vanilla-epiceditor

An editor plugin for Vanilla that uses EpicEditor, an embeddable JavaScript Markdown editor.
CSS
5
star
15

handlebars-spec

The Handlebars.js specification converted to JSON, ready for cross-platform consumption.
JavaScript
4
star
16

hemingway

Implementations of the classic and covering locality-sensitive hashing schemes for Hamming space
C++
4
star
17

metalsmith-myth

Metalsmith plugin to preprocess CSS files with Myth.
JavaScript
4
star
18

vanilla-bootstrapmarkdown

Editor plugin for Vanilla using the Bootstrap Markdown jQuery plugin.
JavaScript
3
star
19

generator-vanilla

A Yeoman generator for Vanilla that will make your Application, Plugin, and Theme development a breeze.
JavaScript
3
star
20

docpad-plugin-tree

DocPad plugin that when given a collection will construct a hierarchical tree of documents. Perfect for navigation menus!
JavaScript
3
star
21

doem

A functional DOM traversal and manipulation library for modern browsers
JavaScript
3
star
22

kelvin-maps

Second semester university project: A mapping application for OpenStreetMap data
Java
3
star
23

vanilla-timeago

Adds automatically updating fuzzy timestamps throughout Vanilla using Timeago by Ryan McGeary.
PHP
3
star
24

ag

A set of abstract accessibility guidelines to describe all the things
2
star
25

vanilla-mediumeditor

An entirely new editing experience for Vanilla using the MediumEditor plugin by Davi Ferreira.
JavaScript
2
star
26

bookie

First semester university project: Ticket reservation for movie theaters
Java
2
star
27

dotfiles

$HOME is where the heart is
Scheme
2
star
28

chord

A simple Java implementation of a Chord peer-to-peer network
Java
2
star
29

bosh-paper

Paper on the Bosh shell for the BOSC course at the IT University of Copenhagen
TeX
2
star
30

vanilla-wysihtml5

The most awesome WYSIWIG editor for Vanilla utilizing Wysihtml5 by Xing. Deprecated in favour of the "Advanced Editor" plugin.
JavaScript
2
star
31

tex-dockerized

Effortless LaTeX compilation leveraging Docker and Compose
TeX
2
star
32

bundstreg

Functional and performant alternatives to many native JavaScript methods and then some
JavaScript
2
star
33

csharp-boilerplate

Cross-platform DNX-based C# boilerplate configured with xUnit
C#
2
star
34

bosh

A simple Unix shell that probably won't blow up your system
C
2
star
35

smk-data-explorer

Experimental web front-end to the "Statens Museum for Kunst" Solr-backed database.
JavaScript
2
star
36

nomads

A collection of useful monads for JavaScript
JavaScript
1
star
37

picklem

Pickle your DOM and CSS and enjoy them outside the confines of your least favorite browser
JavaScript
1
star
38

allie

Utilities for working with accessibility conformance testing
JavaScript
1
star
39

uforanderlig

Simple and efficient JavaScript implementations of common persistent data structures
JavaScript
1
star
40

hemingway-paper

Paper on the Hemingway library for the SAAS course at the IT University of Copenhagen
TeX
1
star
41

krome

A collection of useful abstractions on top of the Chrome Platform APIs
JavaScript
1
star
42

hoardom

A hoarding DOM element abstraction that memoizes all the things
JavaScript
1
star
43

union

A Go implementation of a union-find data structure
Go
1
star
44

fsharp-boilerplate

Cross-platform DNX-based F# boilerplate configured with xUnit and FsUnit
F#
1
star
45

vue-relation

A set of Vue.js mixins for modelling relations between components
JavaScript
1
star
46

fixt

DOM test fixtures made as easy as they ought to be
TypeScript
1
star
47

donkey

A simple and unfancy database agnostic ORM written on top of JDBC
Java
1
star
48

kuloer

A lightning-fast CSS color parsing and manipulation library with a tiny footprint
JavaScript
1
star
49

pak

A reasonably fast optimizing compiler for unfancy web pages and applications
Go
1
star
50

bassine

An asynchronous and bounded resource pool for generic objects
JavaScript
1
star
51

foreman

This is definitely not the build system you're looking for
TypeScript
1
star
52

baenk

A simple and no-frills benchmarking library for JavaScript
JavaScript
1
star
53

vanilla-wordcount

Provides word and character counts when composing discussions and comments in Vanilla.
JavaScript
1
star
54

chromium

Primitives for managing headless Chromium processes
Go
1
star
55

esthree

A Promise-based S3 abstraction layer around the official AWS SDK
JavaScript
1
star
56

typedown

Turn TypeScript projects into beautiful Markdown documentation
TypeScript
1
star
57

concordance-theme-ava

A Concordance theme extracted from Ava
TypeScript
1
star
58

partitionist

An orchestrator for flexible and efficient immutable server upgrades
Go
1
star
59

pqueue

A Go implementation of a priority queue data structure
Go
1
star
60

typecomp

A multi project TypeScript language service abstraction
TypeScript
1
star
61

presentation-coding-for-accessibility

A short introduction to the whys and hows of writing accessible UI
HTML
1
star
62

presentation-postcss

An introduction to the many new specifications in CSS and post-processing
JavaScript
1
star
63

vanilla-styleguide

Living styleguide generator for KSS documented Vanilla themes.
PHP
1
star
64

presentation-tooling

My presentation on front-end tooling from the js-montreal meetup in May '14.
HTML
1
star
65

vanilla-livereload

A simple LiveReload client plugin for Vanilla.
PHP
1
star