A Seneca.js User Management Plugin
Lead Maintainers: Mircea Alexandru and Mihai Dima
A user management plugin for the Seneca toolkit
This module is a plugin for the Seneca framework. It provides business logic for user management, such as:
- login
- logout
- registration
- password handling, incl. resets
There are two core concepts: user and login. A user, storing the user account details and encrypted passwords, and a login, representing an instance of a user that has been authenticated. A user can have multiple logins.
This module does not make any assumptions about the context it runs in. Use the seneca-auth plugin to handle web and social media authentication.
For a working example, see the Seneca user accounts example
If you're using this module, feel free to contact me on Twitter if you have any questions! :) @rjrodger
Supports Seneca versions 1.x and 2.x
npm install seneca
npm install seneca-user
You'll need the seneca module to use this module - it's just a plugin.
var seneca = require('seneca')()
seneca.use('user')
seneca.ready(function (){
var userpin = seneca.pin({role: 'user', cmd:'*'})
userpin.register( {name: "Flann O'Brien",email:'[email protected]',password:'blackair'},
function (err, out) {
userpin.login({email: '[email protected]', password: 'bicycle'}, function (err, out) {
console.log('login success: ' + out.ok)
userpin.login({email: '[email protected]',password:'blackair'}, function (err,out) {
console.log('login success: ' + out.ok)
console.log('login instance: ' + out.login)
})
})
})
})
This example, uses a pin for convenience: userpin.register( ... )
is the same as
seneca.act({role:'user',cmd:'register', ... )
.
In the example code, a user is registered, and then two login attempts are made. The first with an incorrect password, the second with the correct
password. The successful login provides a login instance. The login.id
property can be used to authenticate this login. For example,
the seneca-auth plugin uses this token as a HTTP authentication cookie.
To run this example (and the other code in this README), try:
node test/readme.js
Take a look at the user accounts example.
To load the plugin:
seneca.use('user', { ... options ... })
The user and login data is persisted using Seneca entities. These have
names sys/user
and sys/login
.
Passwords are not stored in plaintext, but using an ~10k round salted SHA512 hash. In the context of password reset functionality, this means you can generate new passwords, but cannot recover old ones. This is what you want.
There are separate actions to encrypt and verify passwords, so you can do things your own way if you like.
To support different use cases, users can be identified by either a
nick
or their email address. The nick
property is the traditional
'username', but does not need to be used in this fashion (hence the name 'nick').
All actions defined by this plugin return meta data objects containing the results of the action. The meta data object
contains an ok
field that is either true or false, indicating the success or failure of the action. For example, a login attempt with an invalid password will result in an {ok:false,...}
. When relevant, a why
property is also provided, with a code that indicates the reason for the result. For example: {...,why:'user-not-found'}.
rounds
: number of SHA512 rounds to use for password encryption, default: 11111autopass
: automatically generate an (unrecoverable) password if none is supplied - mostly good for testing, default: truemustrepeat
: you must provide arepeat
argument (a repeat of the password) when setting a passwordresetperiod
: duration in millis that a password reset token is valid, default: 24 hourspepper
: used in addition to password salts, a pepper is very similar but is stored in code instead of a database.
To set options, do so when you load the plugin:
seneca.use('user', { resetperiod: 3600*1000 })
The full source code of this plugin is annotated.
The user entity has a default type of -/sys/user
and standard properties:
nick
: Username, mostly. If not provided, will be set to email value.email
: Email address. At least one of nick or email is required.name
: Name of user. Just a text field. Cultural imperialism damages your conversions, ya know...!active
: if true, user can log in, if false, user can't. Default: true.when
: creation time, ISO String, like 2013-03-21T17:32:24.039Zsalt
: salt for encrypted passwordpass
: encrypted password
You can add your own properties, but be careful not to use the standard property names.
The login entity has a default type of -/sys/login
and standard properties:
id
: authentication token, UUIDnick
: copied from useruser
: user.id stringwhen
: creation time, ISO String, like 2013-03-21T17:32:24.039Zactive
: if true, login against this token will succeed, otherwise not
You can add your own properties, but be careful not to use the standard property names.
The reset entity has a default type of -/sys/reset
and standard properties:
id
: authentication token, UUIDnick
: copied from useruser
: user.id stringwhen
: creation time, ISO String, like 2013-03-21T17:32:24.039Zactive
: if true, reset against this token will succeed, otherwise not
You can add your own properties, but be careful not to use the standard property names.
All actions provide results via the standard callback format: function(error,data){ ... }
.
To customize the behavior of the plugin, override these actions, and provide your own business logic. You can call this.prior
inside each custom action to perform the default behaviour - see the [Customization] section below.
Login an existing user. Creates a new sys_login
entry.
nick_: required if no email, identifies user, alias: usernam
- email: required if no nick, identifies user
password_: password as entered by user, optional if using _auto
- auto: automatic login without password, default: false. Use this to generate login tokens.
user_: specify user using a sys/user entity - for convenience use inside your own actions, when you already have a user entity loade
Object with properties:
ok_: true if login succeeded, false if no
- login: login entity, id is the login token, used as cookie
user_: user entit
- why: indicates reason login failed or succeeded, refer to source for codes.
Logout a user. Update sys/login entry to active:false. Adds ended field with ISOString date time.
token_: existing login token, maybe from a cooki
Same object format as login command result: {ok:true|false,user:,login:}
Register a new user. You'll probably call this after a user fills out a regstration form. Any additional action arguments are saved as user properties. The nick and email fields will be checked for uniqueness. The new user is not logged in, use the login action for that.
nick
: Username, mostly. If not provided, will be set to args.username value, if defined, otherwise args.email valueemail
: Email address. At least one of nick or email is requiredusername
: a convenience - just an alias for nickpassword
: Plaintext password, supplied by user - will be stored encrypted and unrecoverablerepeat
: Password, repeated. Optional - if provided, must match passwordname
: Name of user. Just a text field.active
: if true, user can log in, if false, user can't. Default: true
Object with properties:
ok
: true if registration succeeded, false if nouser
: new user entitywhy
: indicates reason registration failed, refer to source for codes`
Authenticate a login token, returning the associated sys/login
and sys/user
if
the token is valid and active. Use this, for example, when handling
HTTP requests with an authentication cookie, to get the user.
token
: existing login token, maybe from a cookie
Same object format as login command result: {ok:true|false,user:,login:}
Create a reset token, valid for a 24 hours (use the resetperiod
options to alter the validity period). This action
creates an entry in the sys/reset
collection.
nick
: required if no email, identifies user, alias:username
email
: required if no nick, identifies useruser
: specify user using a sys/user entity - for convenience use inside your own actions, when you already have a user entity loaded
Object with properties:
ok
: true if update succeeded, false if notuser
:sys/user
entityreset
:sys/reset
entity
Load a sys/reset
entity using a reset token. Use this to load the details of a reset request, possible to confirm with user.
token
: reset token
Object with properties:
ok
: true if reset found, false if notuser
:sys/user
entityreset
:sys/reset
entitywhy
: reason for failure
Execute a password reset action. The user identified by the reset token is allowed to change their password. THe reset must be active, and the validity period must not be expired. On successful reset, the sys/reset
is deactivated and cannot be reused.
- token: reset token
- password: new password
- repeat: optional, repeat of new password
Object with properties:
ok
: true if reset found, false if notuser
:sys/user
entityreset
:sys/reset
entitywhy
: reason for failure
Encrypts a plaintext password, providing the salt and ciphertext. The encyption is options.rounds
(default:11111) rounds of SHA512.
password
: plaintext password.repeat
: optional, repeat of password
Object with properties:
ok
: true if succeededsalt
: the salt stringpass
: the ciphertext stringwhy
: reason for failure
Verifies that a password matches a given salt and ciphertext.
salt
: the salt string to use, find this in user.saltpass
: the pass string to use, find this in user.passproposed
: the proposed plaintext password to verify
Object with properties:
ok
: true if password matches
Updates a user.
nick
: the nick of the user to be updatedorig_nick
: if nick will be changed on this update thenorig_nick
will be used to identify the useremail
: the email of the user to be updatedorig_email
: if email will be changed on this update thenorig_email
will be used to identify the user
At least one of these arguments must be present.
Object with properties:
ok
: true if operation is OK
Deletes an user and all relationed records.
nick
: the nick of the user to be updated
Object with properties:
ok
: true if operation is OK
Enables an user.
nick
: the nick of the user to be updatedemail
: the email of the user to be updated
At least one of these arguments must be present
Object with properties:
ok
: true if operation is OK
Disables an user.
nick
: the nick of the user to be updatedemail
: the email of the user to be updated
At least one of these arguments must be present
Object with properties:
ok
: true if operation is OK
To see what this plugin is doing, try:
node your-app.js --seneca.log=plugin:user
This will print action logs and plugin logs for the user plugin. To skip the action logs, use:
node your-app.js --seneca.log=type:plugin,plugin:user
You can also set up the logging programmatically:
var seneca = require('seneca')({
log:{
map:[
{plugin:'user',handler:'print'}
]
}
})
For more on logging, see the seneca logging example.
As with all seneca plugins, you can customize behavior simply by overwriting actions.
For example, to add some custom fields when registering a user:
// override by using the same action pattern
seneca.add({role:' user', cmd: 'register'},function (args, done) {
// assign user to one of 10 random "teams"
args.team = Math.floor(10 * Math.random())
// this calls the original action, as provided by the user plugin
this.prior(args,done)
})
userpin.register({name: "Brian O'Nolan", email: '[email protected]', password: 'na-gCopaleen'},
function (err, out) {
console.log('user has team: ' + out.user.team)
})
The Senecajs org encourages open participation. If you feel you can help in any way, be it with documentation, examples, extra testing, or new features please get in touch.
npm test
Copyright (c) 2012-2016, Richard Rodger and other contributors. Licensed under MIT.