Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

apollo-passport-local-strategy

Package Overview
Dependencies
Maintainers
1
Versions
3
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

apollo-passport-local-strategy

Local strategy using email address and hashed, bcrypted password

  • 1.0.2
  • latest
  • Source
  • npm
  • Socket score

Version published
Maintainers
1
Created
Source

apollo-passport-local-strategy

Forked from apollo-passport/local Local strategy using email address and hashed, bcrypted password.

npm Circle CI Coverage Status MIT License

Copyright (c) 2017 by Gilad Shoham, released under the MIT license.

New Features in this fork (Highlights)

  • Add option to define input apUserInput (outside) for creating new users with your desired fields
  • Add account verification token during create user
  • Add apVerifyAccount mutation to verify the account
  • Add recoverPasswordRequest mutation to create reset password token
  • Add options to pass hooks method (onCreateUserEnd, onBeforeStoreRegisteredUser, onRecoverPasswordRequestEnd, onVerifyAccountEnd, onRecoverPasswordEnd, onLoginEnd) (for example to send verification emails)
  • Improve errors format (Add error code)
  • Allow users without services to register even if their email already exist (Merge with existing user) for case that the user added from outside and not really registered

Add register date during merge with existing user

New Features in this fork (Usage)

Use my fork of apollo-passport-mongodb-driver

npm install apollo-passport-mongodb-driver

Import my version of local strategy

First, make sure to install my version of local strategy:

npm i --save apollo-passport-local-strategy

In apollo-passport docs, you will see this line:

import { Strategy as LocalStrategy } from 'passport-local';

It should be replaced by:

import { Strategy as LocalStrategy } from 'apollo-passport-local-strategy/lib/index';

(If you don't do this, the options like hooks will not work)

Mutation and types signatures

const typeDefinitions = `
type RootMutation {
  apCreateUserEmailPassword (input: apUserInput!): PassportResult,
  apVerifyAccount (userId: String, verificationToken: String!): SimpleError,
  apRecoverPasswordRequest (email: String): String,
  apRecoverPassword (userId: String!, token: String!, newPassword: String!): String,
  apUpdateUserPassword (userId: String!, oldPassword: String!, newPassword: String!): String,
  apLoginEmailPassword (email: String!, password: String!): PassportResult
}

type SimpleError {
  errCode: String,
  errMessage: String
}
`;

Define apUserInput

You should define your own userInput type (named apUserInput). This way you can define what ever fields you want to be part of the registration process. You have to make sure that you have email and password fields, because the library used them internally.

Example:

`input apUserInput {
  # User email
  email: String!
  # User password
  password: String!
  # User first name
  firstName: String!
  # User last name
  lastName: String!
  # office phone number
  phone: String
  # Personal mobile phone number
  mobilePhone: String
}
`;

Account verification token during create user

During create user the library will add these fields to the new user:

  • verificationToken - The token generated using this code:
crypto.randomBytes(20, (err, buf) => {
  var token = buf.toString('hex');
});

verificationTokenExpiration - An expiration to account verification token (Will be used during verify account), defalut to be 1 month. You can change it via configuration.

verified - Will be set to false during creation, and will be change to true on verify account.

Recover Password Request mutation to create reset password token

A new mutation to generate tokens for reset password. The tokens will be generated the same way as the account verification token. The name of the token fields will be:

  • resetPassToken
  • resetPassTokenExpiration Once a reset password request has been submitted, the verified will be change to false again. If the user has never verified his account the account verification token will be deleted. (The reason beyond is that if the user has the reset password token i assume he got it the same way as the verify account, therefor it can be used to verify the account as well). If the user will try to verify his account after reset password, he will get an error that reset password is in progress.

New error

This new error currently used only on apVerifyAccount mutation. This will give you better way to handle those errors in the client side. List of the possible errors:

{
  errCode: 'USER_NOT_EXIST',
  errMessage: 'No such user id',
}

{
  errCode: 'RESET_PASS_IN_PROGRESS',
  errMessage: 'Reset password is in progress',
}

{
  errCode: 'TOKEN_NOT_VALID',
  errMessage: 'Verification token not valid',
}

{
  errCode: 'TOKEN_EXPIRED',
  errMessage: 'Verification token expired',
}

Allow users without services to register

During the create user there is a check if the user exist. If the user exist but without any service the new user will be merged with the existing one. The reason beyond this, is if you collect some user details from other users or from external source, maybe you want someone to invite other user, you want to create this user, but still let him register and define his passowrd.

New options (hooks / tokensExpirationLength)

The hooks will be called with the user as argument. Default for tokensExpirationLength is 1 week for both (verification and reset pass). The length is at SECONDS and not milliseconds.

Here is an example for one hook and changing the tokens expiration length:

import { Strategy as LocalStrategy } from 'apollo-passport-local-strategy/lib/index';

const onRegisterUserHook = function(user){
    logService.log('user registered');
    mailService.sendVerificationMail(user);
}

const onLoginEndHook = function(user){
    logService.log('user logged in');
    UserService.updateLastLogin(user._id);
}

const MONTH = 60 * 60 * 24 * 7 * 4;

const apolloPassportLocalOptions = {
  usernameField: 'email',
  passwordField: 'password',
  hookMethods: {
    onCreateUserEnd: onRegisterUserHook,
    onBeforeStoreRegisteredUser: onBeforeStoreRegisteredUserHook,
    onRecoverPasswordRequestEnd: onRecoverPasswordRequestEndHook,
    onRecoverPasswordEnd: onRecoverPasswordEndHook,
    onUpdatePasswordEnd: onUpdatePasswordEndHook,
    onVerifyAccountEnd: onVerifyAccountEndHook,
    onLoginEnd: onLoginEndHook,
  },
  // Set the expiration to be 4 weeks
  tokensExpirationLength: {
    verification: MONTH,
    resetPass: MONTH,
  },
};

const apolloPassport = new ApolloPassport({
  db: MongoDBDriver,            
  jwtSecret: 'my special secret',   
  authPath: '/ap-auth',            
});

apolloPassport.use('local', LocalStrategy, apolloPassportLocalOptions);

Features

  • Authenticate users with an email and password.
  • Passwords stored in the database are encrypted with bcrypt.

Usage

See https://github.com/gadicc/apollo-passport.

Note: you don't usually need a special apollo-passport-xxx package for every passport strategy. apollo-passport-local is a special case because of it's dependencies, e.g. bcrypt and some client-side hashing.

$ npm i --save passport-local apollo-passport-local-strategy

Server

import { Strategy as LocalStrategy } from 'apollo-passport-local-strategy/lib/index';

// Your previously created ApolloPassport instance...
apolloPassport.use('local', LocalStrategy /*, options */);

Client

import ApolloPassportLocal from 'apollo-passport-local-strategy/lib/client';

// Your previously created ApolloPassport instance...
apolloPassport.use('local', ApolloPassportLocal);

Keywords

FAQs

Package last updated on 12 Feb 2017

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc