Class: Passwordless

Passwordless

new Passwordless()

Passwordless is a node.js module for express that allows authentication and authorization without passwords but simply by sending tokens via email or other means. It utilizes a very similar mechanism as many sites use for resetting passwords. The module was inspired by Justin Balthrop's article "Passwords are Obsolete"
Source:

Methods

(private) _generateNumberToken(max) → {Number}

Generates a strong random number between 0 and a maximum value. The maximum value cannot exceed 2^32
Parameters:
Name Type Description
max Number Maximum number to be generated
Source:
Throws:
Will throw an error if there is no sufficient entropy accumulated
Type
Error
Returns:
Random number between 0 and max
Type
Number

(private) _generateToken(randomBytes) → {function}

Generates a random token using Node's crypto rng
Parameters:
Name Type Description
randomBytes Number Random bytes to be generated
Source:
Throws:
Will throw an error if there is no sufficient entropy accumulated
Type
Error
Returns:
token-generator function
Type
function

(private) _redirectWithSessionSave(req, res, next, target)

Avoids a bug in express that might lead to a redirect before the session is actually saved
Parameters:
Name Type Description
req Object Node's http req object
res Object Node's http res object
next function Middleware callback
target String URL to redirect to
Source:

(private) _send401(res)

Sends a 401 error message back to the user
Parameters:
Name Type Description
res Object Node's http res object
Source:

acceptToken(optionsopt) → {ExpressMiddleware}

Returns express middleware which will look for token / UID query parameters and authenticate the user if they are provided and valid. A typical URL that is accepted by acceptToken() does look like this: http://www.example.com?token=TOKEN&uid=UID Simply calls the next middleware in case no token / uid has been submitted or if the supplied token / uid are not valid
Parameters:
Name Type Attributes Description
options Object <optional>
Properties
Name Type Attributes Description
successRedirect String <optional>
If set, the user will be redirected to the supplied URL in case of a successful authentication. If not set but the authentication has been successful, the next middleware will be called. This option is overwritten by option.enableOriginRedirect if set and an origin has been supplied. It is strongly recommended to set this option to avoid leaking valid tokens via the HTTP referrer. In case of session-less operation, though, you might want to ignore this flag for efficient operation (default: null)
tokenField String <optional>
The query parameter used to submit the token (default: 'token')
uidField String <optional>
The query parameter used to submit the user id (default: 'uid')
allowPost Boolean <optional>
If set, acceptToken() will also look for POST parameters to contain the token and uid (default: false)
failureFlash String <optional>
The error message to be flashed in case a token and uid were provided but the authentication failed. Using this option requires flash middleware such as connect-flash. The error message will be stored as 'passwordless' (example: 'This token is not valid anymore!', default: null)
successFlash String <optional>
The success message to be flashed in case the supplied token and uid were accepted. Using this option requires flash middleware such as connect-flash. The success message will be stored as 'passwordless-success' (example: 'You are now logged in!', default: null)
enableOriginRedirect Boolean <optional>
If set to true, the user will be redirected to the URL he originally requested before he was redirected to the login page. Requires that the URL was stored in the TokenStore when requesting a token through requestToken() (default: false)
Source:
Throws:
Will throw an error if there is no valid TokenStore, if failureFlash or successFlash is used without flash middleware or allowPost is used without body parser middleware
Type
Error
Returns:
Express middleware
Type
ExpressMiddleware
Example
app.use(passwordless.sessionSupport());
// Look for tokens in any URL requested from the server
app.use(passwordless.acceptToken());
		

addDelivery(nameopt, sendToken, optionsopt)

Adds a new delivery method to Passwordless used to transmit tokens to the user. This could, for example, be an email client or a sms client. If only one method is used, no name has to provided as it will be the default delivery method. If several methods are used and added, they will have to be named.
Parameters:
Name Type Attributes Description
name String <optional>
Name of the strategy. Not needed if only one method is added
sendToken sendToken Method that will be called as function(tokenToSend, uidToSend, recipient, callback, req) to transmit the token to the user. tokenToSend contains the token, uidToSend the UID that has to be part of the token URL, recipient contains the target such as an email address or a phone number depending on the user input, and callback has to be called either with no parameters or with callback({String}) in case of any issues during delivery
options Object <optional>
Properties
Name Type Attributes Description
ttl Number <optional>
Duration in ms that the token shall be valid (example: 1000*60*30, default: 1 hour)
tokenAlgorithm function <optional>
The algorithm used to generate a token. Function shall return the token in sync mode (default: Base58 token)
numberToken.max Number <optional>
Overwrites the default token generator by a random number generator which generates numbers between 0 and max. Cannot be used together with options.tokenAlgorithm
Source:
Example
passwordless.init(new MongoStore(pathToMongoDb));
passwordless.addDelivery(
	function(tokenToSend, uidToSend, recipient, callback, req) {
		// Send out token
		smtpServer.send({
			text:    'Hello!\nYou can now access your account here: ' 
				+ host + '?token=' + tokenToSend + '&uid=' + encodeURIComponent(uidToSend), 
			from:    yourEmail, 
			to:      recipient,
			subject: 'Token for ' + host
		}, function(err, message) { 
			if(err) {
				console.log(err);
			}
			callback(err);
		});
	});
	

init(tokenStore, optionsopt)

Initializes Passwordless and has to be called before any methods are called
Parameters:
Name Type Attributes Description
tokenStore TokenStore An instance of a TokenStore used to store and authenticate the generated tokens
options Object <optional>
Properties
Name Type Attributes Description
userProperty String <optional>
Sets the name under which the uid is stored in the http request object (default: 'user')
allowTokenReuse Boolean <optional>
Defines wether a token may be reused by users. Enabling this option is usually required for stateless operation, but generally not recommended due to the risk that others might have acquired knowledge about the token while in transit (default: false)
skipForceSessionSave Boolean <optional>
Some session middleware (especially cookie-session) does not require (and support) the forced safe of a session. In this case set this option to 'true' (default: false)
Source:
Throws:
Will throw an error if called without an instantiated TokenStore
Type
Error

logout(optionsopt) → {ExpressMiddleware}

Logs out the current user and invalidates any tokens that are still valid for the user
Parameters:
Name Type Attributes Description
options Object <optional>
Properties
Name Type Attributes Description
successFlash String <optional>
The success message to be flashed in case has been logged in an the logout proceeded successfully. Using this option requires flash middleware such as connect-flash. The success message will be stored as 'passwordless-success'. (example: 'You are now logged in!', default: null)
Source:
Throws:
Will throw an error if successFlash is used without flash middleware
Type
Error
Returns:
Express middleware
Type
ExpressMiddleware
Example
router.get('/logout', passwordless.logout( {options.successFlash: 'All done!'} ),
	function(req, res) {
		res.redirect('/');
});
		

requestToken(getUserID, optionsopt) → {ExpressMiddleware}

Requests a token from Passwordless for a specific user and calls the delivery strategy to send the token to the user. Sends back a 401 error message if the user is not valid or a 400 error message if no user information has been transmitted at all. By default, POST params will be expected
Parameters:
Name Type Attributes Description
getUserID getUserID The function called to resolve the supplied user contact information (e.g. email) into a proper user ID: function(user, delivery, callback, req) where user contains the contact details provided, delivery the method used, callback expects a call in the format callback(error, user), where error is either null or an error message and user is either null if not user has been found or the user ID. req contains the Express request object
options Object <optional>
Properties
Name Type Attributes Description
failureRedirect String <optional>
If provided, the user will be redirected to the given URL in case the user details were not provided or could not be validated by getUserId. This could typically by a login page (example: '/login', default: null)
failureFlash String <optional>
The error message to be flashed in case the user details could not be validated. Using this option requires flash middleware such as connect-flash. The message will be stored as 'passwordless'. Can only be used in combination with failureRedirect (example: 'Your user details seem strange', default: null)
successFlash String <optional>
The message to be flashed in case the tokens were send out successfully. Using this option requires flash middleware such as connect-flash. The message will be stored as 'passwordless-success '. (example: 'Your token has been send', default: null)
userField String <optional>
The field which contains the user's contact detail such as her email address (default: 'user')
deliveryField String <optional>
The field which contains the name of the delivery method to be used. Only needed if several strategies have been added with addDelivery() (default: null)
originField String <optional>
If set, requestToken() will look for any URLs in this field that will be stored in the token database so that the user can be redirected to this URL as soon as she is authenticated. Usually used to redirect the user to the resource that she originally requested before being redirected to the login page (default: null)
allowGet Boolean <optional>
If set, requestToken() will look for GET parameters instead of POST (default: false)
Source:
Throws:
Will throw an error if failureFlash is used without flash middleware, failureFlash is used without failureRedirect, successFlash is used without flash middleware, no body parser is used and POST parameters are expected, or if no delivery method has been added
Type
Error
Returns:
Express middleware
Type
ExpressMiddleware
Example
router.post('/sendtoken', 
	passwordless.requestToken(
		function(user, delivery, callback, req) {
			// usually you would want something like:
			User.find({email: user}, callback(ret) {
				if(ret)
					callback(null, ret.id)
				else
					callback(null, null)
			})
		}),
		function(req, res) {
			res.render('sent');
		});

restricted(optionsopt) → {ExpressMiddleware}

Returns express middleware that ensures that only successfully authenticated users have access to any middleware or responses that follows this middleware. Can either be used for individual URLs or a certain path and any sub-elements. By default, a 401 error message is returned if the user has no access to the underlying resource.
Parameters:
Name Type Attributes Description
options Object <optional>
Properties
Name Type Attributes Description
failureRedirect String <optional>
If provided, the user will be redirected to the given URL in case she is not authenticated. This would typically by a login page (example: '/login', default: null)
failureFlash String <optional>
The error message to be flashed in case the user is not authenticated. Using this option requires flash middleware such as connect-flash. The message will be stored as 'passwordless'. Can only be used in combination with failureRedirect (example: 'No access!', default: null)
originField String <optional>
If set, the originally requested URL will be passed as query param (with the supplied name) to the redirect URL provided by failureRedirect. Can only be used in combination with failureRedirect (example: 'origin', default: null)
Source:
Throws:
Will throw an error if failureFlash is used without flash middleware, failureFlash is used without failureRedirect, or originField is used without failureRedirect
Type
Error
Returns:
Express middleware
Type
ExpressMiddleware
Example
router.get('/admin', passwordless.restricted({ failureRedirect: '/login' }),
	function(req, res) {
 	res.render('admin', { user: req.user });
	});
			

sessionSupport() → {ExpressMiddleware}

By adding this middleware function to a route, Passwordless automatically restores the logged in user from the session. In 90% of the cases, this is what is required. However, Passwordless can also work without session support in a stateless mode.
Source:
Throws:
Will throw an error no session middleware has been supplied
Type
Error
Returns:
Express middleware
Type
ExpressMiddleware
Example
var app = express();
var passwordless = new Passwordless(new DBTokenStore());
		
app.use(cookieParser());
app.use(expressSession({ secret: '42' }));
		
app.use(passwordless.sessionSupport());
app.use(passwordless.acceptToken());