The App
object represents a Loopback application.
The App object extends Express and supports Express middleware. See Express documentation for details.
var loopback = require('loopback');
var app = loopback();
app.get('/', function(req, res){
res.send('hello world');
});
app.listen(3000);
Register a connector.
When a new data-source is being added via app.dataSource
, the connector
name is looked up in the registered connectors first.
Connectors are required to be explicitly registered only for applications using browserify, because browserify does not support dynamic require, which is used by LoopBack to automatically load the connector module.
Name | Type | Description |
---|---|---|
name |
String
|
Name of the connector, e.g. 'mysql'. |
connector |
Object
|
Connector object as returned by |
Define a DataSource.
Name | Type | Description |
---|---|---|
name |
String
|
The data source name |
config |
Object
|
The data source config |
Enable app wide authentication.
Listen for connections and update the configured port.
When there are no parameters or there is only one callback parameter,
the server will listen on app.get('host')
and app.get('port')
.
For example, to listen on host/port configured in app config:
app.listen();
Otherwise all arguments are forwarded to http.Server.listen
.
For example, to listen on the specified port and all hosts, and ignore app config.
app.listen(80);
The function also installs a listening
callback that calls
app.set('port')
with the value returned by server.address().port
.
This way the port param contains always the real port number, even when
listen was called with port number 0.
Name | Type | Description |
---|---|---|
[cb] |
Function
|
If specified, the callback is added as a listener for the server's "listening" event. |
Name | Type | Description |
---|---|---|
result |
http.Server
|
A node |
Attach a model to the app. The Model
will be available on the
app.models
object.
Example - Attach an existing model:
var User = loopback.User;
app.model(User);
Example - Attach an existing model, alter some aspects of the model:
var User = loopback.User;
app.model(User, { dataSource: 'db' });
Name | Type | Description |
---|---|---|
Model |
Object or String
|
The model to attach. |
config |
Object
|
The model's configuration. |
Name | Type | Description |
---|---|---|
dataSource |
String or DataSource
|
The |
[public] |
Boolean
|
Whether the model should be exposed via REST API. |
[relations] |
Object
|
Relations to add/update. |
Name | Type | Description |
---|---|---|
result |
ModelConstructor
|
the model class |
Get the models exported by the app. Returns only models defined using app.model()
There are two ways to access models:
app.models()
to get a list of all models.var models = app.models();
models.forEach(function(Model) {
console.log(Model.modelName); // color
});
app.model
to access a model by name.
app.models
has properties for all defined models.The following example illustrates accessing the Product
and CustomerReceipt
models
using the models
object.
var loopback = require('loopback');
var app = loopback();
app.boot({
dataSources: {
db: {connector: 'memory'}
}
});
app.model('product', {dataSource: 'db'});
app.model('customer-receipt', {dataSource: 'db'});
// available based on the given name
var Product = app.models.Product;
// also available as camelCase
var product = app.models.product;
// multi-word models are avaiable as pascal cased
var CustomerReceipt = app.models.CustomerReceipt;
// also available as camelCase
var customerReceipt = app.models.customerReceipt;
Name | Type | Description |
---|---|---|
result |
Array
|
Array of model classes. |
Get all remote objects.
Name | Type | Description |
---|---|---|
result |
Object
|
Lazily load a set of remote objects.
NOTE: Calling app.remotes()
more than once returns only a single set of remote objects.
Name | Type | Description |
---|---|---|
result |
RemoteObjects
|
Register a middleware using a factory function and a JSON config.
Example
app.middlewareFromConfig(compression, {
enabled: true,
phase: 'initial',
params: {
threshold: 128
}
});
Name | Type | Description |
---|---|---|
factory |
function
|
The factory function creating a middleware handler. Typically a result of |
config |
Object
|
The configuration. |
Name | Type | Description |
---|---|---|
phase |
String
|
The phase to register the middleware in. |
[enabled] |
Boolean
|
Whether the middleware is enabled. Default: |
[params] |
Array
|
The arguments to pass to the factory function. Either an array of arguments, or the value of the first argument when the factory expects a single argument only. |
[paths] |
Array or string or RegExp
|
Optional list of paths limiting the scope of the middleware. |
Name | Type | Description |
---|---|---|
result |
object
|
this (fluent API) |
Register (new) middleware phases.
If all names are new, then the phases are added just before "routes" phase. Otherwise the provided list of names is merged with the existing phases in such way that the order of phases is preserved.
Examples
// built-in phases:
// initial, session, auth, parse, routes, files, final
app.defineMiddlewarePhases('custom');
// new list of phases
// initial, session, auth, parse, custom, routes, files, final
app.defineMiddlewarePhases([
'initial', 'postinit', 'preauth', 'routes', 'subapps'
]);
// new list of phases
// initial, postinit, preauth, session, auth, parse, custom,
// routes, subapps, files, final
Name | Type | Description |
---|---|---|
nameOrArray |
string or Array.<string>
|
A phase name or a list of phase names to add. |
Name | Type | Description |
---|---|---|
result |
object
|
this (fluent API) |
Register a middleware handler to be executed in a given phase.
Name | Type | Description |
---|---|---|
name |
string
|
The phase name, e.g. "init" or "routes". |
[paths] |
Array or string or RegExp
|
Optional list of paths limiting the scope of the middleware. String paths are interpreted as expressjs path patterns, regular expressions are used as-is. |
handler |
function
|
The middleware handler, one of |
Name | Type | Description |
---|---|---|
result |
object
|
this (fluent API) |
LoopBack core module. It provides static properties and
methods to create models and data sources. The module itself is a function
that creates loopback app
. For example:
var loopback = require('loopback');
var app = loopback();
Name | Type | Description |
---|---|---|
version |
String
|
Version of LoopBack framework. Static read-only property. |
mime |
String
|
|
isBrowser |
Boolean
|
True if running in a browser environment; false otherwise. Static read-only property. |
isServer |
Boolean
|
True if running in a server environment; false otherwise. Static read-only property. |
registry |
Registry
|
The global |
faviconFile |
String
|
Path to a default favicon shipped with LoopBack. Use as follows: |
Attach any model that does not have a dataSource to the default dataSource for the type the Model requests
Alter an existing Model class.
Name | Type | Description |
---|---|---|
ModelCtor |
Model
|
The model constructor to alter. |
config |
Object
|
Additional configuration to apply |
Name | Type | Description |
---|---|---|
dataSource |
DataSource
|
Attach the model to a dataSource. |
[relations] |
Object
|
Model relations to add/update. |
Create a data source with passing the provided options to the connector.
Name | Type | Description |
---|---|---|
name |
String
|
Optional name. |
options |
Object
|
Data Source options |
Name | Type | Description |
---|---|---|
connector |
Object
|
LoopBack connector. |
[*] |
|
Other connector properties. See the relevant connector documentation. |
Create a named vanilla JavaScript class constructor with an attached set of properties and options.
This function comes with two variants:
loopback.createModel(name, properties, options)
loopback.createModel(config)
In the second variant, the parameters name
, properties
and options
are provided in the config object. Any additional config entries are
interpreted as options
, i.e. the following two configs are identical:
{ name: 'Customer', base: 'User' }
{ name: 'Customer', options: { base: 'User' } }
Example
Create an Author
model using the three-parameter variant:
loopback.createModel(
'Author',
{
firstName: 'string',
lastName: 'string'
},
{
relations: {
books: {
model: 'Book',
type: 'hasAndBelongsToMany'
}
}
}
);
Create the same model using a config object:
loopback.createModel({
name: 'Author',
properties: {
firstName: 'string',
lastName: 'string'
},
relations: {
books: {
model: 'Book',
type: 'hasAndBelongsToMany'
}
}
});
Name | Type | Description |
---|---|---|
name |
String
|
Unique name. |
properties |
Object
|
|
options |
Object
|
(optional) |
Look up a model class by name from all models created by
loopback.createModel()
Name | Type | Description |
---|---|---|
modelName |
String
|
The model name |
Name | Type | Description |
---|---|---|
result |
Model
|
The model class |
Get the default dataSource
for a given type
.
Name | Type | Description |
---|---|---|
type |
String
|
The datasource type. |
Name | Type | Description |
---|---|---|
result |
DataSource
|
The data source instance |
Look up a model class by name from all models created by
loopback.createModel()
. Throw an error when no such model exists.
Name | Type | Description |
---|---|---|
modelName |
String
|
The model name |
Name | Type | Description |
---|---|---|
result |
Model
|
The model class |
Look up a model class by the base model class. The method can be used by LoopBack to find configured models in models.json over the base model.
Name | Type | Description |
---|---|---|
modelType |
Model
|
The base model class |
Name | Type | Description |
---|---|---|
result |
Model
|
The subclass if found or the base class |
Expose path to the default favicon file
only in node
Get an in-memory data source. Use one if it already exists.
Name | Type | Description |
---|---|---|
[name] |
String
|
The name of the data source. If not provided, the |
Add a remote method to a model.
Name | Type | Description |
---|---|---|
fn |
Function
|
|
options |
Object
|
(optional) |
Set the default dataSource
for a given type
.
Name | Type | Description |
---|---|---|
type |
String
|
The datasource type. |
dataSource |
Object or DataSource
|
The data source settings or instance |
Name | Type | Description |
---|---|---|
result |
DataSource
|
The data source instance. |
Create a template helper.
var render = loopback.template('foo.ejs');
var html = render({foo: 'bar'});
Name | Type | Description |
---|---|---|
path |
String
|
Path to the template file. |
Name | Type | Description |
---|---|---|
result |
Function
|
Define and reference Models
and DataSources
.
Add the acl entry to the acls
Name | Type | Description |
---|---|---|
acls |
Array.<Object>
|
|
acl |
Object
|
Attach any model that does not have a dataSource to the default dataSource for the type the Model requests
Alter an existing Model class.
Name | Type | Description |
---|---|---|
ModelCtor |
Model
|
The model constructor to alter. |
config |
Object
|
Additional configuration to apply |
Name | Type | Description |
---|---|---|
dataSource |
DataSource
|
Attach the model to a dataSource. |
[relations] |
Object
|
Model relations to add/update. |
Create a data source with passing the provided options to the connector.
Name | Type | Description |
---|---|---|
name |
String
|
Optional name. |
options |
Object
|
Data Source options |
Name | Type | Description |
---|---|---|
connector |
Object
|
LoopBack connector. |
[*] |
|
Other connector properties. See the relevant connector documentation. |
Create a named vanilla JavaScript class constructor with an attached set of properties and options.
This function comes with two variants:
loopback.createModel(name, properties, options)
loopback.createModel(config)
In the second variant, the parameters name
, properties
and options
are provided in the config object. Any additional config entries are
interpreted as options
, i.e. the following two configs are identical:
{ name: 'Customer', base: 'User' }
{ name: 'Customer', options: { base: 'User' } }
Example
Create an Author
model using the three-parameter variant:
loopback.createModel(
'Author',
{
firstName: 'string',
lastName: 'string'
},
{
relations: {
books: {
model: 'Book',
type: 'hasAndBelongsToMany'
}
}
}
);
Create the same model using a config object:
loopback.createModel({
name: 'Author',
properties: {
firstName: 'string',
lastName: 'string'
},
relations: {
books: {
model: 'Book',
type: 'hasAndBelongsToMany'
}
}
});
Name | Type | Description |
---|---|---|
name |
String
|
Unique name. |
properties |
Object
|
|
options |
Object
|
(optional) |
Look up a model class by name from all models created by
loopback.createModel()
Name | Type | Description |
---|---|---|
modelOrName |
String or Function
|
The model name or a |
Name | Type | Description |
---|---|---|
result |
Model
|
The model class |
Get the default dataSource
for a given type
.
Name | Type | Description |
---|---|---|
type |
String
|
The datasource type. |
Name | Type | Description |
---|---|---|
result |
DataSource
|
The data source instance |
Look up a model class by name from all models created by
loopback.createModel()
. Throw an error when no such model exists.
Name | Type | Description |
---|---|---|
modelOrName |
String
|
The model name or a |
Name | Type | Description |
---|---|---|
result |
Model
|
The model class |
Look up a model class by the base model class. The method can be used by LoopBack to find configured models in models.json over the base model.
Name | Type | Description |
---|---|---|
modelType |
Model
|
The base model class |
Name | Type | Description |
---|---|---|
result |
Model
|
The subclass if found or the base class |
Get an in-memory data source. Use one if it already exists.
Name | Type | Description |
---|---|---|
[name] |
String
|
The name of the data source. If not provided, the |
Set the default dataSource
for a given type
.
Name | Type | Description |
---|---|---|
type |
String
|
The datasource type. |
dataSource |
Object or DataSource
|
The data source settings or instance |
Name | Type | Description |
---|---|---|
result |
DataSource
|
The data source instance. |
Get the current context object. The context is preserved across async calls, it behaves like a thread-local storage.
Name | Type | Description |
---|---|---|
result |
ChainedContext
|
The context object or null. |
Run the given function in such way that
loopback.getCurrentContext
returns the
provided context object.
NOTE
The method is supported on the server only, it does not work in the browser at the moment.
Name | Type | Description |
---|---|---|
fn |
Function
|
The function to run, it will receive arguments (currentContext, currentDomain). |
context |
ChainedContext
|
An optional context object. When no value is provided, then the default global context is used. |
Create a new LoopBackContext instance that can be used
for loopback.runInContext
.
NOTES
At the moment, loopback.getCurrentContext
supports
a single global context instance only. If you call createContext()
multiple times, getCurrentContext
will return the last context
created.
The method is supported on the server only, it does not work in the browser at the moment.
Name | Type | Description |
---|---|---|
scopeName |
String
|
An optional scope name. |
Access context represents the context for a request to access protected resources
Name | Type | Description |
---|---|---|
context |
Object
|
The context object |
Name | Type | Description |
---|---|---|
principals |
Array.<Principal>
|
An array of principals |
model |
Function
|
The model class |
modelName |
String
|
The model name |
modelId |
String
|
The model id |
property |
String
|
The model property/method/relation name |
method |
String
|
The model method to be invoked |
accessType |
String
|
The access type |
accessToken |
AccessToken
|
The access token |
Name | Type | Description |
---|---|---|
result |
AccessContext
|
Add a principal to the context
Name | Type | Description |
---|---|---|
principalType |
String
|
The principal type |
principalId |
|
The principal id |
[principalName] |
String
|
The principal name |
Name | Type | Description |
---|---|---|
result |
boolean
|
Get the application id
Name | Type | Description |
---|---|---|
result |
|
Get the user id
Name | Type | Description |
---|---|---|
result |
|
Check if the access context has authenticated principals
Name | Type | Description |
---|---|---|
result |
boolean
|
A request to access protected resources.
Name | Type | Description |
---|---|---|
model |
String
|
The model name |
property |
String
|
|
accessType |
String
|
The access type |
permission |
String
|
The requested permission |
Name | Type | Description |
---|---|---|
result |
AccessRequest
|
Does the given ACL
apply to this AccessRequest
.
Name | Type | Description |
---|---|---|
acl |
ACL
|
Is the request for access allowed?
Name | Type | Description |
---|---|---|
result |
Boolean
|
Does the request contain any wildcards?
Name | Type | Description |
---|---|---|
result |
Boolean
|
This class represents the abstract notion of a principal, which can be used to represent any entity, such as an individual, a corporation, and a login id
Name | Type | Description |
---|---|---|
type |
String
|
The principal type |
id |
|
The princiapl id |
[name] |
String
|
The principal name |
Name | Type | Description |
---|---|---|
result |
Principal
|
Compare if two principals are equal Returns true if argument principal is equal to this principal.
Name | Type | Description |
---|---|---|
p |
Object
|
The other principal |
The base class for all models.
Inheriting from Model
var properties = {...};
var options = {...};
var MyModel = loopback.Model.extend('MyModel', properties, options);
Options
trackChanges
- If true, changes to the model will be tracked. Required
for replication.Events
changed
Emitted after a model has been successfully created, saved, or updated.
Argument: inst
, model instance, object
MyModel.on('changed', function(inst) {
console.log('model with id %s has been changed', inst.id);
// => model with id 1 has been changed
});
deleted
Emitted after an individual model has been deleted.
Argument: id
, model ID (number).
MyModel.on('deleted', function(id) {
console.log('model with id %s has been deleted', id);
// => model with id 1 has been deleted
});
deletedAll
Emitted after an individual model has been deleted.
Argument: where
(optional), where filter, JSON object.
MyModel.on('deletedAll', function(where) {
if (where) {
console.log('all models where ', where, ' have been deleted');
// => all models where
// => {price: {gt: 100}}
// => have been deleted
}
});
attached
Emitted after a Model
has been attached to an app
.
dataSourceAttached
Emitted after a Model
has been attached to a DataSource
.
Emitted when model property is set.
Argument: inst
, model instance, object
MyModel.on('set', function(inst) {
console.log('model with id %s has been changed', inst.id);
// => model with id 1 has been changed
});
Name | Type | Description |
---|---|---|
data |
Object
|
Name | Type | Description |
---|---|---|
Model.modelName |
String
|
The name of the model. Static property. |
Model.dataSource |
DataSource
|
Data source to which the model is connected, if any. Static property. |
Model.sharedMethod |
SharedClass
|
The |
settings |
Object
|
Contains additional model settings. |
settings.http.path |
string
|
Base URL of the model HTTP route. |
[{string}] |
|
settings.acls Array of ACLs for the model. |
Check if the given access token can invoke the specified method.
Name | Type | Description |
---|---|---|
token |
AccessToken
|
The access token. |
modelId |
|
The model ID. |
sharedMethod |
SharedMethod
|
The method in question. |
ctx |
Object
|
The remote invocation context. |
callback |
Function
|
The callback function. |
Name | Type | Description |
---|---|---|
err |
String or Error
|
The error object. |
allowed |
Boolean
|
True if the request is allowed; false otherwise. |
Disable remote invocation for the method with the given name.
Name | Type | Description |
---|---|---|
name |
String
|
The name of the method. |
isStatic |
Boolean
|
Is the method static (eg. |
Get the Application
object to which the Model is attached.
Name | Type | Description |
---|---|---|
callback |
Function
|
Callback function called with |
Name | Type | Description |
---|---|---|
err |
Error
|
Error object; see Error object. |
app |
Application
|
Attached application object. |
Enabled deeply-nested queries of related models via REST API.
Name | Type | Description |
---|---|---|
relationName |
String
|
Name of the nested relation. |
[options] |
Object
|
It is optional. See below. |
pathName |
String
|
The HTTP path (relative to the model) at which your remote method is exposed. |
filterMethod |
String
|
The filter name. |
paramName |
String
|
The argument name that the remote method accepts. |
getterName |
String
|
The getter name. |
hooks |
Boolean
|
Whether to inherit before/after hooks. |
filterCallback |
Function
|
The Optional filter function. |
Name | Type | Description |
---|---|---|
SharedMethod |
Object
|
object. See here. |
RelationDefinition |
Object
|
object which includes relation |
Enable remote invocation for the specified method. See Remote methods for more information.
Static method example:
Model.myMethod();
Model.remoteMethod('myMethod');
Name | Type | Description |
---|---|---|
name |
String
|
The name of the method. |
options |
Object
|
The remoting options. See Remote methods - Options. |
The loopback.Model.extend()
method calls this when you create a model that extends another model.
Add any setup or configuration code you want executed when the model is created.
See Setting up a custom model.
Extends Model with basic query and CRUD support.
Change Event
Listen for model changes using the change
event.
MyPersistedModel.on('changed', function(obj) {
console.log(obj) // => the changed model
});
Apply an update list.
Note: this is not atomic
Name | Type | Description |
---|---|---|
updates |
Array
|
An updates list, usually from createUpdates(). |
callback |
Function
|
Callback function. |
Get the changes to a model since the specified checkpoint. Provide a filter object to reduce the number of results returned.
Name | Type | Description |
---|---|---|
since |
Number
|
Return only changes since this checkpoint. |
filter |
Object
|
Include only changes that match this filter, the same as for #persistedmodel-find). |
callback |
Function
|
Callback function called with |
Name | Type | Description |
---|---|---|
err |
Error
|
Error object; see Error object. |
changes |
Array
|
An array of Change objects. |
Create a checkpoint.
Name | Type | Description |
---|---|---|
callback |
Function
|
Return the number of records that match the optional "where" filter.
Name | Type | Description |
---|---|---|
[where] |
Object
|
Optional where filter, like |
callback |
Function
|
Callback function called with |
Name | Type | Description |
---|---|---|
err |
Error
|
Error object; see Error object. |
count |
Number
|
Number of instances updated. |
Create new instance of Model, and save to database.
Name | Type | Description |
---|---|---|
{Object}|[{Object}] |
|
data Optional data argument. Can be either a single model instance or an array of instances. |
callback |
Function
|
Callback function called with |
Name | Type | Description |
---|---|---|
err |
Error
|
Error object; see Error object. |
models |
Object
|
Model instances or null. |
Create a change stream. See here for more info
Name | Type | Description |
---|---|---|
options |
Object
|
|
options.where |
Object
|
Only changes to models matching this where filter will be included in the |
callback |
Function
|
Name | Type | Description |
---|---|---|
err |
Error
|
|
changes |
ChangeStream
|
Create an update list (for Model.bulkUpdate()
) from a delta list
(result of Change.diff()
).
Name | Type | Description |
---|---|---|
deltas |
Array
|
|
callback |
Function
|
Get the current checkpoint ID.
Name | Type | Description |
---|---|---|
callback |
Function
|
Callback function called with |
Name | Type | Description |
---|---|---|
err |
Error
|
Error object; see Error object. |
currentCheckpointId |
Number
|
Current checkpoint ID. |
Destroy all model instances that match the optional where
specification.
Name | Type | Description |
---|---|---|
[where] |
Object
|
Optional where filter, like: |
callback |
Function
|
Optional callback function called with |
Name | Type | Description |
---|---|---|
err |
Error
|
Error object; see Error object. |
info |
Object
|
Additional information about the command outcome. |
info.count |
Number
|
Number of instances (rows, documents) destroyed. |
Destroy model instance with the specified ID.
Name | Type | Description |
---|---|---|
id |
|
The ID value of model instance to delete. |
callback |
Function
|
Callback function called with |
Name | Type | Description |
---|---|---|
err |
Error
|
Error object; see Error object. |
Get a set of deltas and conflicts since the given checkpoint.
See Change.diff() for details.
Name | Type | Description |
---|---|---|
since |
Number
|
Find deltas since this checkpoint. |
remoteChanges |
Array
|
An array of change objects. |
callback |
Function
|
Callback function called with |
Name | Type | Description |
---|---|---|
err |
Error
|
Error object; see Error object. |
result |
Object
|
Object with |
Enable the tracking of changes made to the model. Usually for replication.
Check whether a model instance exists in database.
Name | Type | Description |
---|---|---|
id |
id
|
Identifier of object (primary key value). |
callback |
Function
|
Callback function called with |
Name | Type | Description |
---|---|---|
err |
Error
|
Error object; see Error object. |
exists |
Boolean
|
True if the instance with the specified ID exists; false otherwise. |
Find all model instances that match filter
specification.
See Querying models.
Name | Type | Description |
---|---|---|
[filter] |
Object
|
Optional Filter JSON object; see below. |
callback |
Function
|
Callback function called with |
Name | Type | Description |
---|---|---|
fields |
String or Object or Array
|
Identify fields to include in return result. |
include |
String or Object or Array
|
See PersistedModel.include documentation. |
limit |
Number
|
Maximum number of instances to return. |
order |
String
|
Sort order: either "ASC" for ascending or "DESC" for descending. |
skip |
Number
|
Number of results to skip. |
where |
Object
|
Where clause, like |
Name | Type | Description |
---|---|---|
err |
Error
|
Error object; see Error object. |
models |
Array
|
Model instances matching the filter, or null if none found. |
Find object by ID with an optional filter for include/fields.
Name | Type | Description |
---|---|---|
id |
|
Primary key value |
[filter] |
Object
|
Optional Filter JSON object; see below. |
callback |
Function
|
Callback function called with |
Name | Type | Description |
---|---|---|
fields |
String or Object or Array
|
Identify fields to include in return result. |
include |
String or Object or Array
|
See PersistedModel.include documentation. |
Name | Type | Description |
---|---|---|
err |
Error
|
Error object; see Error object. |
instance |
Object
|
Model instance matching the specified ID or null if no instance matches. |
Find one model instance that matches filter
specification.
Same as find
, but limited to one result;
Returns object, not collection.
Name | Type | Description |
---|---|---|
[filter] |
Object
|
Optional Filter JSON object; see below. |
callback |
Function
|
Callback function called with |
Name | Type | Description |
---|---|---|
fields |
String or Object or Array
|
Identify fields to include in return result. |
include |
String or Object or Array
|
See PersistedModel.include documentation. |
order |
String
|
Sort order: either "ASC" for ascending or "DESC" for descending. |
skip |
Number
|
Number of results to skip. |
where |
Object
|
Where clause, like |
Name | Type | Description |
---|---|---|
err |
Error
|
Error object; see Error object. |
model |
Array
|
First model instance that matches the filter or null if none found. |
Finds one record matching the optional filter object. If not found, creates
the object using the data provided as second argument. In this sense it is
the same as find
, but limited to one object. Returns an object, not
collection. If you don't provide the filter object argument, it tries to
locate an existing object that matches the data
argument.
Name | Type | Description |
---|---|---|
[filter] |
Object
|
Optional Filter object; see below. |
data |
Object
|
Data to insert if object matching the |
callback |
Function
|
Callback function called with |
Name | Type | Description |
---|---|---|
fields |
String or Object or Array
|
Identify fields to include in return result. |
include |
String or Object or Array
|
See PersistedModel.include documentation. |
limit |
Number
|
Maximum number of instances to return. |
order |
String
|
Sort order: either "ASC" for ascending or "DESC" for descending. |
skip |
Number
|
Number of results to skip. |
where |
Object
|
Where clause, like |
Name | Type | Description |
---|---|---|
err |
Error
|
Error object; see Error object. |
instance |
Object
|
Model instance matching the |
created |
Boolean
|
True if the instance matching the |
Get the Change
model.
Throws an error if the change model is not correctly setup.
Get the id
property name of the constructor.
Name | Type | Description |
---|---|---|
result |
String
|
The |
Get the source identifier for this model or dataSource.
Name | Type | Description |
---|---|---|
callback |
Function
|
Callback function called with |
Name | Type | Description |
---|---|---|
err |
Error
|
Error object; see Error object. |
sourceId |
String
|
Source identifier for the model or dataSource. |
Handle a change error. Override this method in a subclassing model to customize change error handling.
Name | Type | Description |
---|---|---|
err |
Error
|
Error object; see Error object. |
Specify that a change to the model with the given ID has occurred.
Name | Type | Description |
---|---|---|
id |
|
The ID of the model that has changed. |
callback |
Function
|
Name | Type | Description |
---|---|---|
err |
Error
|
Replicate changes since the given checkpoint to the given target model.
Name | Type | Description |
---|---|---|
[since] |
Number
|
Since this checkpoint |
targetModel |
Model
|
Target this model class |
[options] |
Object
|
|
[options.filter] |
Object
|
Replicate models that match this filter |
[callback] |
Function
|
Callback function called with |
Name | Type | Description |
---|---|---|
err |
Error
|
Error object; see Error object. |
conflicts |
Array.<Conflict>
|
A list of changes that could not be replicated due to conflicts. |
{Object] checkpoints The new checkpoints to use as the "since" |
|
argument for the next replication. |
Update multiple instances that match the where clause.
Example:
Employee.updateAll({managerId: 'x001'}, {managerId: 'x002'}, function(err, info) {
...
});
Name | Type | Description |
---|---|---|
[where] |
Object
|
Optional |
data |
Object
|
Object containing data to replace matching instances, if any. |
callback |
Function
|
Callback function called with |
Name | Type | Description |
---|---|---|
err |
Error
|
Error object; see Error object. |
info |
Object
|
Additional information about the command outcome. |
info.count |
Number
|
Number of instances (rows, documents) updated. |
Update or insert a model instance
Name | Type | Description |
---|---|---|
data |
Object
|
The model instance data to insert. |
callback |
Function
|
Callback function called with |
Name | Type | Description |
---|---|---|
err |
Error
|
Error object; see Error object. |
model |
Object
|
Updated model instance. |
Deletes the model from persistence.
Triggers destroy
hook (async) before and after destroying object.
Name | Type | Description |
---|---|---|
callback |
Function
|
Callback function. |
Get the id
value for the PersistedModel
.
Name | Type | Description |
---|---|---|
result |
|
The |
Get the id
property name of the constructor.
Name | Type | Description |
---|---|---|
result |
String
|
The |
Determine if the data model is new.
Name | Type | Description |
---|---|---|
result |
Boolean
|
Returns true if the data model is new; false otherwise. |
Reload object from persistence. Requires id
member of object
to be able to call find
.
Name | Type | Description |
---|---|---|
callback |
Function
|
Callback function called with |
Name | Type | Description |
---|---|---|
err |
Error
|
Error object; see Error object. |
instance |
Object
|
Model instance. |
Save model instance. If the instance doesn't have an ID, then calls create instead. Triggers: validate, save, update, or create.
Name | Type | Description |
---|---|---|
[options] |
Object
|
See below. |
callback |
Function
|
Optional callback function called with |
Name | Type | Description |
---|---|---|
validate |
Boolean
|
Perform validation before saving. Default is true. |
throws |
Boolean
|
If true, throw a validation error; WARNING: This can crash Node. If false, report the error via callback. Default is false. |
Name | Type | Description |
---|---|---|
err |
Error
|
Error object; see Error object. |
instance |
Object
|
Model instance saved or created. |
Set the correct id
property for the PersistedModel
. Uses the setId
method if the model is attached to
connector that defines it. Otherwise, uses the default lookup.
Override this method to handle complex IDs.
Name | Type | Description |
---|---|---|
val |
|
The |
Update a single attribute.
Equivalent to updateAttributes({name: 'value'}, cb)
Name | Type | Description |
---|---|---|
name |
String
|
Name of property. |
value |
Mixed
|
Value of property. |
callback |
Function
|
Callback function called with |
Name | Type | Description |
---|---|---|
err |
Error
|
Error object; see Error object. |
instance |
Object
|
Updated instance. |
Update set of attributes. Performs validation before updating.
Triggers: validation
, save
and update
hooks
Name | Type | Description |
---|---|---|
data |
Object
|
Data to update. |
callback |
Function
|
Callback function called with |
Name | Type | Description |
---|---|---|
err |
Error
|
Error object; see Error object. |
instance |
Object
|
Updated instance. |
Context middleware.
var app = loopback();
app.use(loopback.context(options);
app.use(loopback.rest());
app.listen();
Name | Type | Description |
---|---|---|
[options] |
Object
|
Options for context |
Name | Type | Description |
---|---|---|
name |
String
|
Context scope name. |
enableHttpContext |
Boolean
|
Whether HTTP context is enabled. Default is false. |
Expose models over REST.
For example:
app.use(loopback.rest());
For more information, see Exposing models over a REST API.
Serve static assets of a LoopBack application.
Name | Type | Description |
---|---|---|
root |
string
|
The root directory from which the static assets are to be served. |
options |
object
|
Refer to express documentation for the full list of available options. |
Return HTTP response with basic application status information: date the application was started and uptime, in JSON format. For example:
{
"started": "2014-06-05T00:26:49.750Z",
"uptime": 9.394
}
Rewrite the url to replace current user literal with the logged in user id
Check for an access token in cookies, headers, and query string parameters. This function always checks for the following:
access_token
(params only)X-Access-Token
(headers only)authorization
(headers and cookies)It checks for these values in cookies, headers, and query string parameters in addition to the items specified in the options parameter.
NOTE: This function only checks for signed cookies.
The following example illustrates how to check for an accessToken
in a custom cookie, query string parameter
and header called foo-auth
.
app.use(loopback.token({
cookies: ['foo-auth'],
headers: ['foo-auth', 'X-Foo-Auth'],
params: ['foo-auth', 'foo_auth']
}));
Name | Type | Description |
---|---|---|
[options] |
Object
|
Each option array is used to add additional keys to find an |
Name | Type | Description |
---|---|---|
[cookies] |
Array
|
Array of cookie names. |
[headers] |
Array
|
Array of header names. |
[params] |
Array
|
Array of param names. |
[searchDefaultTokenKeys] |
Boolean
|
Use the default search locations for Token in request |
[enableDoublecheck] |
Boolean
|
Execute middleware although an instance mounted earlier in the chain didn't find a token |
[overwriteExistingToken] |
Boolean
|
only has effect in combination with |
[model] |
Function or String
|
AccessToken model name or class to use. |
[currentUserLiteral] |
String
|
String literal for the current user. |
Convert any request not handled so far to a 404 error to be handled by error-handling middleware.
Token based authentication and access control.
Default ACLs
*
Name | Type | Description |
---|---|---|
id |
String
|
Generated token ID. |
ttl |
Number
|
Time to live in seconds, 2 weeks by default. |
created |
Date
|
When the token was created. |
settings |
Object
|
Extends the |
settings.accessTokenIdLength |
Number
|
Length of the base64-encoded string access token. Default value is 64. Increase the length for a more secure access token. |
Create a cryptographically random access token id.
Name | Type | Description |
---|---|---|
callback |
Function
|
Name | Type | Description |
---|---|---|
err |
Error
|
|
token |
String
|
Find a token for the given ServerRequest
.
Name | Type | Description |
---|---|---|
req |
ServerRequest
|
|
[options] |
Object
|
Options for finding the token |
callback |
Function
|
Name | Type | Description |
---|---|---|
err |
Error
|
|
token |
AccessToken
|
Validate the token.
Name | Type | Description |
---|---|---|
callback |
Function
|
Name | Type | Description |
---|---|---|
err |
Error
|
|
isValid |
Boolean
|
A Model for access control meta data.
System grants permissions to principals (users/applications, can be grouped into roles).
Protected resource: the model data and operations (model/property/method/relation/…)
For a given principal, such as client application and/or user, is it allowed to access (read/write/execute) the protected resource?
Name | Type | Description |
---|---|---|
model |
String
|
Name of the model. |
property |
String
|
Name of the property, method, scope, or relation. |
accessType |
String
|
Type of access being granted: one of READ, WRITE, or EXECUTE. |
permission |
String
|
Type of permission granted. One of:
|
principalType |
String
|
Type of the principal; one of: Application, Use, Role. |
principalId |
String
|
ID of the principal - such as appId, userId or roleId. |
settings |
Object
|
Extends the |
settings.defaultPermission |
String
|
Default permission setting: ALLOW, DENY, ALARM, or AUDIT. Default is ALLOW. Set to DENY to prohibit all API access by default. |
Check if the request has the permission to access.
Name | Type | Description |
---|---|---|
context |
Object
|
See below. |
callback |
Function
|
Callback function |
Name | Type | Description |
---|---|---|
principals |
Array.<Object>
|
An array of principals. |
model |
String or Model
|
The model name or model class. |
id |
|
The model instance ID. |
property |
String
|
The property/method/relation name. |
accessType |
String
|
The access type: READ, REPLICATE, WRITE, or EXECUTE. |
Check if the given access token can invoke the method
Name | Type | Description |
---|---|---|
token |
AccessToken
|
The access token |
model |
String
|
The model name |
modelId |
|
The model id |
method |
String
|
The method name |
callback |
Function
|
Callback function |
Name | Type | Description |
---|---|---|
err |
String or Error
|
The error object |
allowed |
Boolean
|
is the request allowed |
Check if the given principal is allowed to access the model/property
Name | Type | Description |
---|---|---|
principalType |
String
|
The principal type. |
principalId |
String
|
The principal ID. |
model |
String
|
The model name. |
property |
String
|
The property/method/relation name. |
accessType |
String
|
The access type. |
callback |
Function
|
Callback function. |
Name | Type | Description |
---|---|---|
err |
String or Error
|
The error object |
result |
AccessRequest
|
The access permission |
Calculate the matching score for the given rule and request
Name | Type | Description |
---|---|---|
rule |
ACL
|
The ACL entry |
req |
AccessRequest
|
The request |
Name | Type | Description |
---|---|---|
result |
Number
|
Check if the given principal is mapped to the role
Name | Type | Description |
---|---|---|
principalType |
String
|
Principal type |
principalId |
String
|
Principal id/name |
role |
String
|
Role id/name |
cb |
Function
|
Callback function |
Resolve a principal by type/id
Name | Type | Description |
---|---|---|
type |
String
|
Principal type - ROLE/APP/USER |
id |
String or Number
|
Principal id or name |
cb |
Function
|
Callback function |
Get matching score for the given AccessRequest
.
Name | Type | Description |
---|---|---|
req |
AccessRequest
|
The request |
Name | Type | Description |
---|---|---|
result |
Number
|
score |
Manage client applications and organize their users.
Name | Type | Description |
---|---|---|
id |
String
|
Generated ID. |
name |
String
|
Name; required. |
description |
String
|
Text description |
icon |
String
|
String Icon image URL. |
owner |
String
|
User ID of the developer who registers the application. |
String
|
E-mail address |
|
emailVerified |
Boolean
|
Whether the e-mail is verified. |
url |
String
|
OAuth 2.0 application URL. |
{String}[] |
|
callbackUrls The OAuth 2.0 code/token callback URL. |
status |
String
|
Status of the application; Either |
created |
Date
|
Date Application object was created. Default: current date. |
modified |
Date
|
Date Application object was modified. Default: current date. |
pushSettings.apns |
Object
|
APNS configuration, see the options below and also https://github.com/argon/node-apn/blob/master/doc/apn.markdown |
pushSettings.apns.production |
Boolean
|
Whether to use production Apple Push Notification Service (APNS) servers to send push notifications. If true, uses |
pushSettings.apns.certData |
String
|
The certificate data loaded from the cert.pem file (APNS). |
pushSettings.apns.keyData |
String
|
The key data loaded from the key.pem file (APNS). |
pushSettings.apns.pushOptions.gateway |
String
|
(APNS). |
pushSettings.apns.pushOptions.port |
Number
|
(APNS). |
pushSettings.apns.feedbackOptions.gateway |
String
|
(APNS). |
pushSettings.apns.feedbackOptions.port |
Number
|
(APNS). |
pushSettings.apns.feedbackOptions.batchFeedback |
Boolean
|
(APNS). |
pushSettings.apns.feedbackOptions.interval |
Number
|
(APNS). |
pushSettings.gcm.serverApiKey: |
String
|
Google Cloud Messaging API key. |
authenticationEnabled |
Boolean
|
|
anonymousAllowed |
Boolean
|
|
authenticationSchemes |
Array
|
List of authentication schemes (see below). |
authenticationSchemes.scheme |
String
|
Scheme name. Supported values: |
authenticationSchemes.credential |
Object
|
Scheme-specific credentials. |
Authenticate the application id and key.
Name | Type | Description |
---|---|---|
appId |
Any
|
|
key |
String
|
|
callback |
Function
|
Name | Type | Description |
---|---|---|
err |
Error
|
|
matched |
String
|
The matching key; one of: - clientKey
|
Register a new application
Name | Type | Description |
---|---|---|
owner |
String
|
Owner's user ID. |
name |
String
|
Name of the application |
options |
Object
|
Other options |
callback |
Function
|
Callback function |
Reset keys for a given application by the appId
Name | Type | Description |
---|---|---|
appId |
Any
|
|
callback |
Function
|
Name | Type | Description |
---|---|---|
err |
Error
|
Reset keys for the application instance
Name | Type | Description |
---|---|---|
callback |
Function
|
Name | Type | Description |
---|---|---|
err |
Error
|
Change list entry.
Name | Type | Description |
---|---|---|
id |
String
|
Hash of the modelName and ID. |
rev |
String
|
The current model revision. |
prev |
String
|
The previous model revision. |
checkpoint |
Number
|
The current checkpoint at time of the change. |
modelName |
String
|
Model name. |
modelId |
String
|
Model ID. |
settings |
Object
|
Extends the |
settings.hashAlgorithm |
String
|
Algorithm used to create cryptographic hash, used as argument to crypto.createHash. Default is sha1. |
settings.ignoreErrors |
Boolean
|
By default, when changes are rectified, an error will throw an exception. However, if this setting is true, then errors will not throw exceptions. |
Are both changes deletes?
Name | Type | Description |
---|---|---|
a |
Change
|
|
b |
Change
|
Determine the differences for a given model since a given checkpoint.
The callback will contain an error or result
.
result
{
deltas: Array,
conflicts: Array
}
deltas
An array of changes that differ from remoteChanges
.
conflicts
An array of changes that conflict with remoteChanges
.
Name | Type | Description |
---|---|---|
modelName |
String
|
|
since |
Number
|
Compare changes after this checkpoint |
remoteChanges |
Array.<Change>
|
A set of changes to compare |
callback |
Function
|
Name | Type | Description |
---|---|---|
err |
Error
|
|
result |
Object
|
See above. |
Find or create a change for the given model.
Name | Type | Description |
---|---|---|
modelName |
String
|
|
modelId |
String
|
|
callback |
Function
|
Name | Type | Description |
---|---|---|
err |
Error
|
|
change |
Change
|
Get the checkpoint model.
Create a hash of the given string
with the options.hashAlgorithm
.
Default: sha1
Name | Type | Description |
---|---|---|
str |
String
|
The string to be hashed |
Get an identifier for a given model.
Name | Type | Description |
---|---|---|
modelName |
String
|
|
modelId |
String
|
Correct all change list entries.
Name | Type | Description |
---|---|---|
cb |
Function
|
Track the recent change of the given modelIds.
Name | Type | Description |
---|---|---|
modelName |
String
|
|
modelIds |
Array
|
|
callback |
Function
|
Name | Type | Description |
---|---|---|
err |
Error
|
|
changes |
Array
|
Changes that were tracked |
Get the revision string for the given object
Name | Type | Description |
---|---|---|
inst |
Object
|
The data to get the revision string for |
Does this change conflict with the given change.
Name | Type | Description |
---|---|---|
change |
Change
|
Get a change's current revision based on current data.
Name | Type | Description |
---|---|---|
callback |
Function
|
Name | Type | Description |
---|---|---|
err |
Error
|
|
rev |
String
|
The current revision |
Compare two changes.
Name | Type | Description |
---|---|---|
change |
Change
|
Get the Model
class for change.modelName
.
Determine if the change is based on the given change.
Name | Type | Description |
---|---|---|
change |
Change
|
Update (or create) the change with the current revision.
Name | Type | Description |
---|---|---|
callback |
Function
|
Name | Type | Description |
---|---|---|
err |
Error
|
|
change |
Change
|
Get a change's type. Returns one of:
Change.UPDATE
Change.CREATE
Change.DELETE
Change.UNKNOWN
When two changes conflict a conflict is created.
Note: call conflict.fetch()
to get the target
and source
models.
Name | Type | Description |
---|---|---|
modelId |
|
|
SourceModel |
PersistedModel
|
|
TargetModel |
PersistedModel
|
Name | Type | Description |
---|---|---|
source |
ModelClass
|
The source model instance |
target |
ModelClass
|
The target model instance |
Get the conflicting changes.
Name | Type | Description |
---|---|---|
callback |
Function
|
Name | Type | Description |
---|---|---|
err |
Error
|
|
sourceChange |
Change
|
|
targetChange |
Change
|
Fetch the conflicting models.
Name | Type | Description |
---|---|---|
callback |
Function
|
Name | Type | Description |
---|---|---|
err |
Error
|
|
source |
PersistedModel
|
|
target |
PersistedModel
|
Resolve the conflict.
Set the source change's previous revision to the current revision of the (conflicting) target change. Since the changes are no longer conflicting and appear as if the source change was based on the target, they will be replicated normally as part of the next replicate() call.
This is effectively resolving the conflict using the source version.
Name | Type | Description |
---|---|---|
callback |
Function
|
Name | Type | Description |
---|---|---|
err |
Error
|
Resolve the conflict using the supplied instance data.
Name | Type | Description |
---|---|---|
data |
Object
|
The set of changes to apply on the model instance. Use |
callback |
Function
|
Name | Type | Description |
---|---|---|
err |
Error
|
Resolve the conflict using the instance data in the source model.
Name | Type | Description |
---|---|---|
callback |
Function
|
Name | Type | Description |
---|---|---|
err |
Error
|
Resolve the conflict using the instance data in the target model.
Name | Type | Description |
---|---|---|
callback |
Function
|
Name | Type | Description |
---|---|---|
err |
Error
|
Return a new Conflict instance with swapped Source and Target models.
This is useful when resolving a conflict in one-way replication, where the source data must not be changed:
conflict.swapParties().resolveUsingTarget(cb);
Name | Type | Description |
---|---|---|
result |
Conflict
|
A new Conflict instance. |
Determine the conflict type.
Possible results are
Change.UPDATE
: Source and target models were updated.Change.DELETE
: Source and or target model was deleted.Change.UNKNOWN
: the conflict type is uknown or due to an error.Name | Type | Description |
---|---|---|
callback |
Function
|
Name | Type | Description |
---|---|---|
err |
Error
|
|
type |
String
|
The conflict type. |
Email model. Extends LoopBack base Model.
Name | Type | Description |
---|---|---|
to |
String
|
Email addressee. Required. |
from |
String
|
Email sender address. Required. |
subject |
String
|
Email subject string. Required. |
text |
String
|
Text body of email. |
html |
String
|
HTML body of email. |
Send an email with the given options
.
Example Options:
{
from: "Fred Foo <foo@blurdybloop.com>", // sender address
to: "bar@blurdybloop.com, baz@blurdybloop.com", // list of receivers
subject: "Hello", // Subject line
text: "Hello world", // plaintext body
html: "<b>Hello world</b>" // html body
}
See https://github.com/andris9/Nodemailer for other supported options.
Name | Type | Description |
---|---|---|
options |
Object
|
See below |
callback |
Function
|
Called after the e-mail is sent or the sending failed |
Name | Type | Description |
---|---|---|
from |
String
|
Senders's email address |
to |
String
|
List of one or more recipient email addresses (comma-delimited) |
subject |
String
|
Subject line |
text |
String
|
Body text |
html |
String
|
Body HTML (optional) |
A shortcut for Email.send(this).
The Role model
List roles for a given principal.
Name | Type | Description |
---|---|---|
context |
Object
|
The security context. |
callback |
Function
|
Callback function. |
Name | Type | Description |
---|---|---|
err |
Error
|
Error object. |
roles |
Array.<String>
|
An array of role IDs |
Check if the user ID is authenticated
Name | Type | Description |
---|---|---|
context |
Object
|
The security context. |
callback |
Function
|
Callback function. |
Name | Type | Description |
---|---|---|
err |
Error
|
Error object. |
isAuthenticated |
Boolean
|
True if the user is authenticated. |
Check if a given principal is in the specified role.
Name | Type | Description |
---|---|---|
role |
String
|
The role name. |
context |
Object
|
The context object. |
callback |
Function
|
Callback function. |
Name | Type | Description |
---|---|---|
err |
Error
|
Error object. |
isInRole |
Boolean
|
True if the principal is in the specified role. |
Check if a given user ID is the owner the model instance.
Name | Type | Description |
---|---|---|
modelClass |
Function
|
The model class |
modelId |
|
The model ID |
userId |
|
The user ID |
callback |
Function
|
Callback function |
Add custom handler for roles.
Name | Type | Description |
---|---|---|
role |
String
|
Name of role. |
resolver |
Function
|
Function that determines if a principal is in the specified role. Should provide a callback or return a promise. |
The RoleMapping
model extends from the built in loopback.Model
type.
Name | Type | Description |
---|---|---|
id |
String
|
Generated ID. |
name |
String
|
Name of the role. |
Description |
String
|
Text description. |
Get the application principal
Name | Type | Description |
---|---|---|
callback |
Function
|
Name | Type | Description |
---|---|---|
err |
Error
|
|
application |
Application
|
Get the child role principal
Name | Type | Description |
---|---|---|
callback |
Function
|
Name | Type | Description |
---|---|---|
err |
Error
|
|
childUser |
User
|
Get the user principal
Name | Type | Description |
---|---|---|
callback |
Function
|
Name | Type | Description |
---|---|---|
err |
Error
|
|
user |
User
|
Resource owner grants/delegates permissions to client applications
For a protected resource, does the client application have the authorization from the resource owner (user or system)?
Scope has many resource access entries
Check if the given scope is allowed to access the model/property
Name | Type | Description |
---|---|---|
scope |
String
|
The scope name |
model |
String
|
The model name |
property |
String
|
The property/method/relation name |
accessType |
String
|
The access type |
callback |
Function
|
Name | Type | Description |
---|---|---|
err |
String or Error
|
The error object |
result |
AccessRequest
|
The access permission |
Built-in User model. Extends LoopBack PersistedModel.
Default User
ACLs.
*
create
deleteById
login
logout
findById
updateAttributes
Name | Type | Description |
---|---|---|
username |
String
|
Must be unique. |
password |
String
|
Hidden from remote clients. |
String
|
Must be valid email. |
|
emailVerified |
Boolean
|
Set when a user's email has been verified via |
verificationToken |
String
|
Set when |
realm |
String
|
The namespace the user belongs to. See Partitioning users with realms for details. |
created |
Date
|
The property is not used by LoopBack, you are free to use it for your own purposes. |
lastUpdated |
Date
|
The property is not used by LoopBack, you are free to use it for your own purposes. |
status |
String
|
The property is not used by LoopBack, you are free to use it for your own purposes. |
settings |
Object
|
Extends the |
settings.emailVerificationRequired |
Boolean
|
Require the email verification process before allowing a login. |
settings.ttl |
Number
|
Default time to live (in seconds) for the |
settings.maxTTL |
Number
|
The max value a user can request a token to be alive / valid for. Default is |
settings.realmRequired |
Boolean
|
Require a realm when logging in a user. |
settings.realmDelimiter |
String
|
When set a realm is required. |
settings.resetPasswordTokenTTL |
Number
|
Time to live for password reset |
settings.saltWorkFactor |
Number
|
The |
settings.caseSensitiveEmail |
Boolean
|
Enable case sensitive email. |
Confirm the user's identity.
Name | Type | Description |
---|---|---|
userId |
Any
|
|
token |
String
|
The validation token |
redirect |
String
|
URL to redirect the user to once confirmed |
callback |
Function
|
Name | Type | Description |
---|---|---|
err |
Error
|
A default verification token generator which accepts the user the token is
being generated for and a callback function to indicate completion.
This one uses the crypto library and 64 random bytes (converted to hex)
for the token. When used in combination with the user.verify() method this
function will be called with the user
object as it's context (this
).
Name | Type | Description |
---|---|---|
user |
object
|
The User this token is being generated for. |
cb |
Function
|
The generator must pass back the new token with this function call |
Login a user by with the given credentials
.
User.login({username: 'foo', password: 'bar'}, function (err, token) {
console.log(token.id);
});
Name | Type | Description |
---|---|---|
credentials |
Object
|
username/password or email/password |
[include] |
Array.<String> or String
|
Optionally set it to "user" to include the user info |
callback |
Function
|
Callback function |
Name | Type | Description |
---|---|---|
err |
Error
|
Error object |
token |
AccessToken
|
Access token if login is successful |
Logout a user with the given accessToken id.
User.logout('asd0a9f8dsj9s0s3223mk', function (err) {
console.log(err || 'Logged out');
});
Name | Type | Description |
---|---|---|
accessTokenID |
String
|
|
callback |
Function
|
Name | Type | Description |
---|---|---|
err |
Error
|
Normalize the credentials
Name | Type | Description |
---|---|---|
credentials |
Object
|
The credential object |
realmRequired |
Boolean
|
|
realmDelimiter |
String
|
The realm delimiter, if not set, no realm is needed |
Name | Type | Description |
---|---|---|
result |
Object
|
The normalized credential object |
Create a short lived acess token for temporary login. Allows users to change passwords if forgotten.
Name | Type | Description |
---|---|---|
options |
Object
|
|
callback |
Function
|
Name | Type | Description |
---|---|---|
String
|
The user's email address |
Name | Type | Description |
---|---|---|
err |
Error
|
Create access token for the logged in user. This method can be overridden to customize how access tokens are generated
Name | Type | Description |
---|---|---|
ttl |
Number
|
The requested ttl |
[options] |
Object
|
The options for access token, such as scope, appId |
cb |
Function
|
The callback function |
Name | Type | Description |
---|---|---|
err |
String or Error
|
The error string or object |
token |
AccessToken
|
The generated access token object |
Compare the given password
with the users hashed password.
Name | Type | Description |
---|---|---|
password |
String
|
The plain text password |
Name | Type | Description |
---|---|---|
result |
Boolean
|
Verify a user's identity by sending them a confirmation email.
var options = {
type: 'email',
to: user.email,
template: 'verify.ejs',
redirect: '/',
tokenGenerator: function (user, cb) { cb("random-token"); }
};
user.verify(options, next);
Name | Type | Description |
---|---|---|
options |
Object
|
Name | Type | Description |
---|---|---|
type |
String
|
Must be 'email'. |
to |
String
|
Email address to which verification email is sent. |
from |
String
|
Sender email addresss, for example |
subject |
String
|
Subject line text. |
text |
String
|
Text of email. |
template |
String
|
Name of template that displays verification page, for example, `'verify.ejs'. |
redirect |
String
|
Page to which user will be redirected after they verify their email, for example |
generateVerificationToken |
Function
|
A function to be used to generate the verification token. It must accept the user object and a
callback function. This function should NOT add the token to the user
object, instead simply execute the callback with the token! User saving
and email sending will be handled in the |