Giter VIP home page Giter VIP logo

sails-hook-authorization's Introduction

sails-hook-authorization

Hook that provides jwt authentication sails-compatible scheme, such as policies, routes, controllers, services. Based on https://github.com/saviogl/sails-hook-jwt-auth

Installation

npm install sails-hook-authorization --save

Configuration

This hook has support for working with wetland assuming you're using the wetland hook for sails. You can enable this by adding the following in config/auth.js:

module.exports.auth = {
  wetland: true
};

Options

This hook supports configuration options to make it fit into your application.

module.exports.auth = {

  // Your implementation for sending out the verification email
  sendVerificationEmail: (user, activateToken) => {
    // @todo implement
  },

  // Options concerning a user's identity
  identityOptions: {

    // Property to use for login (one of "email" or "username").
    loginProperty: 'username',

    // Parameters for user sign-up. @see https://www.npmjs.com/package/request-helpers
    parameterBlueprint: ['username', {param: 'email', required: false}],

    // Option to define which relations to populate on the user find
    // can be an array (of relations), a string (single relation), or a boolean (all or nothing).
    populate: true,

    // Whether or not you wish to require a user to validate their email address before being able to log in.
    requireEmailVerification: false
  },

  jwt: {
    // Properties to store on the token. Useful for instance to store the user's role, or language.
    // Accepts nested arguments. E.g.: ['role', {locale: ['language', 'locale']}]
    payloadProperties: [],
    
    // Time to live for the access token
    accessTokenTtl: 86400,  // 1 day
    
    // Time to live for the refresh token
    refreshTokenTtl: 2592000, // 30 days
    
    // The secret used to sign tokens with.
    secret: 'superSecretKeyForJwt'
  },

  // If you're using wetland (requires different query types)
  wetland: true
};

Service

This module globally expose a service which integrates with the jsonwebtoken (https://github.com/auth0/node-jsonwebtoken) and provide the interface to apply the jwt specification (http://self-issued.info/docs/draft-ietf-oauth-json-web-token.html).

module.exports.validatePassword = function(currentPassword, oldPassword) {
  return Promise.resolve(true);
};

module.exports.findAccessToken = function(req) {
  return accessToken;
};

module.exports.issueTokenForUser = function(user) {
  return token;
};

module.exports.issueToken = function(payload, options) {
  return token
};

module.exports.verifyToken = function(token) {
  return Promise.resolve(token);
};

module.exports.decodeToken = function(token, options) {
  return decodedToken;
};

module.exports.refreshToken = function(decodedToken, expiresIn) {
  return Promise.resolve(token);
};

module.exports.issueRefreshTokenForUser = function(token) {
  return token;
};

// renews the `access_token` based on the `refresh_token`
module.exports.validateRefreshToken = function(accessToken, refreshToken) {
  return Promise.resolve(tokens);
};

// set the token payload issued by login
module.exports.payloadBuilder = function (user, payload) {
  payload.foo = 'bar';

  return payload;
}

payloadBuilder()

It's possible to override payloadBuilder() with your own function. This allows you to extend/populate the token payload with custom data or logic.

properties

You can extend the token payload by giving setting sails.config.auth.jwt.payloadProperties. The user object is used to populate the properties.

Example:

  let properties = ['disabled', {groups: 'id'}];

  return {
    user    : user.id,       // default
    username: user.username, // default
    disabled: user.disabled,
    groups  : [3, 4, 6] // get the id's from an array with objects
  }

Policy

The verifyToken.js and ensureToken.js policies are just like any other Sails policy and can be applied as such. It's responsible for parsing the token from the incoming request and validating it's state.

Use it as you would use any other sails policy to enable authentication restriction to your Controllers/Actions:

module.exports.policies = {
  ...
  'AuthController': ['verifyToken', 'ensureToken'],
  ...
};

Model

This hook sets up a basic User model with some defaults attributes required to implement the jwt authentication scheme such as username, email and emailConfirmed. The User model can be extended with any property you want by defining it in your own Sails project.

Routes

These are the routes provided by this hook:

module.exports.routes = {
  'POST /login'                  : 'AuthController.login',
  'POST /signup'                 : 'AuthController.signup',
  'GET /auth/verify-email/:token': 'AuthController.verifyEmail',
  'GET /auth/me'                 : 'AuthController.me',
  'POST /auth/refresh-token'     : 'AuthController.refreshToken'
};

POST /auth/login

The request to this route /auth/login must be sent with these body parameters:

{
  email   : '[email protected]', // or username based on the `loginProperty`
  password: 'test123'
}

The response:

{
  access_token : 'jwt_access_token',
  refresh_token: 'jwt_refresh_token'
}

Make sure that you provide the acquired token in every request made to the protected endpoints, as query parameter access_token or as an HTTP request Authorization header Bearer TOKEN_VALUE.

The default TTL of the access_token is 1 day, refresh_token is 30 days. If the access_token is expired you can expect the expired_token error.

POST /auth/signup

The request to this route /signup must be sent with these body parameters:

{
  username       : 'test',
  email          : '[email protected]',
  password       : 'test123'
}

If the email verification feature is disabled, the response will be the same as the /auth/login.

{
  access_token : 'new jwt access token',
  refresh_token: 'new jwt refresh token'
}

If it's enabled you will get a 200 as response:

GET /auth/activate/:token

Account Activation

This feature is off by default and to enable it you must override the requireEmailVerification configuration and implement the function sendVerificationEmail:

module.exports.auth = {
  secret                  : process.env.JWT_SECRET || 'superSecretForDev',
  loginProperty           : 'email',
  requireEmailVerification: false,
  sendVerificationEmail   : (user, activateUrl) => {
    sails.log.error('sails-hook-authorization:: An email function must be implemented through `sails.config.auth.sendVerificationEmail` in order to enable the email verification feature. This will receive two parameters (user, activationLink).');
  },

  // seconds to be valid
  ttl: {
    accessToken : process.env.JWT_TOKEN_TTL || 86400,  // 1 day
    refreshToken: process.env.JWT_REFRESH_TOKEN_TTL || 2592000 // 30 days
  }
};

GET /auth/me

Returns the user, token protected area.

POST /auth/refresh-token

Refreshes the access_token based on the refresh_token. If the refresh_token is expired it will return expired_refresh_token and the user must login through /login

The request:

{
  access_token : 'jwt access token',
  refresh_token: 'jwt refresh token'
}

The response:

{
  access_token : 'new jwt access token',
  refresh_token: 'new jwt refresh token'
}

sails-hook-authorization's People

Contributors

ex37 avatar jeremyvergnas avatar rawphs avatar rwoverdijk avatar stokworks avatar vmbindraban avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar

sails-hook-authorization's Issues

/auth/me broken

Calling /auth/me causes a TypeError: Cannot read property 'user' of undefined at AuthController.js:52:34. It seems the verifyToken and ensureToken policies are never applied.

Not compatible with Sails V1

I tried to get the hook working on sails V1.

Didn't work from skratch for waterline

issues encountered:
Model User:
TOJSON not supported anymore -> created customTOJSON

authController:
no dynamic finder supported for user.findBy_...

Not working with Sails 1.0 without using Wetland

Hi, when using Sails 1.0.0-37 and Waterline (not Wetland) I get this error when posting to /auth/login:

TypeError: sails.models.user[("findOneBy" + _.upperFirst(...))] is not a function.

Do we have to write our custom actions in our own User model?

Broke in upcoming sails v1

Sails v1 appears to have refactored the way modules get loaded thus the override to support multiples source paths for controller doesn't work anymore.
This is the piece of code that now control actions loading.

One way to fix it may be to manually register actions using sails.registerAction(action, identity) for more info look here.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.