diff --git a/README.md b/README.md index 14a66f628..33ecd580b 100644 --- a/README.md +++ b/README.md @@ -12,9 +12,13 @@ v0.9.0 - [Model](#model) - [DataSource](#data-source) - [Connectors](#connectors) - - [GeoPoint](#geo-point) - [Loopback Types](#loopback-types) + - [GeoPoint](#geo-point) - [REST Router](#rest-router) + - [Bundled Models](#bundled-models) + - [User](#user-model) + - [Session](#session-model) + - [Email](#email-model) ## Client API @@ -43,8 +47,10 @@ Create an loopback application. Expose a `Model` to remote clients. - var memory = loopback.createDataSource({connector: loopback.Memory}); + // create a testing data source + var memory = loopback.memory(); var Color = memory.createModel('color', {name: String}); + Color.attachTo(memory); app.model(Color); app.use(loopback.rest()); @@ -92,6 +98,12 @@ Define an loopback model. ### Validation (expiremental) +#### Model.validatesFormatOf(property, options) + +Require a model to include a property that matches the given format. + + User.validatesFormat('name', {with: /\w+/}); + #### Model.validatesPresenceOf(properties...) Require a model to include a property to be considered valid. @@ -193,10 +205,56 @@ Attach a model to a [DataSource](#data-source). Attaching a [DataSource](#data-s #### CRUD and Query Mixins -Mixins are added by attaching a vanilla model to a data source with a connector. Each [connector](#connectors) enables its own set of operations that are attached to a `Model` as methods. To see available methods for a data source with a connector call `dataSource.operations()`. +Mixins are added by attaching a vanilla model to a [data source](#data-source) with a [connector](#connectors). Each [connector](#connectors) enables its own set of operations that are mixed into a `Model` as methods. To see available methods for a data source call `dataSource.operations()`. + +Log the available methods for a memory data source. + + var ops = loopback + .createDataSource({connector: loopback.Memory}) + .operations(); + + console.log(Object.keys(ops)); + +Outputs: + + [ 'create', + 'updateOrCreate', + 'upsert', + 'findOrCreate', + 'exists', + 'findById', + 'find', + 'all', + 'findOne', + 'destroyAll', + 'deleteAll', + 'count', + 'include', + 'relationNameFor', + 'hasMany', + 'belongsTo', + 'hasAndBelongsToMany', + 'save', + 'isNewRecord', + 'destroy', + 'delete', + 'updateAttribute', + 'updateAttributes', + 'reload' ] + +Here is the definition of the `count()` operation. + + { + accepts: [ { arg: 'where', type: 'object' } ], + http: { verb: 'get', path: '/count' }, + remoteEnabled: true, + name: 'count' + } #### Static Methods +**Note:** These are the default mixin methods for a `Model` attached to a data source. See the specific connector for additional API documentation. + ##### Model.create(data, [callback]) Create an instance of Model with given data and save to the attached data source. Callback is optional. @@ -226,10 +284,24 @@ Find all instances of Model, matched by query. Fields used for filter and sort s - **order** `String` - **limit** `Number` - **skip** `Number` - -Find the second page of 10 users over age 21 in descending order. - - User.find({where: {age: {gt: 21}}, order: 'age DESC', limit: 10, skip: 10}) + - **fields** `Object|Array|String` + - `['foo']` or `'foo'` - include only the foo property + - `['foo', 'bar']` - include the foo and bar properties + - `{foo: true}` - include only foo + - `{bat: false}` - include all properties, exclude bat + +Find the second page of 10 users over age 21 in descending order exluding the password property. + + User.find({ + where: { + age: {gt: 21}}, + order: 'age DESC', + limit: 10, + skip: 10, + fields: {password: false} + }, + console.log + ); **Note:** See the specific connector's [docs](#connectors) for more info. @@ -261,8 +333,6 @@ Update when record with id=data.id found, insert otherwise. **Note:** no setters Define a static model method. - - User.login = function (username, password, fn) { var passwordHash = hashPassword(password); this.findOne({username: username}, function (err, user) { @@ -298,6 +368,8 @@ Setup the static model method to be exposed to clients as a [remote method](#rem #### Instance Methods +**Note:** These are the default mixin methods for a `Model` attached to a data source. See the specific connector for additional API documentation. + ##### model.save([options], [callback]) Save an instance of a Model to the attached data source. @@ -349,13 +421,18 @@ Both instance and static methods can be exposed to clients. A remote method must Expose a remote method. Product.stats = function(fn) { - myApi.getStats('products', fn); + var calc = require('./stats'); + + Product.find(function(err, products) { + var productStats = calc(products); + fn(null, productStats); + }); } loopback.remoteMethod( Product.stats, { - returns: {arg: 'stats', type: 'array'}, + returns: {arg: 'stats', type: 'object'}, http: {path: '/info', verb: 'get'} } ); @@ -703,16 +780,16 @@ Create a data source with a specific connector. See **available connectors** for **Available Connectors** - - [Oracle](http://github.com/strongloop/loopback-connectors/oracle) - - [In Memory](http://github.com/strongloop/loopback-connectors/memory) - - TODO - [REST](http://github.com/strongloop/loopback-connectors/rest) - - TODO - [MySQL](http://github.com/strongloop/loopback-connectors/mysql) - - TODO - [SQLite3](http://github.com/strongloop/loopback-connectors/sqlite) - - TODO - [Postgres](http://github.com/strongloop/loopback-connectors/postgres) - - TODO - [Redis](http://github.com/strongloop/loopback-connectors/redis) - - TODO - [MongoDB](http://github.com/strongloop/loopback-connectors/mongo) - - TODO - [CouchDB](http://github.com/strongloop/loopback-connectors/couch) - - TODO - [Firebird](http://github.com/strongloop/loopback-connectors/firebird) + - [In Memory](#memory-connector) + - [REST](http://github.com/strongloop/loopback-connector-rest) + - [Oracle](http://github.com/strongloop/loopback-connector-oracle) + - [MongoDB](http://github.com/strongloop/loopback-connector-mongodb) + - TODO - [MySQL](http://github.com/strongloop/loopback-connector-mysql) + - TODO - [SQLite3](http://github.com/strongloop/loopback-connector-sqlite) + - TODO - [Postgres](http://github.com/strongloop/loopback-connector-postgres) + - TODO - [Redis](http://github.com/strongloop/loopback-connector-redis) + - TODO - [CouchDB](http://github.com/strongloop/loopback-connector-couch) + - TODO - [Firebird](http://github.com/strongloop/loopback-connector-firebird) **Installing Connectors** @@ -724,6 +801,49 @@ Include the connector in your package.json dependencies and run `npm install`. } } +##### Memory Connector + +The built-in memory connector allows you to test your application without connecting to an actual persistent data source, such as a database. Although the memory connector is very well tested it is not recommended to be used in production. Creating a data source using the memory connector is very simple. + + // use the built in memory function + // to create a memory data source + var memory = loopback.memory(); + + // or create it using the standard + // data source creation api + var memory = loopback.createDataSource({ + connector: loopback.Memory + }); + + // create a model using the + // memory data source + var properties = { + name: String, + price: Number + }; + + var Product = memory.createModel('product', properties); + + Product.create([ + {name: 'apple', price: 0.79}, + {name: 'pear', price: 1.29}, + {name: 'orange', price: 0.59}, + ], count); + + function count() { + Product.count(console.log); // 3 + } + +###### Operations + +**CRUD / Query** + +The memory connector supports all the standard [query and crud operations](#crud-and-query-mixins) to allow you to test your models against an in memory data source. + +**GeoPoint Filtering** + +The memory connector also supports geo-filtering when using the `find()` operation with an attached model. See [GeoPoint](#geopoint) for more information on geo-filtering. + ### GeoPoint Use the `GeoPoint` class. @@ -794,14 +914,16 @@ Various APIs in Loopback accept type descriptions (eg. [remote methods](#remote- - `Buffer` - a node.js Buffer object - [GeoPoint](#geopoint) - an loopback GeoPoint object. TODO -#### Bundled Models +## Bundled Models The Loopback library is unopinioned in the way you define your app's data and logic. Loopback also bundles useful pre-built models for common use cases. - - User - _TODO_ register and authenticate users of your app locally or against 3rd party services. + - User - register and authenticate users of your app locally or against 3rd party services. - Notification - _TODO_ create, store, schedule and send push notifications to your app users. - - Email - _TODO_ schedule and send emails to your app users using smtp or 3rd party services. + - Email - send emails to your app users using smtp or 3rd party services. - Job - _TODO_ schedule arbitrary code to run at a given time. + +Defining a model with `loopback.createModel()` is really just extending the base `loopback.Model` type using `loopback.Model.extend()`. The bundled models extend from the base `loopback.Model` allowing you to extend them arbitrarily. ### User Model @@ -811,32 +933,38 @@ Register and authenticate users of your app locally or against 3rd party service Extend a vanilla Loopback model using the built in User model. + // create a data source + var memory = loopback.memory(); + // define a User model - var User = loopback.createModel( - 'user', - { - email: { - type: 'EmailAddress', - username: true - }, - password: { - hideRemotely: true, // default for Password - type: 'Password', - min: 4, - max: 26 - } - }, - { - extend: 'User', - } - ); + var User = loopback.User.extend('user'); // attach to the memory connector User.attachTo(memory); + // also attach the session model to a data source + User.session.attachTo(memory); + // expose over the app's api app.model(User); +**Note:** By default the `loopback.User` model uses the `loopback.Session` model to persist sessions. You can change this by setting the `session` property. + +**Note:** You must attach both the `User` and `User.session` model's to a data source! + + // define a custom session model + var MySession = loopback.Session.extend('my-session'); + + // define a custom User model + var User = loopback.User.extend('user'); + + // use the custom session model + User.session = MySession; + + // attaching to + + + #### User Creation Create a user like any other model. @@ -863,7 +991,7 @@ Setup an authentication strategy. // create a custom strategy var LocalStrategy = require('passport-local').Strategy; - User.use(new LocalStrategy(function(username, password, done) { + passport.use(new LocalStrategy(function(username, password, done) { User.findOne({ username: username }, function(err, user) { if (err) { return done(err); } if (!user) { return done(null, false, { message: 'Unknown user ' + username }); } @@ -881,7 +1009,7 @@ Setup an authentication strategy. #### Login a User -Create a session for a user. When called remotely the password is required. +Create a session for a user. User.login({username: 'foo', password: 'bar'}, function(err, session) { console.log(session); @@ -908,71 +1036,86 @@ You must provide a username and password over rest. To ensure these values are e "uid": "123" } -**Note:** The `uid` type will be the same type you specify when creating your model. In this case it is a string. - #### Logout a User - User.logout({username: 'foo'}, function(err) { - console.log(err); - }); +**NODE** -**Note:** When calling this method remotely, the first argument will automatically be populated with the current user's id. If the caller is not logged in the method will fail with an error status code `401`. +// login a user and logout +User.login({"email": "foo@bar.com", "password": "bar"}, function(err, session) { + User.logout(session.id, function(err) { + // user logged out + }); +}); -#### Verify Email Addresses +// logout a user (server side only) +User.findOne({email: 'foo@bar.com'}, function(err, user) { + user.logout(); +}); + +**REST** -To require email verification before a user is allowed to login, supply a verification property with a `verify` settings object. +**Note:** When calling this method remotely, the first argument will be populated with the current user's id. If the caller is not logged in the method will fail with an error status code `401`. - // define a User model - var User = loopback.createModel( - 'user', - { - email: { - type: 'EmailAddress', - username: true - }, - password: { - hideRemotely: true, // default for Password - type: 'Password', - min: 4, - max: 26 - }, - verified: { - hideRemotely: true, - type: 'Boolean', - verify: { - // the model field - // that contains the email - // to verify - email: 'email', - template: 'email.ejs' - } - } - }, - { - extend: 'User', - // the model field - // that contains the user's email - // for verification and password reset - // defaults to 'email' - email: 'email', - resetTemplate: 'reset.ejs' - } - ); +#### Verify Email Addresses + +Require a user to verify their email address before being able to login. This will send an email to the user containing a link to verify their address. Once the user follows the link they will be redirected to `/` and be able to login normally. + + User.requireEmailVerfication = true; + User.afterRemote('create', function(ctx, user, next) { + var options = { + type: 'email', + to: user.email, + from: 'noreply@myapp.com', + subject: 'Thanks for Registering at FooBar', + text: 'Please verify your email address!' + template: 'verify.ejs', + redirect: '/' + }; + + user.verify(options, next); + }); -When a user is created (on the server or remotely) an email is sent to the field that corresponds to `verify.email` or `options.email`. The email contains a link the user must navigate to in order to verify their email address. Once they verify, users are allowed to login normally. Otherwise login attempts will respond with a 'must verify' error. #### Send Reset Password Email Send an email to the user's supplied email address containing a link to reset their password. - - User.sendResetPasswordEmail(email, function(err) { - // email sent + + User.reset(email, function(err) { + console.log('email sent'); }); #### Remote Password Reset -The password reset email will send users to a page rendered by loopback with fields required to reset the user's password. You may customize this template by providing a `resetTemplate` option when defining your user model. +The password reset email will send users to a page rendered by loopback with fields required to reset the user's password. You may customize this template by defining a `resetTemplate` setting. + User.settings.resetTemplate = 'reset.ejs'; + +#### Remote Password Reset Confirmation + +Confirm the password reset. + + User.confirmReset(token, function(err) { + console.log(err || 'your password was reset'); + }); + + +### Session Model + +Identify users by creating sessions when they connect to your loopback app. By default the `loopback.User` model uses the `loopback.Session` model to persist sessions. You can change this by setting the `session` property. + + // define a custom session model + var MySession = loopback.Session.extend('my-session'); + + // define a custom User model + var User = loopback.User.extend('user'); + + // use the custom session model + User.session = MySession; + + // attach both Session and User to a data source + User.attachTo(loopback.memory()); + MySession.attachTo(loopback.memory()); + ### Email Model Send emails from your loopback app. diff --git a/lib/application.js b/lib/application.js index 4f8fa7f95..5e573ad21 100644 --- a/lib/application.js +++ b/lib/application.js @@ -25,21 +25,6 @@ app.remotes = function () { } } -/** - * Expose an object or Class remotely. - * - * @param {String} name The remote namespace (eg. url base) - * @param {Object|Function} obj The object to remote - */ - -app.remote = function (name, obj) { - // add the object to the remote exports - this.remotes().exports[name] = obj; - - // clear the handlers cache - this._handlers = {}; -} - /** * Remove a route by reference. */ @@ -54,20 +39,11 @@ app.disuse = function (route) { } } -/** - * Get ModelBuilder. - */ - -app.modelBuilder = function () { - return this._modelBuilder || (this._modelBuilder = new ModelBuilder()) -} - /** * App models. */ app._models = []; -app._services = []; /** * Expose a model. @@ -76,17 +52,10 @@ app._services = []; */ app.model = function (Model) { - var remotes = this.remotes(); - this._models.push(Model); Model.shared = true; Model.app = this; - if(Model._remoteHooks) { - Model._remoteHooks.emit('attached', app); - } - - // add to the remote exports - this.remote(Model.pluralModelName, Model); + Model.emit('attached', this); } /** @@ -98,28 +67,22 @@ app.models = function () { } /** - * Expose a service. - * - * @param {String} name - * @param {Service} service + * Get all remote objects. */ -app.service = function (name, service) { - this._services.push(service); - service.shared = true; - - service.app = this; +app.remoteObjects = function () { + var result = {}; + var models = this.models(); - // add to the remote exports - this.remote(name, service); -} - -/** - * Get all exposed services. - */ - -app.services = function () { - return this._services; + // add in models + models.forEach(function (ModelCtor) { + // only add shared models + if(ModelCtor.shared && typeof ModelCtor.sharedCtor === 'function') { + result[ModelCtor.pluralModelName] = ModelCtor; + } + }); + + return result; } /** @@ -128,29 +91,4 @@ app.services = function () { app.remotes = function () { return this._remotes || (this._remotes = RemoteObjects.create()); -} - -/** - * Get a remotes handler. - */ - -app.handler = function (type) { - var handler = this._handlers[type]; - - if(!handler) { - // get the sl remoting object - var remotes = this.remotes(); - - // create and save the handler - handler = this._handlers[type] = remotes.handler(type); - } - - return handler; -} - -/*! - * Handlers - */ - -app._handlers = {}; - +} \ No newline at end of file diff --git a/lib/loopback.js b/lib/loopback.js index b0f0164bd..a5466db00 100644 --- a/lib/loopback.js +++ b/lib/loopback.js @@ -4,6 +4,7 @@ var express = require('express') , fs = require('fs') + , ejs = require('ejs') , EventEmitter = require('events').EventEmitter , path = require('path') , proto = require('./application') @@ -150,98 +151,7 @@ loopback.createDataSource = function (name, options) { */ loopback.createModel = function (name, properties, options) { - assert(typeof name === 'string', 'Cannot create a model without a name'); - - var mb = new ModelBuilder(); - var ModelCtor = mb.define(name, properties, options); - - ModelCtor.shared = true; - ModelCtor.sharedCtor = function (data, id, fn) { - if(typeof data === 'function') { - fn = data; - data = null; - id = null; - } else if (typeof id === 'function') { - fn = id; - - if(typeof data !== 'object') { - id = data; - data = null; - } else { - id = null; - } - } - - if(id && data) { - var model = new ModelCtor(data); - model.id = id; - fn(null, model); - } else if(data) { - fn(null, new ModelCtor(data)); - } else if(id) { - ModelCtor.find(id, function (err, model) { - if(err) { - fn(err); - } else if(model) { - fn(null, model); - } else { - err = new Error('could not find a model with id ' + id); - err.statusCode = 404; - - fn(err); - } - }); - } else { - fn(new Error('must specify an id or data')); - } - }; - - ModelCtor.sharedCtor.accepts = [ - {arg: 'data', type: 'object', http: {source: 'body'}}, - {arg: 'id', type: 'any', http: {source: 'url'}} - ]; - - ModelCtor.sharedCtor.http = [ - {path: '/'}, - {path: '/:id'} - ]; - - // before remote hook - ModelCtor.beforeRemote = function (name, fn) { - var self = this; - if(this.app) { - var remotes = this.app.remotes(); - remotes.before(self.pluralModelName + '.' + name, function (ctx, next) { - fn(ctx, ctx.instance, next); - }); - } else { - var args = arguments; - this._remoteHooks.once('attached', function () { - self.beforeRemote.apply(ModelCtor, args); - }); - } - } - - // after remote hook - ModelCtor.afterRemote = function (name, fn) { - var self = this; - if(this.app) { - var remotes = this.app.remotes(); - remotes.after(self.pluralModelName + '.' + name, function (ctx, next) { - fn(ctx, ctx.instance, next); - }); - } else { - var args = arguments; - this._remoteHooks.once('attached', function () { - self.afterRemote.apply(ModelCtor, args); - }); - } - } - - // allow hooks to be added before attaching to an app - ModelCtor._remoteHooks = new EventEmitter(); - - return ModelCtor; + return loopback.Model.extend(name, properties, options); } /** @@ -260,3 +170,49 @@ loopback.remoteMethod = function (fn, options) { fn.http = fn.http || {verb: 'get'}; } +/** + * Create a template helper. + * + * var render = loopback.template('foo.ejs'); + * var html = render({foo: 'bar'}); + * + * @param {String} path Path to the template file. + * @returns {Function} + */ + +loopback.template = function (file) { + var templates = this._templates || (this._templates = {}); + var str = templates[file] || (templates[file] = fs.readFileSync(file, 'utf8')); + return ejs.compile(str); +} + +/** + * Get an in-memory data source. Use one if it already exists. + * + * @param {String} [name] The name of the data source. If not provided, the `'default'` is used. + */ + +loopback.memory = function (name) { + name = name || 'default'; + var memory = ( + this._memoryDataSources + || (this._memoryDataSources = {}) + )[name]; + + if(!memory) { + memory = this._memoryDataSources[name] = loopback.createDataSource({ + connector: loopback.Memory + }); + } + + return memory; +} + +/* + * Built in models / services + */ + +loopback.Model = require('./models/model'); +loopback.Email = require('./models/email'); +loopback.User = require('./models/user'); +loopback.Session = require('./models/session'); diff --git a/lib/middleware/auth.js b/lib/middleware/auth.js new file mode 100644 index 000000000..c278aa8c7 --- /dev/null +++ b/lib/middleware/auth.js @@ -0,0 +1,34 @@ +/** + * Module dependencies. + */ + +var loopback = require('../loopback') + , passport = require('passport'); + +/** + * Export the middleware. + */ + +module.exports = auth; + +/** + * Build a temp app for mounting resources. + */ + +function auth() { + return function (req, res, next) { + var sub = loopback(); + + // TODO clean this up + sub._models = req.app._models; + sub._remotes = req.app._remotes; + + sub.use(loopback.session({secret: 'change me'})) + sub.use(passport.initialize()); + sub.use(passport.session()); + + sub.handle(req, res, next); + } +} + + diff --git a/lib/middleware/rest.js b/lib/middleware/rest.js index 5f1d91442..13be19a55 100644 --- a/lib/middleware/rest.js +++ b/lib/middleware/rest.js @@ -17,16 +17,24 @@ module.exports = rest; function rest() { return function (req, res, next) { - var handler = req.app.handler('rest'); + var app = req.app; + var remotes = app.remotes(); + + // get all remote objects + var objs = app.remoteObjects(); + + // export remote objects + remotes.exports = objs; + + var handler = remotes.handler('rest'); if(req.url === '/routes') { res.send(handler.adapter.allRoutes()); } else if(req.url === '/models') { - return res.send(req.app.remotes().toJSON()); + return res.send(remotes.toJSON()); } else { handler(req, res, next); } } } - diff --git a/lib/models/acl.js b/lib/models/acl.js index 7c70af43d..42c80a04d 100644 --- a/lib/models/acl.js +++ b/lib/models/acl.js @@ -20,32 +20,19 @@ Factors to be authorized against: Class level permissions, for example, Album * model name: Album * methods +// blog posts +allow: ['owner', 'admin'] to: '*' // allow owner's of posts and admins to do anything +allow: '*' to: ['find', 'read'] // allow everyone to read and find +// comments +allow '*' to: ['find', 'read'] // read aka findById +allow 'user' to: ['create'] +allow ['owner', 'admin'] to: '*' -URL/Route level permissions - * url pattern - * application id - * ip addresses - * http headers +// users only section +allow: '*' to: ['find', 'read', 'create'] +allow: 'owner' to: ['*.destroy', '*.save'] -Map to oAuth 2.0 scopes +// scopes +// URL level permissions */ - -var ACLSchema = { - model: String, // The model name - properties: [String], // A list of property names - methods: [String], // A list of methods - roles: [String], // A list of roles - permission: {type: String, enum: ['Allow', 'Deny']}, // Allow/Deny - status: String, // Enabled/disabled - created: Date, - modified: Date -} - -// readAccess, writeAccess --> public, userId, role - -module.exports = function(dataSource) { - dataSource = dataSource || new require('loopback-data').ModelBuilder(); - var ACL = dataSource.define('ACL', ACLSchema); - return ACL; -} \ No newline at end of file diff --git a/lib/models/email.js b/lib/models/email.js new file mode 100644 index 000000000..e9358b2b2 --- /dev/null +++ b/lib/models/email.js @@ -0,0 +1,109 @@ +/** + * Module Dependencies. + */ + +var Model = require('../loopback').Model + , loopback = require('../loopback') + , mailer = require("nodemailer"); + +/** + * Default Email properties. + */ + +var properties = { + to: {type: String, required: true}, + from: {type: String, required: true}, + subject: {type: String, required: true}, + text: {type: String}, + html: {type: String} +}; + +/** + * Extends from the built in `loopback.Model` type. + */ + +var Email = module.exports = Model.extend('email', properties); + +/*! + * Setup the Email class after extension. + */ + +Email.setup = function (settings) { + settings = settings || this.settings; + var transports = settings.transports || []; + + transports.forEach(this.setupTransport.bind(this)); +} + +/** + * Add a transport to the available transports. See https://github.com/andris9/Nodemailer#setting-up-a-transport-method. + * + * Example: + * + * Email.setupTransport({ + * type: 'SMTP', + * host: "smtp.gmail.com", // hostname + * secureConnection: true, // use SSL + * port: 465, // port for secure SMTP + * auth: { + * user: "gmail.user@gmail.com", + * pass: "userpass" + * } + * }); + * + */ + +Email.setupTransport = function (setting) { + var Email = this; + Email.transports = Email.transports || []; + Email.transportsIndex = Email.transportsIndex || {}; + var transport = mailer.createTransport(setting.type, setting); + Email.transportsIndex[setting.type] = transport; + Email.transports.push(transport); +} + +/** + * Send an email with the given `options`. + * + * Example Options: + * + * { + * from: "Fred Foo ✔ ", // sender address + * to: "bar@blurdybloop.com, baz@blurdybloop.com", // list of receivers + * subject: "Hello ✔", // Subject line + * text: "Hello world ✔", // plaintext body + * html: "Hello world ✔" // html body + * } + * + * See https://github.com/andris9/Nodemailer for other supported options. + * + * @param {Object} options + * @param {Function} callback Called after the e-mail is sent or the sending failed + */ + +Email.send = function (options, fn) { + var transport = this.transportsIndex[options.transport || 'SMTP'] || this.transports[0]; + assert(transport, 'You must supply an Email.settings.transports array containing at least one transport'); + + transport.sendMail(options, fn); +} + +/** + * Access the node mailer object. + * + * Email.mailer + * // or + * var email = new Email({to: 'foo@bar.com', from: 'bar@bat.com'}); + * email.mailer + */ + +Email.mailer = +Email.prototype.mailer = mailer; + +/** + * Send an email instance using `Email.send()`. + */ + +Email.prototype.send = function (fn) { + this.constructor.send(this, fn); +} \ No newline at end of file diff --git a/lib/models/model.js b/lib/models/model.js new file mode 100644 index 000000000..8a5bf5e0c --- /dev/null +++ b/lib/models/model.js @@ -0,0 +1,114 @@ +/** + * Module Dependencies. + */ + +var ModelBuilder = require('loopback-data').ModelBuilder; +var modeler = new ModelBuilder(); + +/** + * Define the built in loopback.Model. + */ + +var Model = module.exports = modeler.define('model'); + +Model.shared = true; + +/*! + * Called when a model is extended. + */ + +Model.setup = function () { + var ModelCtor = this; + + // each model has its + // own access control + // list + ModelCtor.acl = []; + + ModelCtor.sharedCtor = function (data, id, fn) { + if(typeof data === 'function') { + fn = data; + data = null; + id = null; + } else if (typeof id === 'function') { + fn = id; + + if(typeof data !== 'object') { + id = data; + data = null; + } else { + id = null; + } + } + + if(id && data) { + var model = new ModelCtor(data); + model.id = id; + fn(null, model); + } else if(data) { + fn(null, new ModelCtor(data)); + } else if(id) { + ModelCtor.find(id, function (err, model) { + if(err) { + fn(err); + } else if(model) { + fn(null, model); + } else { + err = new Error('could not find a model with id ' + id); + err.statusCode = 404; + + fn(err); + } + }); + } else { + fn(new Error('must specify an id or data')); + } + } + + // before remote hook + ModelCtor.beforeRemote = function (name, fn) { + var self = this; + if(this.app) { + var remotes = this.app.remotes(); + remotes.before(self.pluralModelName + '.' + name, function (ctx, next) { + fn(ctx, ctx.result, next); + }); + } else { + var args = arguments; + this.once('attached', function () { + self.beforeRemote.apply(self, args); + }); + } + } + + // after remote hook + ModelCtor.afterRemote = function (name, fn) { + var self = this; + if(this.app) { + var remotes = this.app.remotes(); + remotes.after(self.pluralModelName + '.' + name, function (ctx, next) { + fn(ctx, ctx.result, next); + }); + } else { + var args = arguments; + this.once('attached', function () { + self.afterRemote.apply(self, args); + }); + } + } + + ModelCtor.sharedCtor.accepts = [ + {arg: 'data', type: 'object', http: {source: 'body'}}, + {arg: 'id', type: 'any', http: {source: 'url'}} + ]; + + ModelCtor.sharedCtor.http = [ + {path: '/'}, + {path: '/:id'} + ]; + + return ModelCtor; +} + +// setup the initial model +Model.setup(); \ No newline at end of file diff --git a/lib/models/session.js b/lib/models/session.js new file mode 100644 index 000000000..7bf76250e --- /dev/null +++ b/lib/models/session.js @@ -0,0 +1,56 @@ +/** + * Module Dependencies. + */ + +var Model = require('../loopback').Model + , loopback = require('../loopback') + , crypto = require('crypto'); + +/** + * Default Session properties. + */ + +var properties = { + id: {type: String, required: true}, + uid: {type: String}, + ttl: {type: Number, ttl: true} +}; + +/** + * Extends from the built in `loopback.Model` type. + */ + +var Session = module.exports = Model.extend('session', properties); + +/** + * Create a cryptographically random session id. + * + * @param {Function} callback + */ + +Session.createSessionId = function (fn) { + crypto.randomBytes(this.settings.sessionIdLength || 64, function(err, buf) { + if(err) { + fn(err); + } else { + fn(null, buf.toString('base64')); + } + }); +} + +/*! + * Hook to create session id. + */ + +Session.beforeCreate = function (next, data) { + data = data || {}; + + Session.createSessionId(function (err, id) { + if(err) { + next(err); + } else { + data.id = id; + next(); + } + }); +} \ No newline at end of file diff --git a/lib/models/user.js b/lib/models/user.js index 02215c317..93fdb07bb 100644 --- a/lib/models/user.js +++ b/lib/models/user.js @@ -1,48 +1,28 @@ /** - * User Model - Active User - Explicit vs. Implicit - Signup - Removing the User from the System - Login - Logout - User Management - Email Verification - Password Reset - Forgot Username - Using Social Identities - Facebook - Google+ - LinkedIn - Twitter - User Discovery - Username Existence Check - * @type {{question: *, answer: *}} - */ -var ChallengeSchema = { - // id: String, - question: String, - answer: String -}; - -var Credential = { - // id: String, - provider: String, - protocol: String, - attributes: Object -} - -// User model -var UserSchema = { - id: {type: String, required: true}, - realm: {type: String}, + * Module Dependencies. + */ + +var Model = require('../loopback').Model + , loopback = require('../loopback') + , path = require('path') + , SALT_WORK_FACTOR = 10 + , crypto = require('crypto') + , bcrypt = require('bcrypt') + , passport = require('passport') + , LocalStrategy = require('passport-local').Strategy; + +/** + * Default User properties. + */ + +var properties = { + realm: {type: String, }, username: {type: String, required: true}, - // password: {type: String, transient: true}, // Transient property - hash: {type: String}, // Hash code calculated from sha256(realm, username, password, salt, macKey) - salt: {type: String}, - macKey: {type: String}, // HMAC to calculate the hash code + password: {type: String, hideRemotely: true}, // Transient property email: String, emailVerified: Boolean, + verificationToken: String, + credentials: [ 'UserCredential' // User credentials, private or public, such as private/public keys, Kerberos tickets, oAuth tokens, facebook, google, github ids ], @@ -57,5 +37,296 @@ var UserSchema = { */ status: String, created: Date, - modified: Date -} \ No newline at end of file + lastUpdated: Date +} + + +/** + * Extends from the built in `loopback.Model` type. + */ + +var User = module.exports = Model.extend('user', properties); + +/** + * Login a user by with the given `credentials`. + * + * User.login({username: 'foo', password: 'bar'}, function (err, session) { + * console.log(session.id); + * }); + * + * @param {Object} credentials + */ + +User.login = function (credentials, fn) { + var UserCtor = this; + var query = {}; + + if(credentials.email) { + query.email = credentials.email; + } else if(credentials.username) { + query.username = credentials.username; + } else { + return fn(new Error('must provide username or email')); + } + + this.findOne(query, function(err, user) { + var defaultError = new Error('login failed'); + + if(err) { + fn(defaultError); + } else if(user) { + user.hasPassword(credentials.password, function(err, isMatch) { + if(err) { + fn(defaultError); + } else if(isMatch) { + createSession(user, fn); + } else { + fn(defaultError); + } + }); + } else { + fn(defaultError); + } + }); + + function createSession(user, fn) { + var Session = UserCtor.session; + + Session.create({uid: user.id}, function (err, session) { + if(err) { + fn(err); + } else { + fn(null, session) + } + }); + } +} + +/** + * Logout a user with the given session id. + * + * User.logout('asd0a9f8dsj9s0s3223mk', function (err) { + * console.log(err || 'Logged out'); + * }); + * + * @param {String} sessionID + */ + +User.logout = function (sid, fn) { + var UserCtor = this; + + var Session = UserCtor.settings.session || loopback.Session; + + Session.findById(sid, function (err, session) { + if(err) { + fn(err); + } else if(session) { + session.destroy(fn); + } else { + fn(new Error('could not find session')); + } + }); +} + +/** + * Compare the given `password` with the users hashed password. + * + * @param {String} password The plain text password + * @returns {Boolean} + */ + +User.prototype.hasPassword = function (plain, fn) { + if(this.password && plain) { + bcrypt.compare(plain, this.password, function(err, isMatch) { + if(err) return fn(err); + fn(null, isMatch); + }); + } else { + fn(null, false); + } +} + +/** + * Verify a user's identity. + * + * var options = { + * type: 'email', + * to: user.email, + * template: 'verify.ejs', + * redirect: '/' + * }; + * + * user.verify(options, next); + * + * @param {Object} options + */ + +User.prototype.verify = function (options, fn) { + var user = this; + assert(typeof options === 'object', 'options required when calling user.verify()'); + assert(options.type, 'You must supply a verification type (options.type)'); + assert(options.type === 'email', 'Unsupported verification type'); + assert(options.to || this.email, 'Must include options.to when calling user.verify() or the user must have an email property'); + assert(options.from, 'Must include options.from when calling user.verify() or the user must have an email property'); + + options.redirect = options.redirect || '/'; + options.template = path.resolve(options.template || path.join(__dirname, '..', '..', 'templates', 'verify.ejs')); + options.user = this; + options.protocol = options.protocol || 'http'; + options.host = options.host || 'localhost'; + options.verifyHref = options.verifyHref || + options.protocol + + '://' + + options.host + + (User.sharedCtor.http.path || '/' + User.pluralModelName) + + User.confirm.http.path; + + + + // Email model + var Email = options.mailer || this.constructor.email || loopback.Email; + + crypto.randomBytes(64, function(err, buf) { + if(err) { + fn(err); + } else { + user.verificationToken = buf.toString('base64'); + user.save(function (err) { + if(err) { + fn(err); + } else { + sendEmail(user); + } + }); + } + }); + + // TODO - support more verification types + function sendEmail(user) { + options.verifyHref += '?token=' + user.verificationToken; + + options.text = options.text || 'Please verify your email by opening this link in a web browser:\n\t{href}'; + + options.text = options.text.replace('{href}', options.verifyHref); + + var template = loopback.template(options.template); + Email.send({ + to: options.to || user.email, + subject: options.subject || 'Thanks for Registering', + text: options.text, + html: template(options) + }, function (err, email) { + if(err) { + fn(err); + } else { + fn(null, {email: email, token: user.verificationToken, uid: user.id}); + } + }); + } +} + +User.confirm = function (uid, token, redirect, fn) { + this.findById(uid, function (err, user) { + if(err) { + fn(err); + } else { + if(user.verificationToken === token) { + user.verificationToken = undefined; + user.emailVerified = true; + user.save(function (err) { + if(err) { + fn(err) + } else { + fn(); + } + }); + } else { + fn(new Error('invalid token')); + } + } + }); +} +/** + * Setup an extended user model. + */ + +User.setup = function () { + var UserModel = this; + + UserModel.setter.password = function (plain) { + var salt = bcrypt.genSaltSync(this.constructor.settings.saltWorkFactor || SALT_WORK_FACTOR); + this._password = bcrypt.hashSync(plain, salt); + } + + loopback.remoteMethod( + UserModel.login, + { + accepts: [ + {arg: 'credentials', type: 'object', required: true, http: {source: 'body'}} + ], + returns: {arg: 'session', type: 'object'}, + http: {verb: 'post'} + } + ); + + loopback.remoteMethod( + UserModel.logout, + { + accepts: [ + {arg: 'sid', type: 'string', required: true} + ], + http: {verb: 'all'} + } + ); + + loopback.remoteMethod( + UserModel.confirm, + { + accepts: [ + {arg: 'uid', type: 'string', required: true}, + {arg: 'token', type: 'string', required: true}, + {arg: 'redirect', type: 'string', required: true} + ], + http: {verb: 'get', path: '/confirm'} + } + ); + + UserModel.on('attached', function () { + UserModel.afterRemote('confirm', function (ctx, inst, next) { + if(ctx.req) { + ctx.res.redirect(ctx.req.param('redirect')); + } else { + fn(new Error('transport unsupported')); + } + }); + }); + + // default models + UserModel.email = require('./email'); + UserModel.session = require('./session'); + + UserModel.validatesUniquenessOf('email', {message: 'Email already exists'}); + var re = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/; + + UserModel.validatesFormatOf('email', {with: re, message: 'Must provide a valid email'}); + + return UserModel; +} + +/** + * Logout a user. + */ + +User.prototype.logout = function (fn) { + fn = fn || function() {}; // noop + + this.constructor.session.findOne({email: this.email}, function (err, session) { + session.destroy(fn); + }); +} + +/*! + * Setup the base user. + */ + +User.setup(); diff --git a/package.json b/package.json index 19add2484..49d5f0de4 100644 --- a/package.json +++ b/package.json @@ -10,7 +10,12 @@ "express": "~3.1.1", "loopback-data": "git+ssh://git@github.com:strongloop/loopback-data.git", "sl-remoting": "git+ssh://git@github.com:strongloop/sl-remoting.git", - "inflection": "~1.2.5" + "inflection": "~1.2.5", + "bcrypt": "~0.7.6", + "passport": "~0.1.17", + "passport-local": "~0.1.6", + "nodemailer": "~0.4.4", + "ejs": "~0.8.4" }, "devDependencies": { "mocha": "latest", diff --git a/templates/verify.ejs b/templates/verify.ejs new file mode 100644 index 000000000..708c11390 --- /dev/null +++ b/templates/verify.ejs @@ -0,0 +1,9 @@ +

Thank You

+ +

+ Thanks for registering. Please follow the link below to complete your registration. +

+ +

+ <%= verifyHref %> +

\ No newline at end of file diff --git a/test/README.md b/test/README.md index 241ae3193..15ca05305 100644 --- a/test/README.md +++ b/test/README.md @@ -2,12 +2,24 @@ - [app](#app) - [app.model(Model)](#app-appmodelmodel) - [app.models()](#app-appmodels) +<<<<<<< HEAD +======= - [loopback](#loopback) - [loopback.createDataSource(options)](#loopback-loopbackcreatedatasourceoptions) - [loopback.remoteMethod(Model, fn, [options]);](#loopback-loopbackremotemethodmodel-fn-options) +>>>>>>> master - [DataSource](#datasource) - [dataSource.createModel(name, properties, settings)](#datasource-datasourcecreatemodelname-properties-settings) - [dataSource.operations()](#datasource-datasourceoperations) + - [GeoPoint](#geopoint) + - [geoPoint.distanceTo(geoPoint, options)](#geopoint-geopointdistancetogeopoint-options) + - [GeoPoint.distanceBetween(a, b, options)](#geopoint-geopointdistancebetweena-b-options) + - [GeoPoint()](#geopoint-geopoint) + - [loopback](#loopback) + - [loopback.createDataSource(options)](#loopback-loopbackcreatedatasourceoptions) + - [loopback.remoteMethod(Model, fn, [options]);](#loopback-loopbackremotemethodmodel-fn-options) + - [loopback.memory([name])](#loopback-loopbackmemoryname) + - [Memory Connector](#memory-connector) - [Model](#model) - [Model.validatesPresenceOf(properties...)](#model-modelvalidatespresenceofproperties) - [Model.validatesLengthOf(property, options)](#model-modelvalidateslengthofproperty-options) @@ -23,7 +35,7 @@ - [Model.upsert(data, callback)](#model-modelupsertdata-callback) - [model.destroy([callback])](#model-modeldestroycallback) - [Model.destroyAll(callback)](#model-modeldestroyallcallback) - - [Model.find(id, callback)](#model-modelfindid-callback) + - [Model.findById(id, callback)](#model-modelfindbyidid-callback) - [Model.count([query], callback)](#model-modelcountquery-callback) - [Remote Methods](#model-remote-methods) - [Example Remote Method](#model-remote-methods-example-remote-method) @@ -33,13 +45,23 @@ - [ctx.req](#model-remote-methods-remote-method-invoking-context-ctxreq) - [ctx.res](#model-remote-methods-remote-method-invoking-context-ctxres) - [Model.hasMany(Model)](#model-modelhasmanymodel) + - [Model.properties](#model-modelproperties) + - [Model.extend()](#model-modelextend) + - [User](#user) + - [User.create](#user-usercreate) + - [User.login](#user-userlogin) + - [User.logout](#user-userlogout) + - [user.hasPassword(plain, fn)](#user-userhaspasswordplain-fn) + - [Verification](#user-verification) + - [user.verify(options, fn)](#user-verification-userverifyoptions-fn) + - [User.confirm(options, fn)](#user-verification-userconfirmoptions-fn) # app ## app.model(Model) -Expose a `Model` to remote clients.. +Expose a `Model` to remote clients. ```js var memory = loopback.createDataSource({connector: loopback.Memory}); @@ -50,7 +72,7 @@ assert.equal(app.models().length, 1); ## app.models() -Get the app's exposed models.. +Get the app's exposed models. ```js var Color = loopback.createModel('color', {name: String}); @@ -60,6 +82,8 @@ assert.equal(models.length, 1); assert.equal(models[0].modelName, 'color'); ``` +<<<<<<< HEAD +======= # loopback @@ -99,22 +123,23 @@ assert.equal(Product.stats.http.verb, 'get'); assert.equal(Product.stats.shared, true); ``` +>>>>>>> master # DataSource ## dataSource.createModel(name, properties, settings) -Define a model and attach it to a `DataSource`.. +Define a model and attach it to a `DataSource`. ```js var Color = memory.createModel('color', {name: String}); -assert.isFunc(Color, 'all'); +assert.isFunc(Color, 'find'); +assert.isFunc(Color, 'findById'); +assert.isFunc(Color, 'findOne'); assert.isFunc(Color, 'create'); assert.isFunc(Color, 'updateOrCreate'); assert.isFunc(Color, 'upsert'); assert.isFunc(Color, 'findOrCreate'); assert.isFunc(Color, 'exists'); -assert.isFunc(Color, 'find'); -assert.isFunc(Color, 'findOne'); assert.isFunc(Color, 'destroyAll'); assert.isFunc(Color, 'count'); assert.isFunc(Color, 'include'); @@ -132,7 +157,7 @@ assert.isFunc(Color.prototype, 'reload'); ## dataSource.operations() -List the enabled and disabled operations.. +List the enabled and disabled operations. ```js // assert the defaults @@ -146,7 +171,6 @@ existsAndShared('upsert', false); existsAndShared('findOrCreate', false); existsAndShared('exists', true); existsAndShared('find', true); -existsAndShared('all', true); existsAndShared('findOne', true); existsAndShared('destroyAll', false); existsAndShared('count', true); @@ -159,7 +183,6 @@ existsAndShared('save', true); existsAndShared('isNewRecord', false); existsAndShared('_adapter', false); existsAndShared('destroy', true); -existsAndShared('updateAttribute', true); existsAndShared('updateAttributes', true); existsAndShared('reload', true); @@ -169,11 +192,176 @@ function existsAndShared(name, isRemoteEnabled) { } ``` + +# GeoPoint + +## geoPoint.distanceTo(geoPoint, options) +Get the distance to another `GeoPoint`. + +```js +var here = new GeoPoint({lat: 10, lng: 10}); +var there = new GeoPoint({lat: 5, lng: 5}); + +assert.equal(here.distanceTo(there, {type: 'meters'}), 782777.923052584); +``` + + +## GeoPoint.distanceBetween(a, b, options) +Get the distance between two points. + +```js +var here = new GeoPoint({lat: 10, lng: 10}); +var there = new GeoPoint({lat: 5, lng: 5}); + +assert.equal(GeoPoint.distanceBetween(here, there, {type: 'feet'}), 2568169.038886431); +``` + + +## GeoPoint() +Create from string. + +```js +var point = new GeoPoint('1.234,5.678'); +assert.equal(point.lng, 1.234); +assert.equal(point.lat, 5.678); +var point2 = new GeoPoint('1.222, 5.333'); +assert.equal(point2.lng, 1.222); +assert.equal(point2.lat, 5.333); +var point3 = new GeoPoint('1.333, 5.111'); +assert.equal(point3.lng, 1.333); +assert.equal(point3.lat, 5.111); +``` + +Serialize as string. + +```js +var str = '1.234,5.678'; +var point = new GeoPoint(str); +assert.equal(point.toString(), str); +``` + +Create from array. + +```js +var point = new GeoPoint([5.555, 6.777]); +assert.equal(point.lng, 5.555); +assert.equal(point.lat, 6.777); +``` + +Create as Model property. + +```js +var Model = loopback.createModel('geo-model', { + geo: {type: 'GeoPoint'} +}); + +var m = new Model({ + geo: '1.222,3.444' +}); + +assert(m.geo instanceof GeoPoint); +assert.equal(m.geo.lng, 1.222); +assert.equal(m.geo.lat, 3.444); +``` + + +# loopback + +## loopback.createDataSource(options) +Create a data source with a connector. + +```js +var dataSource = loopback.createDataSource({ + connector: loopback.Memory +}); +assert(dataSource.connector()); +``` + + +## loopback.remoteMethod(Model, fn, [options]); +Setup a remote method. + +```js +var Product = loopback.createModel('product', {price: Number}); + +Product.stats = function(fn) { + // ... +} + +loopback.remoteMethod( + Product.stats, + { + returns: {arg: 'stats', type: 'array'}, + http: {path: '/info', verb: 'get'} + } +); + +assert.equal(Product.stats.returns.arg, 'stats'); +assert.equal(Product.stats.returns.type, 'array'); +assert.equal(Product.stats.http.path, '/info'); +assert.equal(Product.stats.http.verb, 'get'); +assert.equal(Product.stats.shared, true); +``` + + +## loopback.memory([name]) +Get an in-memory data source. Use one if it already exists. + +```js +var memory = loopback.memory(); +assertValidDataSource(memory); +var m1 = loopback.memory(); +var m2 = loopback.memory('m2'); +var alsoM2 = loopback.memory('m2'); + +assert(m1 === memory); +assert(m1 !== m2); +assert(alsoM2 === m2); +``` + + +# Memory Connector +Create a model using the memory connector. + +```js +// use the built in memory function +// to create a memory data source +var memory = loopback.memory(); + +// or create it using the standard +// data source creation api +var memory = loopback.createDataSource({ + connector: loopback.Memory +}); + +// create a model using the +// memory data source +var properties = { + name: String, + price: Number +}; + +var Product = memory.createModel('product', properties); + +Product.create([ + {name: 'apple', price: 0.79}, + {name: 'pear', price: 1.29}, + {name: 'orange', price: 0.59}, +], count); + +function count() { + Product.count(function (err, count) { + assert.equal(count, 3); + done(); + }); +} +``` + # Model ## Model.validatesPresenceOf(properties...) -Require a model to include a property to be considered valid.. +Require a model to include a property to be considered valid. ```js User.validatesPresenceOf('first', 'last', 'age'); @@ -185,7 +373,7 @@ assert(joe.errors.age, 'should have a missing age error'); ## Model.validatesLengthOf(property, options) -Require a property length to be within a specified range.. +Require a property length to be within a specified range. ```js User.validatesLengthOf('password', {min: 5, message: {min: 'Password is too short'}}); @@ -196,7 +384,7 @@ assert(joe.errors.password, 'should have password error'); ## Model.validatesInclusionOf(property, options) -Require a value for `property` to be in the specified array.. +Require a value for `property` to be in the specified array. ```js User.validatesInclusionOf('gender', {in: ['male', 'female']}); @@ -207,7 +395,7 @@ assert(foo.errors.gender, 'should have gender error'); ## Model.validatesExclusionOf(property, options) -Require a value for `property` to not exist in the specified array.. +Require a value for `property` to not exist in the specified array. ```js User.validatesExclusionOf('domain', {in: ['www', 'billing', 'admin']}); @@ -224,7 +412,7 @@ assert(bat.errors.domain, 'model should have a domain error'); ## Model.validatesNumericalityOf(property, options) -Require a value for `property` to be a specific type of `Number`.. +Require a value for `property` to be a specific type of `Number`. ```js User.validatesNumericalityOf('age', {int: true}); @@ -237,7 +425,7 @@ assert(joe.errors.age, 'model should have an age error'); ## Model.validatesUniquenessOf(property, options) -Ensure the value for `property` is unique.. +Ensure the value for `property` is unique. ```js User.validatesUniquenessOf('email', {message: 'email is not unique'}); @@ -257,7 +445,7 @@ joe.save(function () { ## myModel.isValid() -Validate the model instance.. +Validate the model instance. ```js User.validatesNumericalityOf('age', {int: true}); @@ -267,7 +455,7 @@ assert(valid === false); assert(user.errors.age, 'model should have age error'); ``` -Asynchronously validate the model.. +Asynchronously validate the model. ```js User.validatesNumericalityOf('age', {int: true}); @@ -286,16 +474,16 @@ Attach a model to a [DataSource](#data-source). ```js var MyModel = loopback.createModel('my-model', {name: String}); -assert(MyModel.all === undefined, 'should not have data access methods'); +assert(MyModel.find === undefined, 'should not have data access methods'); MyModel.attachTo(memory); -assert(typeof MyModel.all === 'function', 'should have data access methods after attaching to a data source'); +assert(typeof MyModel.find === 'function', 'should have data access methods after attaching to a data source'); ``` ## Model.create([data], [callback]) -Create an instance of Model with given data and save to the attached data source.. +Create an instance of Model with given data and save to the attached data source. ```js User.create({first: 'Joe', last: 'Bob'}, function(err, user) { @@ -306,7 +494,7 @@ User.create({first: 'Joe', last: 'Bob'}, function(err, user) { ## model.save([options], [callback]) -Save an instance of a Model to the attached data source.. +Save an instance of a Model to the attached data source. ```js var joe = new User({first: 'Joe', last: 'Bob'}); @@ -320,7 +508,7 @@ joe.save(function(err, user) { ## model.updateAttributes(data, [callback]) -Save specified attributes to the attached data source.. +Save specified attributes to the attached data source. ```js User.create({first: 'joe', age: 100}, function (err, user) { @@ -359,14 +547,14 @@ User.upsert({first: 'joe', id: 7}, function (err, user) { ## model.destroy([callback]) -Remove a model from the attached data source.. +Remove a model from the attached data source. ```js User.create({first: 'joe', last: 'bob'}, function (err, user) { - User.find(user.id, function (err, foundUser) { + User.findById(user.id, function (err, foundUser) { assert.equal(user.id, foundUser.id); foundUser.destroy(function () { - User.find(user.id, function (err, notFound) { + User.findById(user.id, function (err, notFound) { assert(!err); assert.equal(notFound, null); done(); @@ -400,13 +588,13 @@ Delete all Model instances from data source. }); ``` - -## Model.find(id, callback) -Find instance by id.. + +## Model.findById(id, callback) +Find an instance by id. ```js User.create({first: 'michael', last: 'jordan', id: 23}, function () { - User.find(23, function (err, user) { + User.findById(23, function (err, user) { assert.equal(user.id, 23); assert.equal(user.first, 'michael'); assert.equal(user.last, 'jordan'); @@ -454,12 +642,12 @@ request(app) ### Model.beforeRemote(name, fn) -Run a function before a remote method is called by a client.. +Run a function before a remote method is called by a client. ```js var hookCalled = false; -User.beforeRemote('*.save', function(ctx, user, next) { +User.beforeRemote('create', function(ctx, user, next) { hookCalled = true; next(); }); @@ -479,18 +667,18 @@ request(app) ### Model.afterRemote(name, fn) -Run a function after a remote method is called by a client.. +Run a function after a remote method is called by a client. ```js var beforeCalled = false; var afterCalled = false; -User.beforeRemote('*.save', function(ctx, user, next) { +User.beforeRemote('create', function(ctx, user, next) { assert(!afterCalled); beforeCalled = true; next(); }); -User.afterRemote('*.save', function(ctx, user, next) { +User.afterRemote('create', function(ctx, user, next) { assert(beforeCalled); afterCalled = true; next(); @@ -519,7 +707,7 @@ The express ServerRequest object. ```js var hookCalled = false; -User.beforeRemote('*.save', function(ctx, user, next) { +User.beforeRemote('create', function(ctx, user, next) { hookCalled = true; assert(ctx.req); assert(ctx.req.url); @@ -550,7 +738,7 @@ The express ServerResponse object. ```js var hookCalled = false; -User.beforeRemote('*.save', function(ctx, user, next) { +User.beforeRemote('create', function(ctx, user, next) { hookCalled = true; assert(ctx.req); assert(ctx.req.url); @@ -576,7 +764,7 @@ request(app) ## Model.hasMany(Model) -Define a one to many relationship.. +Define a one to many relationship. ```js var Book = memory.createModel('book', {title: String, author: String}); @@ -603,3 +791,349 @@ Book.create({title: 'Into the Wild', author: 'Jon Krakauer'}, function(err, book }); ``` + +## Model.properties +Normalized properties passed in originally by loopback.createModel(). + +```js +var props = { + s: String, + n: {type: 'Number'}, + o: {type: 'String', min: 10, max: 100}, + d: Date, + g: loopback.GeoPoint +}; + +var MyModel = loopback.createModel('foo', props); + +Object.keys(MyModel.properties).forEach(function (key) { + var p = MyModel.properties[key]; + var o = MyModel.properties[key]; + assert(p); + assert(o); + assert(typeof p.type === 'function'); + + if(typeof o === 'function') { + // the normalized property + // should match the given property + assert( + p.type.name === o.name + || + p.type.name === o + ) + } +}); +``` + + +## Model.extend() +Create a new model by extending an existing model. + +```js +var User = loopback.Model.extend('test-user', { + email: String +}); + +User.foo = function () { + return 'bar'; +} + +User.prototype.bar = function () { + return 'foo'; +} + +var MyUser = User.extend('my-user', { + a: String, + b: String +}); + +assert.equal(MyUser.prototype.bar, User.prototype.bar); +assert.equal(MyUser.foo, User.foo); + +var user = new MyUser({ + email: 'foo@bar.com', + a: 'foo', + b: 'bar' +}); + +assert.equal(user.email, 'foo@bar.com'); +assert.equal(user.a, 'foo'); +assert.equal(user.b, 'bar'); +``` + + +# User + +## User.create +Create a new user. + +```js +User.create({email: 'f@b.com'}, function (err, user) { + assert(!err); + assert(user.id); + assert(user.email); + done(); +}); +``` + +Requires a valid email. + +```js +User.create({}, function (err) { + assert(err); + User.create({email: 'foo@'}, function (err) { + assert(err); + done(); + }); +}); +``` + +Requires a unique email. + +```js +User.create({email: 'a@b.com'}, function () { + User.create({email: 'a@b.com'}, function (err) { + assert(err, 'should error because the email is not unique!'); + done(); + }); +}); +``` + +Requires a password to login with basic auth. + +```js +User.create({email: 'b@c.com'}, function (err) { + User.login({email: 'b@c.com'}, function (err, session) { + assert(!session, 'should not create a session without a valid password'); + assert(err, 'should not login without a password'); + done(); + }); +}); +``` + +Hashes the given password. + +```js +var u = new User({username: 'foo', password: 'bar'}); +assert(u.password !== 'bar'); +``` + + +## User.login +Login a user by providing credentials. + +```js +request(app) + .post('/users/login') + .expect('Content-Type', /json/) + .expect(200) + .send({email: 'foo@bar.com', password: 'bar'}) + .end(function(err, res){ + if(err) return done(err); + var session = res.body; + + assert(session.uid); + assert(session.id); + assert.equal((new Buffer(session.id, 'base64')).length, 64); + + done(); + }); +``` + + +## User.logout +Logout a user by providing the current session id (using node). + +```js +login(logout); + +function login(fn) { + User.login({email: 'foo@bar.com', password: 'bar'}, fn); +} + +function logout(err, session) { + User.logout(session.id, verify(session.id, done)); +} +``` + +Logout a user by providing the current session id (over rest). + +```js +login(logout); + +function login(fn) { + request(app) + .post('/users/login') + .expect('Content-Type', /json/) + .expect(200) + .send({email: 'foo@bar.com', password: 'bar'}) + .end(function(err, res){ + if(err) return done(err); + var session = res.body; + + assert(session.uid); + assert(session.id); + + fn(null, session.id); + }); +} + +function logout(err, sid) { + request(app) + .post('/users/logout') + .expect(200) + .send({sid: sid}) + .end(verify(sid, done)); +} +``` + +Logout a user using the instance method. + +```js +login(logout); + +function login(fn) { + User.login({email: 'foo@bar.com', password: 'bar'}, fn); +} + +function logout(err, session) { + User.findOne({email: 'foo@bar.com'}, function (err, user) { + user.logout(verify(session.id, done)); + }); +} +``` + + +## user.hasPassword(plain, fn) +Determine if the password matches the stored password. + +```js +var u = new User({username: 'foo', password: 'bar'}); +u.hasPassword('bar', function (err, isMatch) { + assert(isMatch, 'password doesnt match'); + done(); +}); +``` + +should match a password when saved. + +```js +var u = new User({username: 'a', password: 'b', email: 'z@z.net'}); + +u.save(function (err, user) { + User.findById(user.id, function (err, uu) { + uu.hasPassword('b', function (err, isMatch) { + assert(isMatch); + done(); + }); + }); +}); +``` + +should match a password after it is changed. + +```js +User.create({email: 'foo@baz.net', username: 'bat', password: 'baz'}, function (err, user) { + User.findById(user.id, function (err, foundUser) { + assert(foundUser); + foundUser.hasPassword('baz', function (err, isMatch) { + assert(isMatch); + foundUser.password = 'baz2'; + foundUser.save(function (err, updatedUser) { + updatedUser.hasPassword('baz2', function (err, isMatch) { + assert(isMatch); + User.findById(user.id, function (err, uu) { + uu.hasPassword('baz2', function (err, isMatch) { + assert(isMatch); + done(); + }); + }); + }); + }); + }); + }); +}); +``` + + +## Verification + +### user.verify(options, fn) +Verify a user's email address. + +```js +User.afterRemote('create', function(ctx, user, next) { + assert(user, 'afterRemote should include result'); + + var options = { + type: 'email', + to: user.email, + from: 'noreply@myapp.org', + redirect: '/', + protocol: ctx.req.protocol, + host: ctx.req.get('host') + }; + + user.verify(options, function (err, result) { + assert(result.email); + assert(result.email.message); + assert(result.token); + + + var lines = result.email.message.split('\n'); + assert(lines[4].indexOf('To: bar@bat.com') === 0); + done(); + }); +}); + +request(app) + .post('/users') + .expect('Content-Type', /json/) + .expect(200) + .send({email: 'bar@bat.com', password: 'bar'}) + .end(function(err, res){ + if(err) return done(err); + }); +``` + + +### User.confirm(options, fn) +Confirm a user verification. + +```js +User.afterRemote('create', function(ctx, user, next) { + assert(user, 'afterRemote should include result'); + + var options = { + type: 'email', + to: user.email, + from: 'noreply@myapp.org', + redirect: 'http://foo.com/bar', + protocol: ctx.req.protocol, + host: ctx.req.get('host') + }; + + user.verify(options, function (err, result) { + if(err) return done(err); + + request(app) + .get('/users/confirm?uid=' + result.uid + '&token=' + encodeURIComponent(result.token) + '&redirect=' + encodeURIComponent(options.redirect)) + .expect(302) + .expect('location', options.redirect) + .end(function(err, res){ + if(err) return done(err); + done(); + }); + }); +}); + +request(app) + .post('/users') + .expect('Content-Type', /json/) + .expect(302) + .send({email: 'bar@bat.com', password: 'bar'}) + .end(function(err, res){ + if(err) return done(err); + }); +``` + diff --git a/test/app.test.js b/test/app.test.js index a27748c4d..b499bfcec 100644 --- a/test/app.test.js +++ b/test/app.test.js @@ -1,7 +1,7 @@ describe('app', function() { describe('app.model(Model)', function() { - it("Expose a `Model` to remote clients.", function() { + it("Expose a `Model` to remote clients", function() { var memory = loopback.createDataSource({connector: loopback.Memory}); var Color = memory.createModel('color', {name: String}); app.model(Color); @@ -10,7 +10,7 @@ describe('app', function() { }); describe('app.models()', function() { - it("Get the app's exposed models.", function() { + it("Get the app's exposed models", function() { var Color = loopback.createModel('color', {name: String}); var models = app.models(); diff --git a/test/data-source.test.js b/test/data-source.test.js index ae536d25c..f39866a2a 100644 --- a/test/data-source.test.js +++ b/test/data-source.test.js @@ -5,10 +5,12 @@ describe('DataSource', function() { memory = loopback.createDataSource({ connector: loopback.Memory }); + + assertValidDataSource(memory); }); describe('dataSource.createModel(name, properties, settings)', function() { - it("Define a model and attach it to a `DataSource`.", function() { + it("Define a model and attach it to a `DataSource`", function() { var Color = memory.createModel('color', {name: String}); assert.isFunc(Color, 'find'); assert.isFunc(Color, 'findById'); @@ -35,7 +37,7 @@ describe('DataSource', function() { }); describe('dataSource.operations()', function() { - it("List the enabled and disabled operations.", function() { + it("List the enabled and disabled operations", function() { // assert the defaults // - true: the method should be remote enabled // - false: the method should not be remote enabled @@ -59,7 +61,6 @@ describe('DataSource', function() { existsAndShared('isNewRecord', false); existsAndShared('_adapter', false); existsAndShared('destroy', true); - existsAndShared('updateAttribute', true); existsAndShared('updateAttributes', true); existsAndShared('reload', true); diff --git a/test/geo-point.test.js b/test/geo-point.test.js index 223df816d..2e436be3c 100644 --- a/test/geo-point.test.js +++ b/test/geo-point.test.js @@ -1,6 +1,6 @@ describe('GeoPoint', function() { describe('geoPoint.distanceTo(geoPoint, options)', function() { - it("Get the distance to another `GeoPoint`.", function() { + it("Get the distance to another `GeoPoint`", function() { var here = new GeoPoint({lat: 10, lng: 10}); var there = new GeoPoint({lat: 5, lng: 5}); @@ -9,7 +9,7 @@ describe('GeoPoint', function() { }); describe('GeoPoint.distanceBetween(a, b, options)', function() { - it("Get the distance between two points.", function() { + it("Get the distance between two points", function() { var here = new GeoPoint({lat: 10, lng: 10}); var there = new GeoPoint({lat: 5, lng: 5}); @@ -18,7 +18,7 @@ describe('GeoPoint', function() { }); describe('GeoPoint()', function(){ - it('Create from string.', function() { + it('Create from string', function() { var point = new GeoPoint('1.234,5.678'); assert.equal(point.lng, 1.234); assert.equal(point.lat, 5.678); @@ -29,12 +29,12 @@ describe('GeoPoint', function() { assert.equal(point3.lng, 1.333); assert.equal(point3.lat, 5.111); }); - it('Serialize as string.', function() { + it('Serialize as string', function() { var str = '1.234,5.678'; var point = new GeoPoint(str); assert.equal(point.toString(), str); }); - it('Create from array.', function() { + it('Create from array', function() { var point = new GeoPoint([5.555, 6.777]); assert.equal(point.lng, 5.555); assert.equal(point.lat, 6.777); diff --git a/test/memory.test.js b/test/memory.test.js new file mode 100644 index 000000000..88a3d176a --- /dev/null +++ b/test/memory.test.js @@ -0,0 +1,35 @@ +describe('Memory Connector', function(){ + it('Create a model using the memory connector', function(done) { + // use the built in memory function + // to create a memory data source + var memory = loopback.memory(); + + // or create it using the standard + // data source creation api + var memory = loopback.createDataSource({ + connector: loopback.Memory + }); + + // create a model using the + // memory data source + var properties = { + name: String, + price: Number + }; + + var Product = memory.createModel('product', properties); + + Product.create([ + {name: 'apple', price: 0.79}, + {name: 'pear', price: 1.29}, + {name: 'orange', price: 0.59}, + ], count); + + function count() { + Product.count(function (err, count) { + assert.equal(count, 3); + done(); + }); + } + }); +}); \ No newline at end of file diff --git a/test/model.test.js b/test/model.test.js index c8512b867..5c5891ff1 100644 --- a/test/model.test.js +++ b/test/model.test.js @@ -16,7 +16,7 @@ describe('Model', function() { }); describe('Model.validatesPresenceOf(properties...)', function() { - it("Require a model to include a property to be considered valid.", function() { + it("Require a model to include a property to be considered valid", function() { User.validatesPresenceOf('first', 'last', 'age'); var joe = new User({first: 'joe'}); assert(joe.isValid() === false, 'model should not validate'); @@ -26,7 +26,7 @@ describe('Model', function() { }); describe('Model.validatesLengthOf(property, options)', function() { - it("Require a property length to be within a specified range.", function() { + it("Require a property length to be within a specified range", function() { User.validatesLengthOf('password', {min: 5, message: {min: 'Password is too short'}}); var joe = new User({password: '1234'}); assert(joe.isValid() === false, 'model should not be valid'); @@ -35,7 +35,7 @@ describe('Model', function() { }); describe('Model.validatesInclusionOf(property, options)', function() { - it("Require a value for `property` to be in the specified array.", function() { + it("Require a value for `property` to be in the specified array", function() { User.validatesInclusionOf('gender', {in: ['male', 'female']}); var foo = new User({gender: 'bar'}); assert(foo.isValid() === false, 'model should not be valid'); @@ -44,7 +44,7 @@ describe('Model', function() { }); describe('Model.validatesExclusionOf(property, options)', function() { - it("Require a value for `property` to not exist in the specified array.", function() { + it("Require a value for `property` to not exist in the specified array", function() { User.validatesExclusionOf('domain', {in: ['www', 'billing', 'admin']}); var foo = new User({domain: 'www'}); var bar = new User({domain: 'billing'}); @@ -59,7 +59,7 @@ describe('Model', function() { }); describe('Model.validatesNumericalityOf(property, options)', function() { - it("Require a value for `property` to be a specific type of `Number`.", function() { + it("Require a value for `property` to be a specific type of `Number`", function() { User.validatesNumericalityOf('age', {int: true}); var joe = new User({age: 10.2}); assert(joe.isValid() === false); @@ -70,7 +70,7 @@ describe('Model', function() { }); describe('Model.validatesUniquenessOf(property, options)', function() { - it("Ensure the value for `property` is unique.", function(done) { + it("Ensure the value for `property` is unique", function(done) { User.validatesUniquenessOf('email', {message: 'email is not unique'}); var joe = new User({email: 'joe@joe.com'}); @@ -88,7 +88,7 @@ describe('Model', function() { }); describe('myModel.isValid()', function() { - it("Validate the model instance.", function() { + it("Validate the model instance", function() { User.validatesNumericalityOf('age', {int: true}); var user = new User({first: 'joe', age: 'flarg'}) var valid = user.isValid(); @@ -96,7 +96,7 @@ describe('Model', function() { assert(user.errors.age, 'model should have age error'); }); - it('Asynchronously validate the model.', function(done) { + it('Asynchronously validate the model', function(done) { User.validatesNumericalityOf('age', {int: true}); var user = new User({first: 'joe', age: 'flarg'}) user.isValid(function (valid) { @@ -120,7 +120,7 @@ describe('Model', function() { }); describe('Model.create([data], [callback])', function() { - it("Create an instance of Model with given data and save to the attached data source.", function(done) { + it("Create an instance of Model with given data and save to the attached data source", function(done) { User.create({first: 'Joe', last: 'Bob'}, function(err, user) { assert(user instanceof User); done(); @@ -129,7 +129,7 @@ describe('Model', function() { }); describe('model.save([options], [callback])', function() { - it("Save an instance of a Model to the attached data source.", function(done) { + it("Save an instance of a Model to the attached data source", function(done) { var joe = new User({first: 'Joe', last: 'Bob'}); joe.save(function(err, user) { assert(user.id); @@ -141,7 +141,7 @@ describe('Model', function() { }); describe('model.updateAttributes(data, [callback])', function() { - it("Save specified attributes to the attached data source.", function(done) { + it("Save specified attributes to the attached data source", function(done) { User.create({first: 'joe', age: 100}, function (err, user) { assert(!err); assert.equal(user.first, 'joe'); @@ -176,7 +176,7 @@ describe('Model', function() { }); describe('model.destroy([callback])', function() { - it("Remove a model from the attached data source.", function(done) { + it("Remove a model from the attached data source", function(done) { User.create({first: 'joe', last: 'bob'}, function (err, user) { User.findById(user.id, function (err, foundUser) { assert.equal(user.id, foundUser.id); @@ -215,7 +215,7 @@ describe('Model', function() { }); describe('Model.findById(id, callback)', function() { - it("Find an instance by id.", function(done) { + it("Find an instance by id", function(done) { User.create({first: 'michael', last: 'jordan', id: 23}, function () { User.findById(23, function (err, user) { assert.equal(user.id, 23); @@ -285,10 +285,10 @@ describe('Model', function() { }); describe('Model.beforeRemote(name, fn)', function(){ - it('Run a function before a remote method is called by a client.', function(done) { + it('Run a function before a remote method is called by a client', function(done) { var hookCalled = false; - User.beforeRemote('*.save', function(ctx, user, next) { + User.beforeRemote('create', function(ctx, user, next) { hookCalled = true; next(); }); @@ -308,16 +308,16 @@ describe('Model', function() { }); describe('Model.afterRemote(name, fn)', function(){ - it('Run a function after a remote method is called by a client.', function(done) { + it('Run a function after a remote method is called by a client', function(done) { var beforeCalled = false; var afterCalled = false; - User.beforeRemote('*.save', function(ctx, user, next) { + User.beforeRemote('create', function(ctx, user, next) { assert(!afterCalled); beforeCalled = true; next(); }); - User.afterRemote('*.save', function(ctx, user, next) { + User.afterRemote('create', function(ctx, user, next) { assert(beforeCalled); afterCalled = true; next(); @@ -349,7 +349,7 @@ describe('Model', function() { it("The express ServerRequest object", function(done) { var hookCalled = false; - User.beforeRemote('*.save', function(ctx, user, next) { + User.beforeRemote('create', function(ctx, user, next) { hookCalled = true; assert(ctx.req); assert(ctx.req.url); @@ -378,7 +378,7 @@ describe('Model', function() { it("The express ServerResponse object", function(done) { var hookCalled = false; - User.beforeRemote('*.save', function(ctx, user, next) { + User.beforeRemote('create', function(ctx, user, next) { hookCalled = true; assert(ctx.req); assert(ctx.req.url); @@ -406,7 +406,7 @@ describe('Model', function() { }); describe('Model.hasMany(Model)', function() { - it("Define a one to many relationship.", function(done) { + it("Define a one to many relationship", function(done) { var Book = memory.createModel('book', {title: String, author: String}); var Chapter = memory.createModel('chapter', {title: String}); @@ -433,7 +433,7 @@ describe('Model', function() { }); describe('Model.properties', function(){ - it('Normalized properties passed in originally by loopback.createModel().', function() { + it('Normalized properties passed in originally by loopback.createModel()', function() { var props = { s: String, n: {type: 'Number'}, @@ -463,6 +463,40 @@ describe('Model', function() { }); }); }); + + describe('Model.extend()', function(){ + it('Create a new model by extending an existing model', function() { + var User = loopback.Model.extend('test-user', { + email: String + }); + + User.foo = function () { + return 'bar'; + } + + User.prototype.bar = function () { + return 'foo'; + } + + var MyUser = User.extend('my-user', { + a: String, + b: String + }); + + assert.equal(MyUser.prototype.bar, User.prototype.bar); + assert.equal(MyUser.foo, User.foo); + + var user = new MyUser({ + email: 'foo@bar.com', + a: 'foo', + b: 'bar' + }); + + assert.equal(user.email, 'foo@bar.com'); + assert.equal(user.a, 'foo'); + assert.equal(user.b, 'bar'); + }); + }); // describe('Model.hasAndBelongsToMany()', function() { // it("TODO: implement / document", function(done) { @@ -474,14 +508,14 @@ describe('Model', function() { // }); // describe('Model.remoteMethods()', function() { - // it("Return a list of enabled remote methods.", function() { + // it("Return a list of enabled remote methods", function() { // app.model(User); // User.remoteMethods(); // ['save', ...] // }); // }); // describe('Model.availableMethods()', function() { - // it("Returns the currently available api of a model as well as descriptions of any modified behavior or methods from attached data sources.", function(done) { + // it("Returns the currently available api of a model as well as descriptions of any modified behavior or methods from attached data sources", function(done) { // /* example - // User.attachTo(oracle); // console.log(User.availableMethods()); @@ -511,7 +545,7 @@ describe('Model', function() { // }); // describe('Model.before(name, fn)', function(){ -// it('Run a function before a method is called.', function() { +// it('Run a function before a method is called', function() { // // User.before('save', function(user, next) { // // console.log('about to save', user); // // @@ -535,7 +569,7 @@ describe('Model', function() { // }); // // describe('Model.after(name, fn)', function(){ -// it('Run a function after a method is called.', function() { +// it('Run a function after a method is called', function() { // // throw new Error('not implemented'); // }); diff --git a/test/support.js b/test/support.js index 0919dca30..1983d420c 100644 --- a/test/support.js +++ b/test/support.js @@ -19,8 +19,8 @@ assertValidDataSource = function (dataSource) { assert.isFunc(dataSource, 'createModel'); assert.isFunc(dataSource, 'discoverModelDefinitions'); assert.isFunc(dataSource, 'discoverSchema'); - assert.isFunc(dataSource, 'enable'); - assert.isFunc(dataSource, 'disable'); + assert.isFunc(dataSource, 'enableRemote'); + assert.isFunc(dataSource, 'disableRemote'); assert.isFunc(dataSource, 'defineOperation'); assert.isFunc(dataSource, 'operations'); } diff --git a/test/user.test.js b/test/user.test.js new file mode 100644 index 000000000..cdc3194cc --- /dev/null +++ b/test/user.test.js @@ -0,0 +1,293 @@ +var User = loopback.User.extend('user'); +var Session = loopback.Session; +var passport = require('passport'); + +var userMemory = loopback.createDataSource({ + connector: loopback.Memory +}); + + +describe('User', function(){ + + User.attachTo(userMemory); + User.session.attachTo(userMemory); + User.email.setup({transports: [{type: 'STUB'}]}); + + // allow many User.afterRemote's to be called + User.setMaxListeners(22); + + beforeEach(function (done) { + app.use(loopback.cookieParser()); + app.use(loopback.auth()); + app.use(loopback.rest()); + app.model(User); + + User.create({email: 'foo@bar.com', password: 'bar'}, done); + }); + + afterEach(function (done) { + User.destroyAll(function (err) { + User.session.destroyAll(done); + }); + }); + + describe('User.create', function(){ + it('Create a new user', function(done) { + User.create({email: 'f@b.com'}, function (err, user) { + assert(!err); + assert(user.id); + assert(user.email); + done(); + }); + }); + + it('Requires a valid email', function(done) { + User.create({}, function (err) { + assert(err); + User.create({email: 'foo@'}, function (err) { + assert(err); + done(); + }); + }); + }); + + it('Requires a unique email', function(done) { + User.create({email: 'a@b.com'}, function () { + User.create({email: 'a@b.com'}, function (err) { + assert(err, 'should error because the email is not unique!'); + done(); + }); + }); + }); + + it('Requires a password to login with basic auth', function(done) { + User.create({email: 'b@c.com'}, function (err) { + User.login({email: 'b@c.com'}, function (err, session) { + assert(!session, 'should not create a session without a valid password'); + assert(err, 'should not login without a password'); + done(); + }); + }); + }); + + it('Hashes the given password', function() { + var u = new User({username: 'foo', password: 'bar'}); + assert(u.password !== 'bar'); + }); + }); + + describe('User.login', function() { + it('Login a user by providing credentials', function(done) { + request(app) + .post('/users/login') + .expect('Content-Type', /json/) + .expect(200) + .send({email: 'foo@bar.com', password: 'bar'}) + .end(function(err, res){ + if(err) return done(err); + var session = res.body; + + assert(session.uid); + assert(session.id); + assert.equal((new Buffer(session.id, 'base64')).length, 64); + + done(); + }); + }); + }); + + describe('User.logout', function() { + it('Logout a user by providing the current session id (using node)', function(done) { + login(logout); + + function login(fn) { + User.login({email: 'foo@bar.com', password: 'bar'}, fn); + } + + function logout(err, session) { + User.logout(session.id, verify(session.id, done)); + } + }); + + it('Logout a user by providing the current session id (over rest)', function(done) { + login(logout); + + function login(fn) { + request(app) + .post('/users/login') + .expect('Content-Type', /json/) + .expect(200) + .send({email: 'foo@bar.com', password: 'bar'}) + .end(function(err, res){ + if(err) return done(err); + var session = res.body; + + assert(session.uid); + assert(session.id); + + fn(null, session.id); + }); + } + + function logout(err, sid) { + request(app) + .post('/users/logout') + .expect(200) + .send({sid: sid}) + .end(verify(sid, done)); + } + }); + + it('Logout a user using the instance method', function(done) { + login(logout); + + function login(fn) { + User.login({email: 'foo@bar.com', password: 'bar'}, fn); + } + + function logout(err, session) { + User.findOne({email: 'foo@bar.com'}, function (err, user) { + user.logout(verify(session.id, done)); + }); + } + }); + + function verify(sid, done) { + assert(sid); + + return function (err) { + if(err) return done(err); + + Session.findById(sid, function (err, session) { + assert(!session, 'session should not exist after logging out'); + done(err); + }); + } + } + }); + + describe('user.hasPassword(plain, fn)', function(){ + it('Determine if the password matches the stored password', function(done) { + var u = new User({username: 'foo', password: 'bar'}); + u.hasPassword('bar', function (err, isMatch) { + assert(isMatch, 'password doesnt match'); + done(); + }); + }); + + it('should match a password when saved', function(done) { + var u = new User({username: 'a', password: 'b', email: 'z@z.net'}); + + u.save(function (err, user) { + User.findById(user.id, function (err, uu) { + uu.hasPassword('b', function (err, isMatch) { + assert(isMatch); + done(); + }); + }); + }); + }); + + it('should match a password after it is changed', function(done) { + User.create({email: 'foo@baz.net', username: 'bat', password: 'baz'}, function (err, user) { + User.findById(user.id, function (err, foundUser) { + assert(foundUser); + foundUser.hasPassword('baz', function (err, isMatch) { + assert(isMatch); + foundUser.password = 'baz2'; + foundUser.save(function (err, updatedUser) { + updatedUser.hasPassword('baz2', function (err, isMatch) { + assert(isMatch); + User.findById(user.id, function (err, uu) { + uu.hasPassword('baz2', function (err, isMatch) { + assert(isMatch); + done(); + }); + }); + }); + }); + }); + }); + }); + }); + }); + + describe('Verification', function(){ + + describe('user.verify(options, fn)', function(){ + it('Verify a user\'s email address', function(done) { + User.afterRemote('create', function(ctx, user, next) { + assert(user, 'afterRemote should include result'); + + var options = { + type: 'email', + to: user.email, + from: 'noreply@myapp.org', + redirect: '/', + protocol: ctx.req.protocol, + host: ctx.req.get('host') + }; + + user.verify(options, function (err, result) { + assert(result.email); + assert(result.email.message); + assert(result.token); + + + var lines = result.email.message.split('\n'); + assert(lines[4].indexOf('To: bar@bat.com') === 0); + done(); + }); + }); + + request(app) + .post('/users') + .expect('Content-Type', /json/) + .expect(200) + .send({email: 'bar@bat.com', password: 'bar'}) + .end(function(err, res){ + if(err) return done(err); + }); + }); + }); + + describe('User.confirm(options, fn)', function(){ + it('Confirm a user verification', function(done) { + User.afterRemote('create', function(ctx, user, next) { + assert(user, 'afterRemote should include result'); + + var options = { + type: 'email', + to: user.email, + from: 'noreply@myapp.org', + redirect: 'http://foo.com/bar', + protocol: ctx.req.protocol, + host: ctx.req.get('host') + }; + + user.verify(options, function (err, result) { + if(err) return done(err); + + request(app) + .get('/users/confirm?uid=' + result.uid + '&token=' + encodeURIComponent(result.token) + '&redirect=' + encodeURIComponent(options.redirect)) + .expect(302) + .expect('location', options.redirect) + .end(function(err, res){ + if(err) return done(err); + done(); + }); + }); + }); + + request(app) + .post('/users') + .expect('Content-Type', /json/) + .expect(302) + .send({email: 'bar@bat.com', password: 'bar'}) + .end(function(err, res){ + if(err) return done(err); + }); + }); + }); + }); +}); \ No newline at end of file