From 2a30efe23f52bee1ee5a50aac8af427c9d04404b Mon Sep 17 00:00:00 2001 From: Ritchie Martori Date: Mon, 1 Jul 2013 11:46:41 -0700 Subject: [PATCH 01/39] Remove app.modelBuilder() --- README.md | 12 +++++------- lib/application.js | 8 -------- test/model.test.js | 34 ++++++++++++++++++++++++++++++++++ 3 files changed, 39 insertions(+), 15 deletions(-) diff --git a/README.md b/README.md index 0baadbcaf..0d68a77e2 100644 --- a/README.md +++ b/README.md @@ -802,6 +802,8 @@ The Asteroid library is unopinioned in the way you define your app's data and lo - 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. - Job - _TODO_ schedule arbitrary code to run at a given time. + +Defining a model with `asteroid.createModel()` is really just extending the base `asteroid.Model` type using `asteroid.Model.extend()`. The bundled models extend from the base `asteroid.Model` allowing you to extend them arbitrarily. ### User Model @@ -812,7 +814,7 @@ Register and authenticate users of your app locally or against 3rd party service Extend a vanilla Asteroid model using the built in User model. // define a User model - var User = asteroid.createModel( + var User = asteroid.User.extend( 'user', { email: { @@ -825,9 +827,6 @@ Extend a vanilla Asteroid model using the built in User model. min: 4, max: 26 } - }, - { - extend: 'User', } ); @@ -923,7 +922,7 @@ You must provide a username and password over rest. To ensure these values are e To require email verification before a user is allowed to login, supply a verification property with a `verify` settings object. // define a User model - var User = asteroid.createModel( + var User = asteroid.User.extend( 'user', { email: { @@ -949,7 +948,6 @@ To require email verification before a user is allowed to login, supply a verifi } }, { - extend: 'User', // the model field // that contains the user's email // for verification and password reset @@ -959,7 +957,7 @@ To require email verification before a user is allowed to login, supply a verifi } ); -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. +When a user is created (on the server or remotely) and the verification property exists, 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 diff --git a/lib/application.js b/lib/application.js index 5094ae74f..c292c8d85 100644 --- a/lib/application.js +++ b/lib/application.js @@ -39,14 +39,6 @@ app.disuse = function (route) { } } -/** - * Get ModelBuilder. - */ - -app.modelBuilder = function () { - return this._modelBuilder || (this._modelBuilder = new ModelBuilder()) -} - /** * App models. */ diff --git a/test/model.test.js b/test/model.test.js index 44bad7cf1..bf2a5228b 100644 --- a/test/model.test.js +++ b/test/model.test.js @@ -463,6 +463,40 @@ describe('Model', function() { }); }); }); + + // describe('Model.extend()', function(){ + // it('Create a new model by extending an existing model.', function(done) { + // var User = asteroid.Model.extend('user', { + // email: String + // }); + // + // User.foo = function () { + // return 'bar'; + // } + // + // User.prototype.bar = function () { + // return 'foo'; + // } + // + // var MyUser = User.extend('my-user', { + // foo: String, + // bar: String + // }); + // + // assert(MyUser.prototype.bar === User.prototype.bar); + // assert(MyUser.foo === User.foo); + // + // var user = new MyUser({ + // email: 'foo@bar.com', + // foo: 'foo', + // bar: 'bar' + // }); + // + // assert.equal(user.email, 'foo@bar.com'); + // assert.equal(user.foo, 'foo'); + // assert.equal(user.bar, 'bar'); + // }); + // }); // describe('Model.hasAndBelongsToMany()', function() { // it("TODO: implement / document", function(done) { From 643877b677394c8a771e6a5fa275e676f3d736f4 Mon Sep 17 00:00:00 2001 From: Ritchie Martori Date: Mon, 1 Jul 2013 16:50:03 -0700 Subject: [PATCH 02/39] Add initial User model --- README.md | 21 +++----------- lib/asteroid.js | 6 ++++ lib/models/user.js | 24 ++++++++-------- test/model.test.js | 69 +++++++++++++++++++++++----------------------- 4 files changed, 58 insertions(+), 62 deletions(-) diff --git a/README.md b/README.md index 0d68a77e2..2d772ee41 100644 --- a/README.md +++ b/README.md @@ -814,21 +814,7 @@ Register and authenticate users of your app locally or against 3rd party service Extend a vanilla Asteroid model using the built in User model. // define a User model - var User = asteroid.User.extend( - 'user', - { - email: { - type: 'EmailAddress', - username: true - }, - password: { - hideRemotely: true, // default for Password - type: 'Password', - min: 4, - max: 26 - } - } - ); + var User = asteroid.User.extend('user'); // attach to the memory connector User.attachTo(memory); @@ -862,7 +848,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 }); } @@ -943,7 +929,8 @@ To require email verification before a user is allowed to login, supply a verifi // that contains the email // to verify email: 'email', - template: 'email.ejs' + template: 'email.ejs', + redirect: '/' } } }, diff --git a/lib/asteroid.js b/lib/asteroid.js index 4cb569bf6..7c2c46d4f 100644 --- a/lib/asteroid.js +++ b/lib/asteroid.js @@ -260,3 +260,9 @@ asteroid.remoteMethod = function (fn, options) { fn.http = fn.http || {verb: 'get'}; } +/* + * Built in models + */ + +asteroid.Model = asteroid.createModel('model'); +asteroid.User = require('./models/user'); diff --git a/lib/models/user.js b/lib/models/user.js index 38d20452c..531606d47 100644 --- a/lib/models/user.js +++ b/lib/models/user.js @@ -1,11 +1,13 @@ -// User model -var UserSchema = { - id: {type: String, required: true}, - username: {type: String, required: true}, - password: String, - authData: [], - email: String, - emailVerified: Boolean, - created: Date, - lastUpdated: Date -} \ No newline at end of file +/** + * Module Dependencies. + */ + +var Model = require('../asteroid').Model; + + +/** + * Extends from the built in `asteroid.Model` type. + */ + +var User = module.exports = Model.extend('user'); + diff --git a/test/model.test.js b/test/model.test.js index bf2a5228b..4ecf4d28d 100644 --- a/test/model.test.js +++ b/test/model.test.js @@ -463,40 +463,41 @@ describe('Model', function() { }); }); }); - - // describe('Model.extend()', function(){ - // it('Create a new model by extending an existing model.', function(done) { - // var User = asteroid.Model.extend('user', { - // email: String - // }); - // - // User.foo = function () { - // return 'bar'; - // } - // - // User.prototype.bar = function () { - // return 'foo'; - // } - // - // var MyUser = User.extend('my-user', { - // foo: String, - // bar: String - // }); - // - // assert(MyUser.prototype.bar === User.prototype.bar); - // assert(MyUser.foo === User.foo); - // - // var user = new MyUser({ - // email: 'foo@bar.com', - // foo: 'foo', - // bar: 'bar' - // }); - // - // assert.equal(user.email, 'foo@bar.com'); - // assert.equal(user.foo, 'foo'); - // assert.equal(user.bar, 'bar'); - // }); - // }); + + describe('Model.extend()', function(){ + it('Create a new model by extending an existing model.', function() { + var User = asteroid.Model.extend('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); + + debugger; + 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) { From c14ef9af8c36e2bfa4d03d7d8a67b6cb4c87013e Mon Sep 17 00:00:00 2001 From: Ritchie Martori Date: Mon, 1 Jul 2013 17:01:26 -0700 Subject: [PATCH 03/39] Add default user properties --- lib/models/user.js | 33 ++++++++++++++++++++++++++++++++- 1 file changed, 32 insertions(+), 1 deletion(-) diff --git a/lib/models/user.js b/lib/models/user.js index 531606d47..f13d0be10 100644 --- a/lib/models/user.js +++ b/lib/models/user.js @@ -4,10 +4,41 @@ var Model = require('../asteroid').Model; +/** + * Default User properties. + */ + +var properties = { + id: {type: String, required: true}, + 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 + email: String, + emailVerified: Boolean, + credentials: [ + 'UserCredential' // User credentials, private or public, such as private/public keys, Kerberos tickets, oAuth tokens, facebook, google, github ids + ], + challenges: [ + 'Challenge' // Security questions/answers + ], + // https://en.wikipedia.org/wiki/Multi-factor_authentication + /* + factors: [ + 'AuthenticationFactor' + ], + */ + status: String, + created: Date, + lastUpdated: Date +} + /** * Extends from the built in `asteroid.Model` type. */ -var User = module.exports = Model.extend('user'); +var User = module.exports = Model.extend('user', properties); From 2f13c53161fa892085aa1e46df2bf2c84d9c42f1 Mon Sep 17 00:00:00 2001 From: Ritchie Martori Date: Tue, 2 Jul 2013 16:51:38 -0700 Subject: [PATCH 04/39] Initial users --- lib/application.js | 4 +- lib/asteroid.js | 10 ++--- lib/middleware/auth.js | 34 +++++++++++++++ lib/models/session.js | 22 ++++++++++ lib/models/user.js | 93 +++++++++++++++++++++++++++++++++++++++++- package.json | 5 ++- test/user.test.js | 38 +++++++++++++++++ 7 files changed, 194 insertions(+), 12 deletions(-) create mode 100644 lib/middleware/auth.js create mode 100644 lib/models/session.js create mode 100644 test/user.test.js diff --git a/lib/application.js b/lib/application.js index c292c8d85..703e630ed 100644 --- a/lib/application.js +++ b/lib/application.js @@ -55,9 +55,7 @@ app.model = function (Model) { this._models.push(Model); Model.shared = true; Model.app = this; - if(Model._remoteHooks) { - Model._remoteHooks.emit('attached', app); - } + Model.emit('attached', this); } /** diff --git a/lib/asteroid.js b/lib/asteroid.js index 7c2c46d4f..3ca416d49 100644 --- a/lib/asteroid.js +++ b/lib/asteroid.js @@ -216,8 +216,8 @@ asteroid.createModel = function (name, properties, options) { }); } else { var args = arguments; - this._remoteHooks.once('attached', function () { - self.beforeRemote.apply(ModelCtor, args); + this.once('attached', function () { + self.beforeRemote.apply(self, args); }); } } @@ -232,15 +232,12 @@ asteroid.createModel = function (name, properties, options) { }); } else { var args = arguments; - this._remoteHooks.once('attached', function () { + this.once('attached', function () { self.afterRemote.apply(ModelCtor, args); }); } } - // allow hooks to be added before attaching to an app - ModelCtor._remoteHooks = new EventEmitter(); - return ModelCtor; } @@ -266,3 +263,4 @@ asteroid.remoteMethod = function (fn, options) { asteroid.Model = asteroid.createModel('model'); asteroid.User = require('./models/user'); +asteroid.Session = require('./models/session'); diff --git a/lib/middleware/auth.js b/lib/middleware/auth.js new file mode 100644 index 000000000..79f8acd9b --- /dev/null +++ b/lib/middleware/auth.js @@ -0,0 +1,34 @@ +/** + * Module dependencies. + */ + +var asteroid = require('../asteroid') + , 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 = asteroid(); + + // TODO clean this up + sub._models = req.app._models; + sub._remotes = req.app._remotes; + + sub.use(asteroid.session({secret: 'change me'})) + sub.use(passport.initialize()); + sub.use(passport.session()); + + sub.handle(req, res, next); + } +} + + diff --git a/lib/models/session.js b/lib/models/session.js new file mode 100644 index 000000000..eadfeb5ed --- /dev/null +++ b/lib/models/session.js @@ -0,0 +1,22 @@ +/** + * Module Dependencies. + */ + +var Model = require('../asteroid').Model + , asteroid = require('../asteroid'); + +/** + * Default Session properties. + */ + +var properties = { + id: {type: String, required: true}, + uid: {type: String}, + ttl: {type: Number, ttl: true} +}; + +/** + * Extends from the built in `asteroid.Model` type. + */ + +var Session = module.exports = Model.extend('session', properties); \ No newline at end of file diff --git a/lib/models/user.js b/lib/models/user.js index f13d0be10..211189171 100644 --- a/lib/models/user.js +++ b/lib/models/user.js @@ -2,7 +2,10 @@ * Module Dependencies. */ -var Model = require('../asteroid').Model; +var Model = require('../asteroid').Model + , asteroid = require('../asteroid') + , passport = require('passport') + , LocalStrategy = require('passport-local').Strategy; /** * Default User properties. @@ -12,7 +15,7 @@ var properties = { id: {type: String, required: true}, realm: {type: String}, username: {type: String, required: true}, - // password: {type: String, transient: true}, // Transient property + 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 @@ -42,3 +45,89 @@ var properties = { 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; + + this.findOne({username: credentials.username}, 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.settings.session || asteroid.Session; + + Session.create({uid: user.id}, function (err, session) { + if(err) { + fn(err); + } else { + fn(null, 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) { + // TODO - bcrypt + fn(null, this.password === plain); +} + +/** + * Override the extend method to setup any extended user models. + */ + +User.extend = function () { + var EUser = Model.extend.apply(User, arguments); + + setup(EUser); + + return EUser; +} + +function setup(UserModel) { + asteroid.remoteMethod( + UserModel.login, + { + accepts: [ + {arg: 'credentials', type: 'object', required: true, http: {source: 'body'}} + ], + returns: {arg: 'session', type: 'object'}, + http: {verb: 'post'} + } + ); + + return UserModel; +} + +setup(User); \ No newline at end of file diff --git a/package.json b/package.json index 127cad16f..80b328375 100644 --- a/package.json +++ b/package.json @@ -10,7 +10,10 @@ "express": "~3.1.1", "jugglingdb": "git+ssh://git@github.com:strongloop/jugglingdb.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" }, "devDependencies": { "mocha": "latest", diff --git a/test/user.test.js b/test/user.test.js new file mode 100644 index 000000000..55b6bf1b6 --- /dev/null +++ b/test/user.test.js @@ -0,0 +1,38 @@ +var User = asteroid.User; +var passport = require('passport'); + +describe('User', function(){ + + beforeEach(function (done) { + var memory = asteroid.createDataSource({ + connector: asteroid.Memory + }); + asteroid.User.attachTo(memory); + asteroid.Session.attachTo(memory); + app.use(asteroid.cookieParser()); + app.use(asteroid.auth()); + app.use(asteroid.rest()); + app.model(asteroid.User); + + asteroid.User.create({email: 'foo@bar.com', password: 'bar'}, done); + }); + + 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); + + done(); + }); + }); + }); +}); \ No newline at end of file From 42766a28c0ce5e77efd5019a085611adc7e0e5bf Mon Sep 17 00:00:00 2001 From: Ritchie Martori Date: Tue, 2 Jul 2013 22:37:31 -0700 Subject: [PATCH 05/39] Add basic email verification --- README.md | 79 ++++++++----------- lib/asteroid.js | 24 +++++- lib/models/email.js | 109 +++++++++++++++++++++++++++ lib/models/user.js | 176 +++++++++++++++++++++++++++++++++++++++++-- package.json | 4 +- templates/verify.ejs | 9 +++ test/model.test.js | 13 ++-- test/user.test.js | 150 ++++++++++++++++++++++++++++++++++-- 8 files changed, 492 insertions(+), 72 deletions(-) create mode 100644 lib/models/email.js create mode 100644 templates/verify.ejs diff --git a/README.md b/README.md index 2d772ee41..61053b459 100644 --- a/README.md +++ b/README.md @@ -866,7 +866,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); @@ -893,70 +893,55 @@ 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); }); -**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`. +**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`. #### Verify Email Addresses -To require email verification before a user is allowed to login, supply a verification property with a `verify` settings object. - - // define a User model - var User = asteroid.User.extend( - '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', - redirect: '/' - } - } - }, - { - // the model field - // that contains the user's email - // for verification and password reset - // defaults to 'email' - email: 'email', - resetTemplate: 'reset.ejs' - } - ); +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) and the verification property exists, 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 asteroid 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 asteroid 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'); + }); ### Email Model diff --git a/lib/asteroid.js b/lib/asteroid.js index 3ca416d49..6eb733e64 100644 --- a/lib/asteroid.js +++ b/lib/asteroid.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') @@ -212,7 +213,7 @@ asteroid.createModel = function (name, properties, options) { if(this.app) { var remotes = this.app.remotes(); remotes.before(self.pluralModelName + '.' + name, function (ctx, next) { - fn(ctx, ctx.instance, next); + fn(ctx, ctx.result, next); }); } else { var args = arguments; @@ -228,7 +229,7 @@ asteroid.createModel = function (name, properties, options) { if(this.app) { var remotes = this.app.remotes(); remotes.after(self.pluralModelName + '.' + name, function (ctx, next) { - fn(ctx, ctx.instance, next); + fn(ctx, ctx.result, next); }); } else { var args = arguments; @@ -257,10 +258,27 @@ asteroid.remoteMethod = function (fn, options) { fn.http = fn.http || {verb: 'get'}; } +/** + * Create a template helper. + * + * var render = asteroid.template('foo.ejs'); + * var html = render({foo: 'bar'}); + * + * @param {String} path Path to the template file. + * @returns {Function} + */ + +asteroid.template = function (file) { + var templates = this._templates || (this._templates = {}); + var str = templates[file] || (templates[file] = fs.readFileSync(file, 'utf8')); + return ejs.compile(str); +} + /* - * Built in models + * Built in models / services */ asteroid.Model = asteroid.createModel('model'); +asteroid.Email = require('./models/email'); asteroid.User = require('./models/user'); asteroid.Session = require('./models/session'); diff --git a/lib/models/email.js b/lib/models/email.js new file mode 100644 index 000000000..bcc9cb391 --- /dev/null +++ b/lib/models/email.js @@ -0,0 +1,109 @@ +/** + * Module Dependencies. + */ + +var Model = require('../asteroid').Model + , asteroid = require('../asteroid') + , 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 `asteroid.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/user.js b/lib/models/user.js index 211189171..bdd3d1ca7 100644 --- a/lib/models/user.js +++ b/lib/models/user.js @@ -4,6 +4,8 @@ var Model = require('../asteroid').Model , asteroid = require('../asteroid') + , path = require('path') + , crypto = require('crypto') , passport = require('passport') , LocalStrategy = require('passport-local').Strategy; @@ -13,7 +15,7 @@ var Model = require('../asteroid').Model var properties = { id: {type: String, required: true}, - realm: {type: String}, + 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) @@ -21,6 +23,7 @@ var properties = { macKey: {type: String}, // HMAC to calculate the hash code 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 ], @@ -91,6 +94,32 @@ User.login = function (credentials, fn) { } } +/** + * 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 || asteroid.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. * @@ -104,18 +133,113 @@ User.prototype.hasPassword = function (plain, fn) { } /** - * Override the extend method to setup any extended user models. + * Verify a user's identity. + * + * var options = { + * type: 'email', + * to: user.email, + * template: 'verify.ejs', + * redirect: '/' + * }; + * + * user.verify(options, next); + * + * @param {Object} options */ -User.extend = function () { - var EUser = Model.extend.apply(User, arguments); +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'); - setup(EUser); + 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; - return EUser; + + + // Email model + var Email = options.mailer || this.constructor.settings.email || asteroid.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 = asteroid.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}); + } + }); + } } -function setup(UserModel) { +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')); + } + } + }); +} + +/** + * Override the extend method to setup any extended user models. + */ + +User.setup = function () { + var UserModel = this; + asteroid.remoteMethod( UserModel.login, { @@ -127,7 +251,43 @@ function setup(UserModel) { } ); + asteroid.remoteMethod( + UserModel.logout, + { + accepts: [ + {arg: 'sid', type: 'string', required: true} + ], + http: {verb: 'all'} + } + ); + + asteroid.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')); + } + }); + }); + return UserModel; } -setup(User); \ No newline at end of file +/*! + * Setup the base user. + */ + +User.setup(); \ No newline at end of file diff --git a/package.json b/package.json index 80b328375..5f83d169d 100644 --- a/package.json +++ b/package.json @@ -13,7 +13,9 @@ "inflection": "~1.2.5", "bcrypt": "~0.7.6", "passport": "~0.1.17", - "passport-local": "~0.1.6" + "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/model.test.js b/test/model.test.js index 4ecf4d28d..2b08634ff 100644 --- a/test/model.test.js +++ b/test/model.test.js @@ -288,7 +288,7 @@ describe('Model', function() { 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(); }); @@ -312,12 +312,12 @@ describe('Model', function() { 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); @@ -466,7 +466,7 @@ describe('Model', function() { describe('Model.extend()', function(){ it('Create a new model by extending an existing model.', function() { - var User = asteroid.Model.extend('user', { + var User = asteroid.Model.extend('test-user', { email: String }); @@ -486,7 +486,6 @@ describe('Model', function() { assert.equal(MyUser.prototype.bar, User.prototype.bar); assert.equal(MyUser.foo, User.foo); - debugger; var user = new MyUser({ email: 'foo@bar.com', a: 'foo', diff --git a/test/user.test.js b/test/user.test.js index 55b6bf1b6..39997d8c1 100644 --- a/test/user.test.js +++ b/test/user.test.js @@ -1,14 +1,17 @@ var User = asteroid.User; +var Session = asteroid.Session; var passport = require('passport'); +var userMemory = asteroid.createDataSource({ + connector: asteroid.Memory +}); +asteroid.User.attachTo(userMemory); +asteroid.Session.attachTo(userMemory); +asteroid.Email.setup({transports: [{type: 'STUB'}]}); + describe('User', function(){ beforeEach(function (done) { - var memory = asteroid.createDataSource({ - connector: asteroid.Memory - }); - asteroid.User.attachTo(memory); - asteroid.Session.attachTo(memory); app.use(asteroid.cookieParser()); app.use(asteroid.auth()); app.use(asteroid.rest()); @@ -17,7 +20,11 @@ describe('User', function(){ asteroid.User.create({email: 'foo@bar.com', password: 'bar'}, done); }); - describe('User.login', function(){ + afterEach(function (done) { + Session.destroyAll(done); + }); + + describe('User.login', function() { it('Login a user by providing credentials.', function(done) { request(app) .post('/users/login') @@ -35,4 +42,135 @@ describe('User', function(){ }); }); }); + + describe('User.logout', function() { + it('Logout a user by providing the current session id.', 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)); + } + + function verify(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(); + }); + }); + }); + + 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({data: {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({data: {email: 'bar@bat.com', password: 'bar'}}) + .end(function(err, res){ + if(err) return done(err); + }); + }); + }); + }); }); \ No newline at end of file From 29d1077630af611ac0bbfa6eeca85882e505abec Mon Sep 17 00:00:00 2001 From: Raymond Feng Date: Wed, 26 Jun 2013 16:25:51 -0700 Subject: [PATCH 06/39] Add schema skeletons for built-in models --- lib/models/acl.js | 17 ++++++++++++++++ lib/models/application.js | 41 ++++++++++++++++++++++++++++++++++++++ lib/models/installation.js | 4 ++++ lib/models/role.js | 11 ++++++++++ lib/models/user.js | 11 ++++++++++ 5 files changed, 84 insertions(+) create mode 100644 lib/models/acl.js create mode 100644 lib/models/application.js create mode 100644 lib/models/installation.js create mode 100644 lib/models/role.js create mode 100644 lib/models/user.js diff --git a/lib/models/acl.js b/lib/models/acl.js new file mode 100644 index 000000000..d10f2c3c3 --- /dev/null +++ b/lib/models/acl.js @@ -0,0 +1,17 @@ +// Schema ACL options + + +// Object level permissions + +// open: no protection +// none: always rejected +// owner: only the owner +// loggedIn: any logged in user +// roles: logged in users with the roles +// related: owner of the related objects + +// Class level permissions + +// scopes + +// URL level permissions \ No newline at end of file diff --git a/lib/models/application.js b/lib/models/application.js new file mode 100644 index 000000000..173d2b971 --- /dev/null +++ b/lib/models/application.js @@ -0,0 +1,41 @@ +// Application model +var ApplicationSchema = { + + // Basic information + id: {type: String, required: true}, + name: {type: String, required: true}, + description: String, // description + icon: String, // The icon url + public: Boolean, + permissions: [String], + + userId: String, + + status: String, + + // Keys + clientKey: String, + javaScriptKey: String, + restApiKey: String, + windowsKey: String, + masterKey: String, + + // Push notification + pushPlatforms: [String], + pushCredentials: [], + + // Authentication + authenticationEnabled: Boolean, + anonymousAllowed: Boolean, + schemes: [String], // Basic, facebook, github, google + attachedCredentials: [], + + // email + email: String, // e-mail address + emailVerified: Boolean, // Is the e-mail verified + + collaborators: [String], // A list of users ids who have permissions to work on this app + + created: Date, + lastUpdated: Date +}; diff --git a/lib/models/installation.js b/lib/models/installation.js new file mode 100644 index 000000000..37e8bd0d1 --- /dev/null +++ b/lib/models/installation.js @@ -0,0 +1,4 @@ +// Device registration +var InstallationSchema = { + +}; diff --git a/lib/models/role.js b/lib/models/role.js new file mode 100644 index 000000000..a95467773 --- /dev/null +++ b/lib/models/role.js @@ -0,0 +1,11 @@ +// Role model +var RoleSchema = { + id: {type: String, required: true}, + name: {type: String, required: true}, + roles: [String], + users: [String], + acl: [], + + created: Date, + lastUpdated: Date +} \ No newline at end of file diff --git a/lib/models/user.js b/lib/models/user.js new file mode 100644 index 000000000..38d20452c --- /dev/null +++ b/lib/models/user.js @@ -0,0 +1,11 @@ +// User model +var UserSchema = { + id: {type: String, required: true}, + username: {type: String, required: true}, + password: String, + authData: [], + email: String, + emailVerified: Boolean, + created: Date, + lastUpdated: Date +} \ No newline at end of file From 7b8e94019fae6a8b52f7a184565d3568229e43a9 Mon Sep 17 00:00:00 2001 From: Ritchie Martori Date: Thu, 27 Jun 2013 18:26:44 -0700 Subject: [PATCH 07/39] Add normalized properties to Models --- README.md | 37 +++++++++++++++++++++++++++++++++++++ test/model.test.js | 32 ++++++++++++++++++++++++++++++++ 2 files changed, 69 insertions(+) diff --git a/README.md b/README.md index 3b331579a..608c2620a 100644 --- a/README.md +++ b/README.md @@ -140,6 +140,43 @@ Validate the model instance. } }); +#### Model.properties + +The an object containing a normalized set of properties supplied to `asteroid.createModel(name, properties)`. + +Example: + + var props = { + a: String, + b: {type: 'Number'}, + c: {type: 'String', min: 10, max: 100}, + d: Date, + e: asteroid.GeoPoint + }; + + var MyModel = asteroid.createModel('foo', props); + + console.log(MyModel.properties); + +Outputs: + + { + "a": {type: String}, + "b": {type: Number}, + "c": { + "type": String, + "min": 10, + "max": 100 + }, + "d": {type: Date}, + "e": {type: GeoPoint}, + "id": { + "id": 1 + } + } + +assert(MyModel.properties); + #### Model.attachTo(dataSource) Attach a model to a [DataSource](#data-source). Attaching a [DataSource](#data-source) updates the model with additional methods and behaviors. diff --git a/test/model.test.js b/test/model.test.js index 60a7b659b..44bad7cf1 100644 --- a/test/model.test.js +++ b/test/model.test.js @@ -431,6 +431,38 @@ describe('Model', function() { }); }); }); + + describe('Model.properties', function(){ + it('Normalized properties passed in originally by asteroid.createModel().', function() { + var props = { + s: String, + n: {type: 'Number'}, + o: {type: 'String', min: 10, max: 100}, + d: Date, + g: asteroid.GeoPoint + }; + + var MyModel = asteroid.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 + ) + } + }); + }); + }); // describe('Model.hasAndBelongsToMany()', function() { // it("TODO: implement / document", function(done) { From 184ecfec9b90ccd3d28ecefe0cbf677eeb768d6e Mon Sep 17 00:00:00 2001 From: Ritchie Martori Date: Thu, 27 Jun 2013 18:28:21 -0700 Subject: [PATCH 08/39] Fix type in docs --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 608c2620a..697f7b480 100644 --- a/README.md +++ b/README.md @@ -142,7 +142,7 @@ Validate the model instance. #### Model.properties -The an object containing a normalized set of properties supplied to `asteroid.createModel(name, properties)`. +An object containing a normalized set of properties supplied to `asteroid.createModel(name, properties)`. Example: From 3a15d7db0795ee7187128b02f199f31923aa2e86 Mon Sep 17 00:00:00 2001 From: Ritchie Martori Date: Thu, 27 Jun 2013 18:28:58 -0700 Subject: [PATCH 09/39] Fix type in docs --- README.md | 2 -- 1 file changed, 2 deletions(-) diff --git a/README.md b/README.md index 697f7b480..5b0f6c10a 100644 --- a/README.md +++ b/README.md @@ -174,8 +174,6 @@ Outputs: "id": 1 } } - -assert(MyModel.properties); #### Model.attachTo(dataSource) From 7f544576ddc142b15b9e2da64730891ca0fcc58b Mon Sep 17 00:00:00 2001 From: cgole Date: Fri, 28 Jun 2013 14:01:49 -0700 Subject: [PATCH 10/39] Update README.md Added limit:3 for GeoPoint find function example --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 5b0f6c10a..2df247bd2 100644 --- a/README.md +++ b/README.md @@ -742,7 +742,7 @@ Find the 3 nearest coffee shops. CoffeeShop.attachTo(oracle); var here = new GeoPoint({lat: 10.32424, lng: 5.84978}); - CoffeeShop.find({where: {location: {near: here}}}, function(err, nearbyShops) { + CoffeeShop.find({where: {location: {near: here}}, limit:3}, function(err, nearbyShops) { console.info(nearbyShops); // [CoffeeShop, ...] }); From 4aac4273e6e8f54c44a588cd8bec0f1bb18f8833 Mon Sep 17 00:00:00 2001 From: Ritchie Martori Date: Sun, 30 Jun 2013 17:38:53 -0700 Subject: [PATCH 11/39] Add more user model docs --- README.md | 166 +++++++++++++++++++++++++++++++++++++++++++++++++++--- 1 file changed, 157 insertions(+), 9 deletions(-) diff --git a/README.md b/README.md index 2df247bd2..0baadbcaf 100644 --- a/README.md +++ b/README.md @@ -794,36 +794,184 @@ Various APIs in Asteroid accept type descriptions (eg. [remote methods](#remote- - `Buffer` - a node.js Buffer object - [GeoPoint](#geopoint) - an asteroid GeoPoint object. TODO +#### Bundled Models + +The Asteroid library is unopinioned in the way you define your app's data and logic. Asteroid 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. + - 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. + - Job - _TODO_ schedule arbitrary code to run at a given time. + ### User Model -Allow users of your asteroid app to register and authenticate. +Register and authenticate users of your app locally or against 3rd party services. + +#### Create a User Model + +Extend a vanilla Asteroid model using the built in User model. // define a User model var User = asteroid.createModel( 'user', { - email: 'EmailAddress', + email: { + type: 'EmailAddress', + username: true + }, password: { + hideRemotely: true, // default for Password type: 'Password', min: 4, max: 26 } }, { - username: 'email', - extend: 'User' + extend: 'User', } ); - + // attach to the memory connector User.attachTo(memory); - // create a user - User.create({ - email: 'foo@bar.com', - password: '123456' + // expose over the app's api + app.model(User); + +#### User Creation + +Create a user like any other model. + + // username and password are not required + User.create({email: 'foo@bar.com', password: 'bar'}, function(err, user) { + console.log(user); + }); + +#### Authentication Strategies (Using Passport.js) + +Setup an authentication strategy. + +[See all available providers from passport.js](http://passportjs.org/guide/providers/). + + // first add your model to your app + app.model(User); + + // by default your User model has a local strategy similar to below + + // customize your own + // disable the default local strategy + User.useLocalStrategy(false); + + // create a custom strategy + var LocalStrategy = require('passport-local').Strategy; + User.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 }); } + user.comparePassword(password, function(err, isMatch) { + if (err) return done(err); + if(isMatch) { + return done(null, user); + } else { + return done(null, false, { message: 'Invalid password' }); + } + }); + }); + })); + + +#### Login a User + +Create a session for a user. When called remotely the password is required. + + User.login({username: 'foo', password: 'bar'}, function(err, session) { + console.log(session); + }); + +**REST** + +You must provide a username and password over rest. To ensure these values are encrypted, include these as part of the body and make sure you are serving your app over https (through a proxy or using the https node server). + + POST + + /users/login + ... + { + "email": "foo@bar.com", + "password": "bar" + } + + ... + + 200 OK + { + "sid": "1234abcdefg", + "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); + }); + +**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`. + +#### Verify Email Addresses + +To require email verification before a user is allowed to login, supply a verification property with a `verify` settings object. + + // define a User model + var User = asteroid.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' + } + ); + +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 }); +#### Remote Password Reset + +The password reset email will send users to a page rendered by asteroid with fields required to reset the user's password. You may customize this template by providing a `resetTemplate` option when defining your user model. ### Email Model From 90d990b798c12b742376bb628a9925edd775f905 Mon Sep 17 00:00:00 2001 From: Ritchie Martori Date: Mon, 1 Jul 2013 11:46:41 -0700 Subject: [PATCH 12/39] Remove app.modelBuilder() --- README.md | 12 +++++------- lib/application.js | 8 -------- test/model.test.js | 34 ++++++++++++++++++++++++++++++++++ 3 files changed, 39 insertions(+), 15 deletions(-) diff --git a/README.md b/README.md index 0baadbcaf..0d68a77e2 100644 --- a/README.md +++ b/README.md @@ -802,6 +802,8 @@ The Asteroid library is unopinioned in the way you define your app's data and lo - 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. - Job - _TODO_ schedule arbitrary code to run at a given time. + +Defining a model with `asteroid.createModel()` is really just extending the base `asteroid.Model` type using `asteroid.Model.extend()`. The bundled models extend from the base `asteroid.Model` allowing you to extend them arbitrarily. ### User Model @@ -812,7 +814,7 @@ Register and authenticate users of your app locally or against 3rd party service Extend a vanilla Asteroid model using the built in User model. // define a User model - var User = asteroid.createModel( + var User = asteroid.User.extend( 'user', { email: { @@ -825,9 +827,6 @@ Extend a vanilla Asteroid model using the built in User model. min: 4, max: 26 } - }, - { - extend: 'User', } ); @@ -923,7 +922,7 @@ You must provide a username and password over rest. To ensure these values are e To require email verification before a user is allowed to login, supply a verification property with a `verify` settings object. // define a User model - var User = asteroid.createModel( + var User = asteroid.User.extend( 'user', { email: { @@ -949,7 +948,6 @@ To require email verification before a user is allowed to login, supply a verifi } }, { - extend: 'User', // the model field // that contains the user's email // for verification and password reset @@ -959,7 +957,7 @@ To require email verification before a user is allowed to login, supply a verifi } ); -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. +When a user is created (on the server or remotely) and the verification property exists, 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 diff --git a/lib/application.js b/lib/application.js index 5094ae74f..c292c8d85 100644 --- a/lib/application.js +++ b/lib/application.js @@ -39,14 +39,6 @@ app.disuse = function (route) { } } -/** - * Get ModelBuilder. - */ - -app.modelBuilder = function () { - return this._modelBuilder || (this._modelBuilder = new ModelBuilder()) -} - /** * App models. */ diff --git a/test/model.test.js b/test/model.test.js index 44bad7cf1..bf2a5228b 100644 --- a/test/model.test.js +++ b/test/model.test.js @@ -463,6 +463,40 @@ describe('Model', function() { }); }); }); + + // describe('Model.extend()', function(){ + // it('Create a new model by extending an existing model.', function(done) { + // var User = asteroid.Model.extend('user', { + // email: String + // }); + // + // User.foo = function () { + // return 'bar'; + // } + // + // User.prototype.bar = function () { + // return 'foo'; + // } + // + // var MyUser = User.extend('my-user', { + // foo: String, + // bar: String + // }); + // + // assert(MyUser.prototype.bar === User.prototype.bar); + // assert(MyUser.foo === User.foo); + // + // var user = new MyUser({ + // email: 'foo@bar.com', + // foo: 'foo', + // bar: 'bar' + // }); + // + // assert.equal(user.email, 'foo@bar.com'); + // assert.equal(user.foo, 'foo'); + // assert.equal(user.bar, 'bar'); + // }); + // }); // describe('Model.hasAndBelongsToMany()', function() { // it("TODO: implement / document", function(done) { From 1abe583029e5513363b97edce252a6f06f23c653 Mon Sep 17 00:00:00 2001 From: Ritchie Martori Date: Mon, 1 Jul 2013 16:50:03 -0700 Subject: [PATCH 13/39] Add initial User model --- README.md | 21 +++----------- lib/asteroid.js | 6 ++++ lib/models/user.js | 24 ++++++++-------- test/model.test.js | 69 +++++++++++++++++++++++----------------------- 4 files changed, 58 insertions(+), 62 deletions(-) diff --git a/README.md b/README.md index 0d68a77e2..2d772ee41 100644 --- a/README.md +++ b/README.md @@ -814,21 +814,7 @@ Register and authenticate users of your app locally or against 3rd party service Extend a vanilla Asteroid model using the built in User model. // define a User model - var User = asteroid.User.extend( - 'user', - { - email: { - type: 'EmailAddress', - username: true - }, - password: { - hideRemotely: true, // default for Password - type: 'Password', - min: 4, - max: 26 - } - } - ); + var User = asteroid.User.extend('user'); // attach to the memory connector User.attachTo(memory); @@ -862,7 +848,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 }); } @@ -943,7 +929,8 @@ To require email verification before a user is allowed to login, supply a verifi // that contains the email // to verify email: 'email', - template: 'email.ejs' + template: 'email.ejs', + redirect: '/' } } }, diff --git a/lib/asteroid.js b/lib/asteroid.js index 4cb569bf6..7c2c46d4f 100644 --- a/lib/asteroid.js +++ b/lib/asteroid.js @@ -260,3 +260,9 @@ asteroid.remoteMethod = function (fn, options) { fn.http = fn.http || {verb: 'get'}; } +/* + * Built in models + */ + +asteroid.Model = asteroid.createModel('model'); +asteroid.User = require('./models/user'); diff --git a/lib/models/user.js b/lib/models/user.js index 38d20452c..531606d47 100644 --- a/lib/models/user.js +++ b/lib/models/user.js @@ -1,11 +1,13 @@ -// User model -var UserSchema = { - id: {type: String, required: true}, - username: {type: String, required: true}, - password: String, - authData: [], - email: String, - emailVerified: Boolean, - created: Date, - lastUpdated: Date -} \ No newline at end of file +/** + * Module Dependencies. + */ + +var Model = require('../asteroid').Model; + + +/** + * Extends from the built in `asteroid.Model` type. + */ + +var User = module.exports = Model.extend('user'); + diff --git a/test/model.test.js b/test/model.test.js index bf2a5228b..4ecf4d28d 100644 --- a/test/model.test.js +++ b/test/model.test.js @@ -463,40 +463,41 @@ describe('Model', function() { }); }); }); - - // describe('Model.extend()', function(){ - // it('Create a new model by extending an existing model.', function(done) { - // var User = asteroid.Model.extend('user', { - // email: String - // }); - // - // User.foo = function () { - // return 'bar'; - // } - // - // User.prototype.bar = function () { - // return 'foo'; - // } - // - // var MyUser = User.extend('my-user', { - // foo: String, - // bar: String - // }); - // - // assert(MyUser.prototype.bar === User.prototype.bar); - // assert(MyUser.foo === User.foo); - // - // var user = new MyUser({ - // email: 'foo@bar.com', - // foo: 'foo', - // bar: 'bar' - // }); - // - // assert.equal(user.email, 'foo@bar.com'); - // assert.equal(user.foo, 'foo'); - // assert.equal(user.bar, 'bar'); - // }); - // }); + + describe('Model.extend()', function(){ + it('Create a new model by extending an existing model.', function() { + var User = asteroid.Model.extend('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); + + debugger; + 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) { From 5f165852702368221f3bef35e90f68571359e0c2 Mon Sep 17 00:00:00 2001 From: Ritchie Martori Date: Mon, 1 Jul 2013 17:01:26 -0700 Subject: [PATCH 14/39] Add default user properties --- lib/models/user.js | 33 ++++++++++++++++++++++++++++++++- 1 file changed, 32 insertions(+), 1 deletion(-) diff --git a/lib/models/user.js b/lib/models/user.js index 531606d47..f13d0be10 100644 --- a/lib/models/user.js +++ b/lib/models/user.js @@ -4,10 +4,41 @@ var Model = require('../asteroid').Model; +/** + * Default User properties. + */ + +var properties = { + id: {type: String, required: true}, + 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 + email: String, + emailVerified: Boolean, + credentials: [ + 'UserCredential' // User credentials, private or public, such as private/public keys, Kerberos tickets, oAuth tokens, facebook, google, github ids + ], + challenges: [ + 'Challenge' // Security questions/answers + ], + // https://en.wikipedia.org/wiki/Multi-factor_authentication + /* + factors: [ + 'AuthenticationFactor' + ], + */ + status: String, + created: Date, + lastUpdated: Date +} + /** * Extends from the built in `asteroid.Model` type. */ -var User = module.exports = Model.extend('user'); +var User = module.exports = Model.extend('user', properties); From 8387a68b8556190d47b98be4751545fe0fe18921 Mon Sep 17 00:00:00 2001 From: Ritchie Martori Date: Tue, 2 Jul 2013 16:51:38 -0700 Subject: [PATCH 15/39] Initial users --- lib/application.js | 4 +- lib/asteroid.js | 10 ++--- lib/middleware/auth.js | 34 +++++++++++++++ lib/models/session.js | 22 ++++++++++ lib/models/user.js | 93 +++++++++++++++++++++++++++++++++++++++++- package.json | 5 ++- test/user.test.js | 38 +++++++++++++++++ 7 files changed, 194 insertions(+), 12 deletions(-) create mode 100644 lib/middleware/auth.js create mode 100644 lib/models/session.js create mode 100644 test/user.test.js diff --git a/lib/application.js b/lib/application.js index c292c8d85..703e630ed 100644 --- a/lib/application.js +++ b/lib/application.js @@ -55,9 +55,7 @@ app.model = function (Model) { this._models.push(Model); Model.shared = true; Model.app = this; - if(Model._remoteHooks) { - Model._remoteHooks.emit('attached', app); - } + Model.emit('attached', this); } /** diff --git a/lib/asteroid.js b/lib/asteroid.js index 7c2c46d4f..3ca416d49 100644 --- a/lib/asteroid.js +++ b/lib/asteroid.js @@ -216,8 +216,8 @@ asteroid.createModel = function (name, properties, options) { }); } else { var args = arguments; - this._remoteHooks.once('attached', function () { - self.beforeRemote.apply(ModelCtor, args); + this.once('attached', function () { + self.beforeRemote.apply(self, args); }); } } @@ -232,15 +232,12 @@ asteroid.createModel = function (name, properties, options) { }); } else { var args = arguments; - this._remoteHooks.once('attached', function () { + this.once('attached', function () { self.afterRemote.apply(ModelCtor, args); }); } } - // allow hooks to be added before attaching to an app - ModelCtor._remoteHooks = new EventEmitter(); - return ModelCtor; } @@ -266,3 +263,4 @@ asteroid.remoteMethod = function (fn, options) { asteroid.Model = asteroid.createModel('model'); asteroid.User = require('./models/user'); +asteroid.Session = require('./models/session'); diff --git a/lib/middleware/auth.js b/lib/middleware/auth.js new file mode 100644 index 000000000..79f8acd9b --- /dev/null +++ b/lib/middleware/auth.js @@ -0,0 +1,34 @@ +/** + * Module dependencies. + */ + +var asteroid = require('../asteroid') + , 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 = asteroid(); + + // TODO clean this up + sub._models = req.app._models; + sub._remotes = req.app._remotes; + + sub.use(asteroid.session({secret: 'change me'})) + sub.use(passport.initialize()); + sub.use(passport.session()); + + sub.handle(req, res, next); + } +} + + diff --git a/lib/models/session.js b/lib/models/session.js new file mode 100644 index 000000000..eadfeb5ed --- /dev/null +++ b/lib/models/session.js @@ -0,0 +1,22 @@ +/** + * Module Dependencies. + */ + +var Model = require('../asteroid').Model + , asteroid = require('../asteroid'); + +/** + * Default Session properties. + */ + +var properties = { + id: {type: String, required: true}, + uid: {type: String}, + ttl: {type: Number, ttl: true} +}; + +/** + * Extends from the built in `asteroid.Model` type. + */ + +var Session = module.exports = Model.extend('session', properties); \ No newline at end of file diff --git a/lib/models/user.js b/lib/models/user.js index f13d0be10..211189171 100644 --- a/lib/models/user.js +++ b/lib/models/user.js @@ -2,7 +2,10 @@ * Module Dependencies. */ -var Model = require('../asteroid').Model; +var Model = require('../asteroid').Model + , asteroid = require('../asteroid') + , passport = require('passport') + , LocalStrategy = require('passport-local').Strategy; /** * Default User properties. @@ -12,7 +15,7 @@ var properties = { id: {type: String, required: true}, realm: {type: String}, username: {type: String, required: true}, - // password: {type: String, transient: true}, // Transient property + 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 @@ -42,3 +45,89 @@ var properties = { 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; + + this.findOne({username: credentials.username}, 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.settings.session || asteroid.Session; + + Session.create({uid: user.id}, function (err, session) { + if(err) { + fn(err); + } else { + fn(null, 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) { + // TODO - bcrypt + fn(null, this.password === plain); +} + +/** + * Override the extend method to setup any extended user models. + */ + +User.extend = function () { + var EUser = Model.extend.apply(User, arguments); + + setup(EUser); + + return EUser; +} + +function setup(UserModel) { + asteroid.remoteMethod( + UserModel.login, + { + accepts: [ + {arg: 'credentials', type: 'object', required: true, http: {source: 'body'}} + ], + returns: {arg: 'session', type: 'object'}, + http: {verb: 'post'} + } + ); + + return UserModel; +} + +setup(User); \ No newline at end of file diff --git a/package.json b/package.json index 127cad16f..80b328375 100644 --- a/package.json +++ b/package.json @@ -10,7 +10,10 @@ "express": "~3.1.1", "jugglingdb": "git+ssh://git@github.com:strongloop/jugglingdb.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" }, "devDependencies": { "mocha": "latest", diff --git a/test/user.test.js b/test/user.test.js new file mode 100644 index 000000000..55b6bf1b6 --- /dev/null +++ b/test/user.test.js @@ -0,0 +1,38 @@ +var User = asteroid.User; +var passport = require('passport'); + +describe('User', function(){ + + beforeEach(function (done) { + var memory = asteroid.createDataSource({ + connector: asteroid.Memory + }); + asteroid.User.attachTo(memory); + asteroid.Session.attachTo(memory); + app.use(asteroid.cookieParser()); + app.use(asteroid.auth()); + app.use(asteroid.rest()); + app.model(asteroid.User); + + asteroid.User.create({email: 'foo@bar.com', password: 'bar'}, done); + }); + + 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); + + done(); + }); + }); + }); +}); \ No newline at end of file From fc0777de080cdd9378ee92086581017bcafcde65 Mon Sep 17 00:00:00 2001 From: Ritchie Martori Date: Tue, 2 Jul 2013 22:37:31 -0700 Subject: [PATCH 16/39] Add basic email verification --- README.md | 79 ++++++++----------- lib/asteroid.js | 24 +++++- lib/models/email.js | 109 +++++++++++++++++++++++++++ lib/models/user.js | 176 +++++++++++++++++++++++++++++++++++++++++-- package.json | 4 +- templates/verify.ejs | 9 +++ test/model.test.js | 13 ++-- test/user.test.js | 150 ++++++++++++++++++++++++++++++++++-- 8 files changed, 492 insertions(+), 72 deletions(-) create mode 100644 lib/models/email.js create mode 100644 templates/verify.ejs diff --git a/README.md b/README.md index 2d772ee41..61053b459 100644 --- a/README.md +++ b/README.md @@ -866,7 +866,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); @@ -893,70 +893,55 @@ 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); }); -**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`. +**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`. #### Verify Email Addresses -To require email verification before a user is allowed to login, supply a verification property with a `verify` settings object. - - // define a User model - var User = asteroid.User.extend( - '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', - redirect: '/' - } - } - }, - { - // the model field - // that contains the user's email - // for verification and password reset - // defaults to 'email' - email: 'email', - resetTemplate: 'reset.ejs' - } - ); +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) and the verification property exists, 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 asteroid 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 asteroid 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'); + }); ### Email Model diff --git a/lib/asteroid.js b/lib/asteroid.js index 3ca416d49..6eb733e64 100644 --- a/lib/asteroid.js +++ b/lib/asteroid.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') @@ -212,7 +213,7 @@ asteroid.createModel = function (name, properties, options) { if(this.app) { var remotes = this.app.remotes(); remotes.before(self.pluralModelName + '.' + name, function (ctx, next) { - fn(ctx, ctx.instance, next); + fn(ctx, ctx.result, next); }); } else { var args = arguments; @@ -228,7 +229,7 @@ asteroid.createModel = function (name, properties, options) { if(this.app) { var remotes = this.app.remotes(); remotes.after(self.pluralModelName + '.' + name, function (ctx, next) { - fn(ctx, ctx.instance, next); + fn(ctx, ctx.result, next); }); } else { var args = arguments; @@ -257,10 +258,27 @@ asteroid.remoteMethod = function (fn, options) { fn.http = fn.http || {verb: 'get'}; } +/** + * Create a template helper. + * + * var render = asteroid.template('foo.ejs'); + * var html = render({foo: 'bar'}); + * + * @param {String} path Path to the template file. + * @returns {Function} + */ + +asteroid.template = function (file) { + var templates = this._templates || (this._templates = {}); + var str = templates[file] || (templates[file] = fs.readFileSync(file, 'utf8')); + return ejs.compile(str); +} + /* - * Built in models + * Built in models / services */ asteroid.Model = asteroid.createModel('model'); +asteroid.Email = require('./models/email'); asteroid.User = require('./models/user'); asteroid.Session = require('./models/session'); diff --git a/lib/models/email.js b/lib/models/email.js new file mode 100644 index 000000000..bcc9cb391 --- /dev/null +++ b/lib/models/email.js @@ -0,0 +1,109 @@ +/** + * Module Dependencies. + */ + +var Model = require('../asteroid').Model + , asteroid = require('../asteroid') + , 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 `asteroid.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/user.js b/lib/models/user.js index 211189171..bdd3d1ca7 100644 --- a/lib/models/user.js +++ b/lib/models/user.js @@ -4,6 +4,8 @@ var Model = require('../asteroid').Model , asteroid = require('../asteroid') + , path = require('path') + , crypto = require('crypto') , passport = require('passport') , LocalStrategy = require('passport-local').Strategy; @@ -13,7 +15,7 @@ var Model = require('../asteroid').Model var properties = { id: {type: String, required: true}, - realm: {type: String}, + 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) @@ -21,6 +23,7 @@ var properties = { macKey: {type: String}, // HMAC to calculate the hash code 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 ], @@ -91,6 +94,32 @@ User.login = function (credentials, fn) { } } +/** + * 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 || asteroid.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. * @@ -104,18 +133,113 @@ User.prototype.hasPassword = function (plain, fn) { } /** - * Override the extend method to setup any extended user models. + * Verify a user's identity. + * + * var options = { + * type: 'email', + * to: user.email, + * template: 'verify.ejs', + * redirect: '/' + * }; + * + * user.verify(options, next); + * + * @param {Object} options */ -User.extend = function () { - var EUser = Model.extend.apply(User, arguments); +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'); - setup(EUser); + 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; - return EUser; + + + // Email model + var Email = options.mailer || this.constructor.settings.email || asteroid.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 = asteroid.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}); + } + }); + } } -function setup(UserModel) { +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')); + } + } + }); +} + +/** + * Override the extend method to setup any extended user models. + */ + +User.setup = function () { + var UserModel = this; + asteroid.remoteMethod( UserModel.login, { @@ -127,7 +251,43 @@ function setup(UserModel) { } ); + asteroid.remoteMethod( + UserModel.logout, + { + accepts: [ + {arg: 'sid', type: 'string', required: true} + ], + http: {verb: 'all'} + } + ); + + asteroid.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')); + } + }); + }); + return UserModel; } -setup(User); \ No newline at end of file +/*! + * Setup the base user. + */ + +User.setup(); \ No newline at end of file diff --git a/package.json b/package.json index 80b328375..5f83d169d 100644 --- a/package.json +++ b/package.json @@ -13,7 +13,9 @@ "inflection": "~1.2.5", "bcrypt": "~0.7.6", "passport": "~0.1.17", - "passport-local": "~0.1.6" + "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/model.test.js b/test/model.test.js index 4ecf4d28d..2b08634ff 100644 --- a/test/model.test.js +++ b/test/model.test.js @@ -288,7 +288,7 @@ describe('Model', function() { 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(); }); @@ -312,12 +312,12 @@ describe('Model', function() { 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); @@ -466,7 +466,7 @@ describe('Model', function() { describe('Model.extend()', function(){ it('Create a new model by extending an existing model.', function() { - var User = asteroid.Model.extend('user', { + var User = asteroid.Model.extend('test-user', { email: String }); @@ -486,7 +486,6 @@ describe('Model', function() { assert.equal(MyUser.prototype.bar, User.prototype.bar); assert.equal(MyUser.foo, User.foo); - debugger; var user = new MyUser({ email: 'foo@bar.com', a: 'foo', diff --git a/test/user.test.js b/test/user.test.js index 55b6bf1b6..39997d8c1 100644 --- a/test/user.test.js +++ b/test/user.test.js @@ -1,14 +1,17 @@ var User = asteroid.User; +var Session = asteroid.Session; var passport = require('passport'); +var userMemory = asteroid.createDataSource({ + connector: asteroid.Memory +}); +asteroid.User.attachTo(userMemory); +asteroid.Session.attachTo(userMemory); +asteroid.Email.setup({transports: [{type: 'STUB'}]}); + describe('User', function(){ beforeEach(function (done) { - var memory = asteroid.createDataSource({ - connector: asteroid.Memory - }); - asteroid.User.attachTo(memory); - asteroid.Session.attachTo(memory); app.use(asteroid.cookieParser()); app.use(asteroid.auth()); app.use(asteroid.rest()); @@ -17,7 +20,11 @@ describe('User', function(){ asteroid.User.create({email: 'foo@bar.com', password: 'bar'}, done); }); - describe('User.login', function(){ + afterEach(function (done) { + Session.destroyAll(done); + }); + + describe('User.login', function() { it('Login a user by providing credentials.', function(done) { request(app) .post('/users/login') @@ -35,4 +42,135 @@ describe('User', function(){ }); }); }); + + describe('User.logout', function() { + it('Logout a user by providing the current session id.', 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)); + } + + function verify(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(); + }); + }); + }); + + 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({data: {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({data: {email: 'bar@bat.com', password: 'bar'}}) + .end(function(err, res){ + if(err) return done(err); + }); + }); + }); + }); }); \ No newline at end of file From a22cf5f4af93f170ff127a8d6ad8289564d3d08b Mon Sep 17 00:00:00 2001 From: Ritchie Martori Date: Fri, 12 Jul 2013 12:40:36 -0700 Subject: [PATCH 17/39] Update docs and add asteroid.memory() sugar api - added asteroid.memory() - added default session and email models to user model --- README.md | 57 ++++++++++++++++++++++++++++++++++++---- lib/asteroid.js | 22 ++++++++++++++++ lib/models/user.js | 10 ++++--- test/asteroid.test.js | 14 ++++++++++ test/data-source.test.js | 2 ++ test/support.js | 4 +-- test/user.test.js | 4 +-- 7 files changed, 101 insertions(+), 12 deletions(-) diff --git a/README.md b/README.md index 61053b459..f67d37806 100644 --- a/README.md +++ b/README.md @@ -12,9 +12,13 @@ v0.9.0 - [Model](#model) - [DataSource](#data-source) - [Connectors](#connectors) - - [GeoPoint](#geo-point) - [Asteroid Types](#asteroid-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 asteroid application. Expose a `Model` to remote clients. - var memory = asteroid.createDataSource({connector: asteroid.Memory}); + // create a testing data source + var memory = asteroid.memory(); var Color = memory.createModel('color', {name: String}); + Color.attachTo(memory); app.model(Color); app.use(asteroid.rest()); @@ -794,13 +800,13 @@ Various APIs in Asteroid accept type descriptions (eg. [remote methods](#remote- - `Buffer` - a node.js Buffer object - [GeoPoint](#geopoint) - an asteroid GeoPoint object. TODO -#### Bundled Models +## Bundled Models The Asteroid library is unopinioned in the way you define your app's data and logic. Asteroid 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 `asteroid.createModel()` is really just extending the base `asteroid.Model` type using `asteroid.Model.extend()`. The bundled models extend from the base `asteroid.Model` allowing you to extend them arbitrarily. @@ -813,15 +819,38 @@ Register and authenticate users of your app locally or against 3rd party service Extend a vanilla Asteroid model using the built in User model. + // create a data source + var memory = asteroid.memory(); + // define a User model var User = asteroid.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 `asteroid.User` model uses the `asteroid.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 = asteroid.Session.extend('my-session'); + + // define a custom User model + var User = asteroid.User.extend('user'); + + // use the custom session model + User.session = MySession; + + // attaching to + + + #### User Creation Create a user like any other model. @@ -943,6 +972,24 @@ Confirm the password reset. console.log(err || 'your password was reset'); }); + +### Session Model + +Identify users by creating sessions when they connect to your asteroid app. By default the `asteroid.User` model uses the `asteroid.Session` model to persist sessions. You can change this by setting the `session` property. + + // define a custom session model + var MySession = asteroid.Session.extend('my-session'); + + // define a custom User model + var User = asteroid.User.extend('user'); + + // use the custom session model + User.session = MySession; + + // attach both Session and User to a data source + User.attachTo(asteroid.memory()); + MySession.attachTo(asteroid.memory()); + ### Email Model Send emails from your asteroid app. diff --git a/lib/asteroid.js b/lib/asteroid.js index 6eb733e64..ffa202600 100644 --- a/lib/asteroid.js +++ b/lib/asteroid.js @@ -274,6 +274,28 @@ asteroid.template = function (file) { 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. + */ + +asteroid.memory = function (name) { + name = name || 'default'; + var memory = ( + this._memoryDataSources + || (this._memoryDataSources = {}) + )[name]; + + if(!memory) { + memory = this._memoryDataSources[name] = asteroid.createDataSource({ + connector: asteroid.Memory + }); + } + + return memory; +} + /* * Built in models / services */ diff --git a/lib/models/user.js b/lib/models/user.js index bdd3d1ca7..9957c6b24 100644 --- a/lib/models/user.js +++ b/lib/models/user.js @@ -82,7 +82,7 @@ User.login = function (credentials, fn) { }); function createSession(user, fn) { - var Session = UserCtor.settings.session || asteroid.Session; + var Session = UserCtor.session; Session.create({uid: user.id}, function (err, session) { if(err) { @@ -170,7 +170,7 @@ User.prototype.verify = function (options, fn) { // Email model - var Email = options.mailer || this.constructor.settings.email || asteroid.Email; + var Email = options.mailer || this.constructor.email || asteroid.Email; crypto.randomBytes(64, function(err, buf) { if(err) { @@ -234,7 +234,7 @@ User.confirm = function (uid, token, redirect, fn) { } /** - * Override the extend method to setup any extended user models. + * Setup an extended user model. */ User.setup = function () { @@ -283,6 +283,10 @@ User.setup = function () { }); }); + // default models + UserModel.email = require('./email'); + UserModel.session = require('./session'); + return UserModel; } diff --git a/test/asteroid.test.js b/test/asteroid.test.js index 232ad8b4e..3b596931e 100644 --- a/test/asteroid.test.js +++ b/test/asteroid.test.js @@ -31,4 +31,18 @@ describe('asteroid', function() { assert.equal(Product.stats.shared, true); }); }); + + describe('asteroid.memory([name])', function(){ + it('Get an in-memory data source. Use one if it already exists.', function() { + var memory = asteroid.memory(); + assertValidDataSource(memory); + var m1 = asteroid.memory(); + var m2 = asteroid.memory('m2'); + var alsoM2 = asteroid.memory('m2'); + + assert(m1 === memory); + assert(m1 !== m2); + assert(alsoM2 === m2); + }); + }); }); \ No newline at end of file diff --git a/test/data-source.test.js b/test/data-source.test.js index a62512b6c..fb33ead48 100644 --- a/test/data-source.test.js +++ b/test/data-source.test.js @@ -5,6 +5,8 @@ describe('DataSource', function() { memory = asteroid.createDataSource({ connector: asteroid.Memory }); + + assertValidDataSource(memory); }); describe('dataSource.createModel(name, properties, settings)', function() { diff --git a/test/support.js b/test/support.js index e620f208f..24014c524 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 index 39997d8c1..8bef7ae2d 100644 --- a/test/user.test.js +++ b/test/user.test.js @@ -6,8 +6,8 @@ var userMemory = asteroid.createDataSource({ connector: asteroid.Memory }); asteroid.User.attachTo(userMemory); -asteroid.Session.attachTo(userMemory); -asteroid.Email.setup({transports: [{type: 'STUB'}]}); +asteroid.User.session.attachTo(userMemory); +asteroid.User.email.setup({transports: [{type: 'STUB'}]}); describe('User', function(){ From 78457fbeaf6c057950a9b6c0196505d0f9064eaa Mon Sep 17 00:00:00 2001 From: Ritchie Martori Date: Fri, 12 Jul 2013 12:53:38 -0700 Subject: [PATCH 18/39] Updated generated test docs --- test/README.md | 937 +++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 937 insertions(+) diff --git a/test/README.md b/test/README.md index 93dde8942..b7fc862f4 100644 --- a/test/README.md +++ b/test/README.md @@ -603,3 +603,940 @@ Book.create({title: 'Into the Wild', author: 'Jon Krakauer'}, function(err, book }); ``` +# TOC + - [app](#app) + - [app.model(Model)](#app-appmodelmodel) + - [app.models()](#app-appmodels) + - [asteroid](#asteroid) + - [asteroid.createDataSource(options)](#asteroid-asteroidcreatedatasourceoptions) + - [asteroid.remoteMethod(Model, fn, [options]);](#asteroid-asteroidremotemethodmodel-fn-options) + - [asteroid.memory([name])](#asteroid-asteroidmemoryname) + - [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) + - [Model](#model) + - [Model.validatesPresenceOf(properties...)](#model-modelvalidatespresenceofproperties) + - [Model.validatesLengthOf(property, options)](#model-modelvalidateslengthofproperty-options) + - [Model.validatesInclusionOf(property, options)](#model-modelvalidatesinclusionofproperty-options) + - [Model.validatesExclusionOf(property, options)](#model-modelvalidatesexclusionofproperty-options) + - [Model.validatesNumericalityOf(property, options)](#model-modelvalidatesnumericalityofproperty-options) + - [Model.validatesUniquenessOf(property, options)](#model-modelvalidatesuniquenessofproperty-options) + - [myModel.isValid()](#model-mymodelisvalid) + - [Model.attachTo(dataSource)](#model-modelattachtodatasource) + - [Model.create([data], [callback])](#model-modelcreatedata-callback) + - [model.save([options], [callback])](#model-modelsaveoptions-callback) + - [model.updateAttributes(data, [callback])](#model-modelupdateattributesdata-callback) + - [Model.upsert(data, callback)](#model-modelupsertdata-callback) + - [model.destroy([callback])](#model-modeldestroycallback) + - [Model.destroyAll(callback)](#model-modeldestroyallcallback) + - [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) + - [Model.beforeRemote(name, fn)](#model-remote-methods-modelbeforeremotename-fn) + - [Model.afterRemote(name, fn)](#model-remote-methods-modelafterremotename-fn) + - [Remote Method invoking context](#model-remote-methods-remote-method-invoking-context) + - [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.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.. + +```js +var memory = asteroid.createDataSource({connector: asteroid.Memory}); +var Color = memory.createModel('color', {name: String}); +app.model(Color); +assert.equal(app.models().length, 1); +``` + + +## app.models() +Get the app's exposed models.. + +```js +var Color = asteroid.createModel('color', {name: String}); +var models = app.models(); + +assert.equal(models.length, 1); +assert.equal(models[0].modelName, 'color'); +``` + + +# asteroid + +## asteroid.createDataSource(options) +Create a data source with a connector.. + +```js +var dataSource = asteroid.createDataSource({ + connector: asteroid.Memory +}); +assert(dataSource.connector()); +``` + + +## asteroid.remoteMethod(Model, fn, [options]); +Setup a remote method.. + +```js +var Product = asteroid.createModel('product', {price: Number}); + +Product.stats = function(fn) { + // ... +} + +asteroid.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); +``` + + +## asteroid.memory([name]) +Get an in-memory data source. Use one if it already exists.. + +```js +var memory = asteroid.memory(); +assertValidDataSource(memory); +var m1 = asteroid.memory(); +var m2 = asteroid.memory('m2'); +var alsoM2 = asteroid.memory('m2'); + +assert(m1 === memory); +assert(m1 !== m2); +assert(alsoM2 === m2); +``` + + +# DataSource + +## dataSource.createModel(name, properties, settings) +Define a model and attach it to a `DataSource`.. + +```js +var Color = memory.createModel('color', {name: String}); +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, 'destroyAll'); +assert.isFunc(Color, 'count'); +assert.isFunc(Color, 'include'); +assert.isFunc(Color, 'relationNameFor'); +assert.isFunc(Color, 'hasMany'); +assert.isFunc(Color, 'belongsTo'); +assert.isFunc(Color, 'hasAndBelongsToMany'); +assert.isFunc(Color.prototype, 'save'); +assert.isFunc(Color.prototype, 'isNewRecord'); +assert.isFunc(Color.prototype, 'destroy'); +assert.isFunc(Color.prototype, 'updateAttribute'); +assert.isFunc(Color.prototype, 'updateAttributes'); +assert.isFunc(Color.prototype, 'reload'); +``` + + +## dataSource.operations() +List the enabled and disabled operations.. + +```js +// assert the defaults +// - true: the method should be remote enabled +// - false: the method should not be remote enabled +// - +existsAndShared('_forDB', false); +existsAndShared('create', true); +existsAndShared('updateOrCreate', false); +existsAndShared('upsert', false); +existsAndShared('findOrCreate', false); +existsAndShared('exists', true); +existsAndShared('find', true); +existsAndShared('findOne', true); +existsAndShared('destroyAll', false); +existsAndShared('count', true); +existsAndShared('include', false); +existsAndShared('relationNameFor', false); +existsAndShared('hasMany', false); +existsAndShared('belongsTo', false); +existsAndShared('hasAndBelongsToMany', false); +existsAndShared('save', true); +existsAndShared('isNewRecord', false); +existsAndShared('_adapter', false); +existsAndShared('destroy', true); +existsAndShared('updateAttribute', true); +existsAndShared('updateAttributes', true); +existsAndShared('reload', true); + +function existsAndShared(name, isRemoteEnabled) { + var op = memory.getOperation(name); + assert(op.remoteEnabled === isRemoteEnabled, name + ' ' + (isRemoteEnabled ? 'should' : 'should not') + ' be remote enabled'); +} +``` + + +# 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 = asteroid.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); +``` + + +# Model + +## Model.validatesPresenceOf(properties...) +Require a model to include a property to be considered valid.. + +```js +User.validatesPresenceOf('first', 'last', 'age'); +var joe = new User({first: 'joe'}); +assert(joe.isValid() === false, 'model should not validate'); +assert(joe.errors.last, 'should have a missing last error'); +assert(joe.errors.age, 'should have a missing age error'); +``` + + +## Model.validatesLengthOf(property, options) +Require a property length to be within a specified range.. + +```js +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'); +assert(joe.errors.password, 'should have password error'); +``` + + +## Model.validatesInclusionOf(property, options) +Require a value for `property` to be in the specified array.. + +```js +User.validatesInclusionOf('gender', {in: ['male', 'female']}); +var foo = new User({gender: 'bar'}); +assert(foo.isValid() === false, 'model should not be valid'); +assert(foo.errors.gender, 'should have gender error'); +``` + + +## Model.validatesExclusionOf(property, options) +Require a value for `property` to not exist in the specified array.. + +```js +User.validatesExclusionOf('domain', {in: ['www', 'billing', 'admin']}); +var foo = new User({domain: 'www'}); +var bar = new User({domain: 'billing'}); +var bat = new User({domain: 'admin'}); +assert(foo.isValid() === false); +assert(bar.isValid() === false); +assert(bat.isValid() === false); +assert(foo.errors.domain, 'model should have a domain error'); +assert(bat.errors.domain, 'model should have a domain error'); +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`.. + +```js +User.validatesNumericalityOf('age', {int: true}); +var joe = new User({age: 10.2}); +assert(joe.isValid() === false); +var bob = new User({age: 0}); +assert(bob.isValid() === true); +assert(joe.errors.age, 'model should have an age error'); +``` + + +## Model.validatesUniquenessOf(property, options) +Ensure the value for `property` is unique.. + +```js +User.validatesUniquenessOf('email', {message: 'email is not unique'}); + +var joe = new User({email: 'joe@joe.com'}); +var joe2 = new User({email: 'joe@joe.com'}); + +joe.save(function () { + joe2.save(function (err) { + assert(err, 'should get a validation error'); + assert(joe2.errors.email, 'model should have email error'); + + done(); + }); +}); +``` + + +## myModel.isValid() +Validate the model instance.. + +```js +User.validatesNumericalityOf('age', {int: true}); +var user = new User({first: 'joe', age: 'flarg'}) +var valid = user.isValid(); +assert(valid === false); +assert(user.errors.age, 'model should have age error'); +``` + +Asynchronously validate the model.. + +```js +User.validatesNumericalityOf('age', {int: true}); +var user = new User({first: 'joe', age: 'flarg'}) +user.isValid(function (valid) { + assert(valid === false); + assert(user.errors.age, 'model should have age error'); + done(); +}); +``` + + +## Model.attachTo(dataSource) +Attach a model to a [DataSource](#data-source). + +```js +var MyModel = asteroid.createModel('my-model', {name: String}); + +assert(MyModel.find === undefined, 'should not have data access methods'); + +MyModel.attachTo(memory); + +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.. + +```js +User.create({first: 'Joe', last: 'Bob'}, function(err, user) { + assert(user instanceof User); + done(); +}); +``` + + +## model.save([options], [callback]) +Save an instance of a Model to the attached data source.. + +```js +var joe = new User({first: 'Joe', last: 'Bob'}); +joe.save(function(err, user) { + assert(user.id); + assert(!err); + assert(!user.errors); + done(); +}); +``` + + +## model.updateAttributes(data, [callback]) +Save specified attributes to the attached data source.. + +```js +User.create({first: 'joe', age: 100}, function (err, user) { + assert(!err); + assert.equal(user.first, 'joe'); + + user.updateAttributes({ + first: 'updatedFirst', + last: 'updatedLast' + }, function (err, updatedUser) { + assert(!err); + assert.equal(updatedUser.first, 'updatedFirst'); + assert.equal(updatedUser.last, 'updatedLast'); + assert.equal(updatedUser.age, 100); + done(); + }); +}); +``` + + +## Model.upsert(data, callback) +Update when record with id=data.id found, insert otherwise. + +```js +User.upsert({first: 'joe', id: 7}, function (err, user) { + assert(!err); + assert.equal(user.first, 'joe'); + + User.upsert({first: 'bob', id: 7}, function (err, updatedUser) { + assert(!err); + assert.equal(updatedUser.first, 'bob'); + done(); + }); +}); +``` + + +## model.destroy([callback]) +Remove a model from the attached data source.. + +```js +User.create({first: 'joe', last: 'bob'}, function (err, user) { + User.findById(user.id, function (err, foundUser) { + assert.equal(user.id, foundUser.id); + foundUser.destroy(function () { + User.findById(user.id, function (err, notFound) { + assert(!err); + assert.equal(notFound, null); + done(); + }); + }); + }); +}); +``` + + +## Model.destroyAll(callback) +Delete all Model instances from data source. + +```js +(new TaskEmitter()) + .task(User, 'create', {first: 'jill'}) + .task(User, 'create', {first: 'bob'}) + .task(User, 'create', {first: 'jan'}) + .task(User, 'create', {first: 'sam'}) + .task(User, 'create', {first: 'suzy'}) + .on('done', function () { + User.count(function (err, count) { + assert.equal(count, 5); + User.destroyAll(function () { + User.count(function (err, count) { + assert.equal(count, 0); + done(); + }); + }); + }); + }); +``` + + +## Model.findById(id, callback) +Find an instance by id.. + +```js +User.create({first: 'michael', last: 'jordan', id: 23}, function () { + User.findById(23, function (err, user) { + assert.equal(user.id, 23); + assert.equal(user.first, 'michael'); + assert.equal(user.last, 'jordan'); + done(); + }); +}); +``` + + +## Model.count([query], callback) +Query count of Model instances in data source. + +```js +(new TaskEmitter()) + .task(User, 'create', {first: 'jill', age: 100}) + .task(User, 'create', {first: 'bob', age: 200}) + .task(User, 'create', {first: 'jan'}) + .task(User, 'create', {first: 'sam'}) + .task(User, 'create', {first: 'suzy'}) + .on('done', function () { + User.count({age: {gt: 99}}, function (err, count) { + assert.equal(count, 2); + done(); + }); + }); +``` + + +## Remote Methods + +### Example Remote Method +Call the method using HTTP / REST. + +```js +request(app) + .get('/users/sign-in?username=foo&password=bar') + .expect('Content-Type', /json/) + .expect(200) + .end(function(err, res){ + if(err) return done(err); + assert(res.body.$data === 123); + done(); + }); +``` + + +### Model.beforeRemote(name, fn) +Run a function before a remote method is called by a client.. + +```js +var hookCalled = false; + +User.beforeRemote('create', function(ctx, user, next) { + hookCalled = true; + next(); +}); + +// invoke save +request(app) + .post('/users') + .send({data: {first: 'foo', last: 'bar'}}) + .expect('Content-Type', /json/) + .expect(200) + .end(function(err, res) { + if(err) return done(err); + assert(hookCalled, 'hook wasnt called'); + done(); + }); +``` + + +### Model.afterRemote(name, fn) +Run a function after a remote method is called by a client.. + +```js +var beforeCalled = false; +var afterCalled = false; + +User.beforeRemote('create', function(ctx, user, next) { + assert(!afterCalled); + beforeCalled = true; + next(); +}); +User.afterRemote('create', function(ctx, user, next) { + assert(beforeCalled); + afterCalled = true; + next(); +}); + +// invoke save +request(app) + .post('/users') + .send({data: {first: 'foo', last: 'bar'}}) + .expect('Content-Type', /json/) + .expect(200) + .end(function(err, res) { + if(err) return done(err); + assert(beforeCalled, 'before hook was not called'); + assert(afterCalled, 'after hook was not called'); + done(); + }); +``` + + +### Remote Method invoking context + +#### ctx.req +The express ServerRequest object. + +```js +var hookCalled = false; + +User.beforeRemote('create', function(ctx, user, next) { + hookCalled = true; + assert(ctx.req); + assert(ctx.req.url); + assert(ctx.req.method); + assert(ctx.res); + assert(ctx.res.write); + assert(ctx.res.end); + next(); +}); + +// invoke save +request(app) + .post('/users') + .send({data: {first: 'foo', last: 'bar'}}) + .expect('Content-Type', /json/) + .expect(200) + .end(function(err, res) { + if(err) return done(err); + assert(hookCalled); + done(); + }); +``` + + +#### ctx.res +The express ServerResponse object. + +```js +var hookCalled = false; + +User.beforeRemote('create', function(ctx, user, next) { + hookCalled = true; + assert(ctx.req); + assert(ctx.req.url); + assert(ctx.req.method); + assert(ctx.res); + assert(ctx.res.write); + assert(ctx.res.end); + next(); +}); + +// invoke save +request(app) + .post('/users') + .send({data: {first: 'foo', last: 'bar'}}) + .expect('Content-Type', /json/) + .expect(200) + .end(function(err, res) { + if(err) return done(err); + assert(hookCalled); + done(); + }); +``` + + +## Model.hasMany(Model) +Define a one to many relationship.. + +```js +var Book = memory.createModel('book', {title: String, author: String}); +var Chapter = memory.createModel('chapter', {title: String}); + +// by referencing model +Book.hasMany(Chapter); + +Book.create({title: 'Into the Wild', author: 'Jon Krakauer'}, function(err, book) { + // using 'chapters' scope for build: + var c = book.chapters.build({title: 'Chapter 1'}); + book.chapters.create({title: 'Chapter 2'}, function () { + c.save(function () { + Chapter.count({bookId: book.id}, function (err, count) { + assert.equal(count, 2); + book.chapters({where: {title: 'Chapter 1'}}, function(err, chapters) { + assert.equal(chapters.length, 1); + assert.equal(chapters[0].title, 'Chapter 1'); + done(); + }); + }); + }); + }); +}); +``` + + +## Model.properties +Normalized properties passed in originally by asteroid.createModel().. + +```js +var props = { + s: String, + n: {type: 'Number'}, + o: {type: 'String', min: 10, max: 100}, + d: Date, + g: asteroid.GeoPoint +}; + +var MyModel = asteroid.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 = asteroid.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.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); + + done(); + }); +``` + + +## User.logout +Logout a user by providing the current session id.. + +```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)); +} + +function verify(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); + }); + } +} +``` + + +## 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(); +}); +``` + + +## 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({data: {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({data: {email: 'bar@bat.com', password: 'bar'}}) + .end(function(err, res){ + if(err) return done(err); + }); +``` + From 9a62c48cfca78200b243c0eba0a495a30e584399 Mon Sep 17 00:00:00 2001 From: Ritchie Martori Date: Fri, 12 Jul 2013 13:38:52 -0700 Subject: [PATCH 19/39] Tests README --- test/README.md | 605 ------------------------------------------------- 1 file changed, 605 deletions(-) diff --git a/test/README.md b/test/README.md index b7fc862f4..44d20f69e 100644 --- a/test/README.md +++ b/test/README.md @@ -1,608 +1,3 @@ -# TOC - - [app](#app) - - [app.model(Model)](#app-appmodelmodel) - - [app.models()](#app-appmodels) - - [asteroid](#asteroid) - - [asteroid.createDataSource(options)](#asteroid-asteroidcreatedatasourceoptions) - - [asteroid.remoteMethod(Model, fn, [options]);](#asteroid-asteroidremotemethodmodel-fn-options) - - [DataSource](#datasource) - - [dataSource.createModel(name, properties, settings)](#datasource-datasourcecreatemodelname-properties-settings) - - [dataSource.operations()](#datasource-datasourceoperations) - - [Model](#model) - - [Model.validatesPresenceOf(properties...)](#model-modelvalidatespresenceofproperties) - - [Model.validatesLengthOf(property, options)](#model-modelvalidateslengthofproperty-options) - - [Model.validatesInclusionOf(property, options)](#model-modelvalidatesinclusionofproperty-options) - - [Model.validatesExclusionOf(property, options)](#model-modelvalidatesexclusionofproperty-options) - - [Model.validatesNumericalityOf(property, options)](#model-modelvalidatesnumericalityofproperty-options) - - [Model.validatesUniquenessOf(property, options)](#model-modelvalidatesuniquenessofproperty-options) - - [myModel.isValid()](#model-mymodelisvalid) - - [Model.attachTo(dataSource)](#model-modelattachtodatasource) - - [Model.create([data], [callback])](#model-modelcreatedata-callback) - - [model.save([options], [callback])](#model-modelsaveoptions-callback) - - [model.updateAttributes(data, [callback])](#model-modelupdateattributesdata-callback) - - [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.count([query], callback)](#model-modelcountquery-callback) - - [Remote Methods](#model-remote-methods) - - [Example Remote Method](#model-remote-methods-example-remote-method) - - [Model.beforeRemote(name, fn)](#model-remote-methods-modelbeforeremotename-fn) - - [Model.afterRemote(name, fn)](#model-remote-methods-modelafterremotename-fn) - - [Remote Method invoking context](#model-remote-methods-remote-method-invoking-context) - - [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) - - - -# app - -## app.model(Model) -Expose a `Model` to remote clients.. - -```js -var memory = asteroid.createDataSource({connector: asteroid.Memory}); -var Color = memory.createModel('color', {name: String}); -app.model(Color); -assert.equal(app.models().length, 1); -``` - - -## app.models() -Get the app's exposed models.. - -```js -var Color = asteroid.createModel('color', {name: String}); -var models = app.models(); - -assert.equal(models.length, 1); -assert.equal(models[0].modelName, 'color'); -``` - - -# asteroid - -## asteroid.createDataSource(options) -Create a data source with a connector.. - -```js -var dataSource = asteroid.createDataSource({ - connector: asteroid.Memory -}); -assert(dataSource.connector()); -``` - - -## asteroid.remoteMethod(Model, fn, [options]); -Setup a remote method.. - -```js -var Product = asteroid.createModel('product', {price: Number}); - -Product.stats = function(fn) { - // ... -} - -asteroid.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); -``` - - -# DataSource - -## dataSource.createModel(name, properties, settings) -Define a model and attach it to a `DataSource`.. - -```js -var Color = memory.createModel('color', {name: String}); -assert.isFunc(Color, 'all'); -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'); -assert.isFunc(Color, 'relationNameFor'); -assert.isFunc(Color, 'hasMany'); -assert.isFunc(Color, 'belongsTo'); -assert.isFunc(Color, 'hasAndBelongsToMany'); -assert.isFunc(Color.prototype, 'save'); -assert.isFunc(Color.prototype, 'isNewRecord'); -assert.isFunc(Color.prototype, 'destroy'); -assert.isFunc(Color.prototype, 'updateAttribute'); -assert.isFunc(Color.prototype, 'updateAttributes'); -assert.isFunc(Color.prototype, 'reload'); -``` - - -## dataSource.operations() -List the enabled and disabled operations.. - -```js -// assert the defaults -// - true: the method should be remote enabled -// - false: the method should not be remote enabled -// - -existsAndShared('_forDB', false); -existsAndShared('create', true); -existsAndShared('updateOrCreate', false); -existsAndShared('upsert', false); -existsAndShared('findOrCreate', false); -existsAndShared('exists', true); -existsAndShared('find', true); -existsAndShared('all', true); -existsAndShared('findOne', true); -existsAndShared('destroyAll', false); -existsAndShared('count', true); -existsAndShared('include', false); -existsAndShared('relationNameFor', false); -existsAndShared('hasMany', false); -existsAndShared('belongsTo', false); -existsAndShared('hasAndBelongsToMany', false); -existsAndShared('save', true); -existsAndShared('isNewRecord', false); -existsAndShared('_adapter', false); -existsAndShared('destroy', true); -existsAndShared('updateAttribute', true); -existsAndShared('updateAttributes', true); -existsAndShared('reload', true); - -function existsAndShared(name, isRemoteEnabled) { - var op = memory.getOperation(name); - assert(op.remoteEnabled === isRemoteEnabled, name + ' ' + (isRemoteEnabled ? 'should' : 'should not') + ' be remote enabled'); -} -``` - - -# Model - -## Model.validatesPresenceOf(properties...) -Require a model to include a property to be considered valid.. - -```js -User.validatesPresenceOf('first', 'last', 'age'); -var joe = new User({first: 'joe'}); -assert(joe.isValid() === false, 'model should not validate'); -assert(joe.errors.last, 'should have a missing last error'); -assert(joe.errors.age, 'should have a missing age error'); -``` - - -## Model.validatesLengthOf(property, options) -Require a property length to be within a specified range.. - -```js -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'); -assert(joe.errors.password, 'should have password error'); -``` - - -## Model.validatesInclusionOf(property, options) -Require a value for `property` to be in the specified array.. - -```js -User.validatesInclusionOf('gender', {in: ['male', 'female']}); -var foo = new User({gender: 'bar'}); -assert(foo.isValid() === false, 'model should not be valid'); -assert(foo.errors.gender, 'should have gender error'); -``` - - -## Model.validatesExclusionOf(property, options) -Require a value for `property` to not exist in the specified array.. - -```js -User.validatesExclusionOf('domain', {in: ['www', 'billing', 'admin']}); -var foo = new User({domain: 'www'}); -var bar = new User({domain: 'billing'}); -var bat = new User({domain: 'admin'}); -assert(foo.isValid() === false); -assert(bar.isValid() === false); -assert(bat.isValid() === false); -assert(foo.errors.domain, 'model should have a domain error'); -assert(bat.errors.domain, 'model should have a domain error'); -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`.. - -```js -User.validatesNumericalityOf('age', {int: true}); -var joe = new User({age: 10.2}); -assert(joe.isValid() === false); -var bob = new User({age: 0}); -assert(bob.isValid() === true); -assert(joe.errors.age, 'model should have an age error'); -``` - - -## Model.validatesUniquenessOf(property, options) -Ensure the value for `property` is unique.. - -```js -User.validatesUniquenessOf('email', {message: 'email is not unique'}); - -var joe = new User({email: 'joe@joe.com'}); -var joe2 = new User({email: 'joe@joe.com'}); - -joe.save(function () { - joe2.save(function (err) { - assert(err, 'should get a validation error'); - assert(joe2.errors.email, 'model should have email error'); - - done(); - }); -}); -``` - - -## myModel.isValid() -Validate the model instance.. - -```js -User.validatesNumericalityOf('age', {int: true}); -var user = new User({first: 'joe', age: 'flarg'}) -var valid = user.isValid(); -assert(valid === false); -assert(user.errors.age, 'model should have age error'); -``` - -Asynchronously validate the model.. - -```js -User.validatesNumericalityOf('age', {int: true}); -var user = new User({first: 'joe', age: 'flarg'}) -user.isValid(function (valid) { - assert(valid === false); - assert(user.errors.age, 'model should have age error'); - done(); -}); -``` - - -## Model.attachTo(dataSource) -Attach a model to a [DataSource](#data-source). - -```js -var MyModel = asteroid.createModel('my-model', {name: String}); - -assert(MyModel.all === 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'); -``` - - -## Model.create([data], [callback]) -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) { - assert(user instanceof User); - done(); -}); -``` - - -## model.save([options], [callback]) -Save an instance of a Model to the attached data source.. - -```js -var joe = new User({first: 'Joe', last: 'Bob'}); -joe.save(function(err, user) { - assert(user.id); - assert(!err); - assert(!user.errors); - done(); -}); -``` - - -## model.updateAttributes(data, [callback]) -Save specified attributes to the attached data source.. - -```js -User.create({first: 'joe', age: 100}, function (err, user) { - assert(!err); - assert.equal(user.first, 'joe'); - - user.updateAttributes({ - first: 'updatedFirst', - last: 'updatedLast' - }, function (err, updatedUser) { - assert(!err); - assert.equal(updatedUser.first, 'updatedFirst'); - assert.equal(updatedUser.last, 'updatedLast'); - assert.equal(updatedUser.age, 100); - done(); - }); -}); -``` - - -## Model.upsert(data, callback) -Update when record with id=data.id found, insert otherwise. - -```js -User.upsert({first: 'joe', id: 7}, function (err, user) { - assert(!err); - assert.equal(user.first, 'joe'); - - User.upsert({first: 'bob', id: 7}, function (err, updatedUser) { - assert(!err); - assert.equal(updatedUser.first, 'bob'); - done(); - }); -}); -``` - - -## model.destroy([callback]) -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) { - assert.equal(user.id, foundUser.id); - foundUser.destroy(function () { - User.find(user.id, function (err, notFound) { - assert(!err); - assert.equal(notFound, null); - done(); - }); - }); - }); -}); -``` - - -## Model.destroyAll(callback) -Delete all Model instances from data source. - -```js -(new TaskEmitter()) - .task(User, 'create', {first: 'jill'}) - .task(User, 'create', {first: 'bob'}) - .task(User, 'create', {first: 'jan'}) - .task(User, 'create', {first: 'sam'}) - .task(User, 'create', {first: 'suzy'}) - .on('done', function () { - User.count(function (err, count) { - assert.equal(count, 5); - User.destroyAll(function () { - User.count(function (err, count) { - assert.equal(count, 0); - done(); - }); - }); - }); - }); -``` - - -## Model.find(id, callback) -Find instance by id.. - -```js -User.create({first: 'michael', last: 'jordan', id: 23}, function () { - User.find(23, function (err, user) { - assert.equal(user.id, 23); - assert.equal(user.first, 'michael'); - assert.equal(user.last, 'jordan'); - done(); - }); -}); -``` - - -## Model.count([query], callback) -Query count of Model instances in data source. - -```js -(new TaskEmitter()) - .task(User, 'create', {first: 'jill', age: 100}) - .task(User, 'create', {first: 'bob', age: 200}) - .task(User, 'create', {first: 'jan'}) - .task(User, 'create', {first: 'sam'}) - .task(User, 'create', {first: 'suzy'}) - .on('done', function () { - User.count({age: {gt: 99}}, function (err, count) { - assert.equal(count, 2); - done(); - }); - }); -``` - - -## Remote Methods - -### Example Remote Method -Call the method using HTTP / REST. - -```js -request(app) - .get('/users/sign-in?username=foo&password=bar') - .expect('Content-Type', /json/) - .expect(200) - .end(function(err, res){ - if(err) return done(err); - assert(res.body.$data === 123); - done(); - }); -``` - - -### Model.beforeRemote(name, fn) -Run a function before a remote method is called by a client.. - -```js -var hookCalled = false; - -User.beforeRemote('*.save', function(ctx, user, next) { - hookCalled = true; - next(); -}); - -// invoke save -request(app) - .post('/users') - .send({data: {first: 'foo', last: 'bar'}}) - .expect('Content-Type', /json/) - .expect(200) - .end(function(err, res) { - if(err) return done(err); - assert(hookCalled, 'hook wasnt called'); - done(); - }); -``` - - -### Model.afterRemote(name, fn) -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) { - assert(!afterCalled); - beforeCalled = true; - next(); -}); -User.afterRemote('*.save', function(ctx, user, next) { - assert(beforeCalled); - afterCalled = true; - next(); -}); - -// invoke save -request(app) - .post('/users') - .send({data: {first: 'foo', last: 'bar'}}) - .expect('Content-Type', /json/) - .expect(200) - .end(function(err, res) { - if(err) return done(err); - assert(beforeCalled, 'before hook was not called'); - assert(afterCalled, 'after hook was not called'); - done(); - }); -``` - - -### Remote Method invoking context - -#### ctx.req -The express ServerRequest object. - -```js -var hookCalled = false; - -User.beforeRemote('*.save', function(ctx, user, next) { - hookCalled = true; - assert(ctx.req); - assert(ctx.req.url); - assert(ctx.req.method); - assert(ctx.res); - assert(ctx.res.write); - assert(ctx.res.end); - next(); -}); - -// invoke save -request(app) - .post('/users') - .send({data: {first: 'foo', last: 'bar'}}) - .expect('Content-Type', /json/) - .expect(200) - .end(function(err, res) { - if(err) return done(err); - assert(hookCalled); - done(); - }); -``` - - -#### ctx.res -The express ServerResponse object. - -```js -var hookCalled = false; - -User.beforeRemote('*.save', function(ctx, user, next) { - hookCalled = true; - assert(ctx.req); - assert(ctx.req.url); - assert(ctx.req.method); - assert(ctx.res); - assert(ctx.res.write); - assert(ctx.res.end); - next(); -}); - -// invoke save -request(app) - .post('/users') - .send({data: {first: 'foo', last: 'bar'}}) - .expect('Content-Type', /json/) - .expect(200) - .end(function(err, res) { - if(err) return done(err); - assert(hookCalled); - done(); - }); -``` - - -## Model.hasMany(Model) -Define a one to many relationship.. - -```js -var Book = memory.createModel('book', {title: String, author: String}); -var Chapter = memory.createModel('chapter', {title: String}); - -// by referencing model -Book.hasMany(Chapter); - -Book.create({title: 'Into the Wild', author: 'Jon Krakauer'}, function(err, book) { - // using 'chapters' scope for build: - var c = book.chapters.build({title: 'Chapter 1'}); - book.chapters.create({title: 'Chapter 2'}, function () { - c.save(function () { - Chapter.count({bookId: book.id}, function (err, count) { - assert.equal(count, 2); - book.chapters({where: {title: 'Chapter 1'}}, function(err, chapters) { - assert.equal(chapters.length, 1); - assert.equal(chapters[0].title, 'Chapter 1'); - done(); - }); - }); - }); - }); -}); -``` - # TOC - [app](#app) - [app.model(Model)](#app-appmodelmodel) From a09b527000a8e56be6e2542b3e5ec872b27de9fb Mon Sep 17 00:00:00 2001 From: Ritchie Martori Date: Fri, 12 Jul 2013 15:47:58 -0700 Subject: [PATCH 20/39] Create 64 byte session ids --- lib/models/session.js | 38 ++++++++++++++++++++++++++++++++++++-- test/user.test.js | 1 + 2 files changed, 37 insertions(+), 2 deletions(-) diff --git a/lib/models/session.js b/lib/models/session.js index eadfeb5ed..6ce1ed966 100644 --- a/lib/models/session.js +++ b/lib/models/session.js @@ -3,7 +3,8 @@ */ var Model = require('../asteroid').Model - , asteroid = require('../asteroid'); + , asteroid = require('../asteroid') + , crypto = require('crypto'); /** * Default Session properties. @@ -19,4 +20,37 @@ var properties = { * Extends from the built in `asteroid.Model` type. */ -var Session = module.exports = Model.extend('session', properties); \ No newline at end of file +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/test/user.test.js b/test/user.test.js index 8bef7ae2d..03aa348e5 100644 --- a/test/user.test.js +++ b/test/user.test.js @@ -37,6 +37,7 @@ describe('User', function(){ assert(session.uid); assert(session.id); + assert.equal((new Buffer(session.id, 'base64')).length, 64); done(); }); From 16617a373737dcc6a6c5f5a832cb74eec5af3bd3 Mon Sep 17 00:00:00 2001 From: Ritchie Martori Date: Fri, 12 Jul 2013 16:10:15 -0700 Subject: [PATCH 21/39] Add user.logout() sugar method and update logout docs --- README.md | 16 ++++++++++++--- lib/models/user.js | 12 ++++++++++++ test/user.test.js | 49 ++++++++++++++++++++++++++++++++++++---------- 3 files changed, 64 insertions(+), 13 deletions(-) diff --git a/README.md b/README.md index f67d37806..4d560d345 100644 --- a/README.md +++ b/README.md @@ -924,9 +924,19 @@ You must provide a username and password over rest. To ensure these values are e #### Logout a User - User.logout({username: 'foo'}, function(err) { - console.log(err); - }); +**NODE** + +// 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 + }); +}); + +// logout a user by username (server side only) + + +**REST** **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`. diff --git a/lib/models/user.js b/lib/models/user.js index 9957c6b24..1d720a52f 100644 --- a/lib/models/user.js +++ b/lib/models/user.js @@ -290,6 +290,18 @@ User.setup = function () { 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. */ diff --git a/test/user.test.js b/test/user.test.js index 03aa348e5..dee770e48 100644 --- a/test/user.test.js +++ b/test/user.test.js @@ -45,7 +45,19 @@ describe('User', function(){ }); describe('User.logout', function() { - it('Logout a user by providing the current session id.', function(done) { + 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) { @@ -70,19 +82,36 @@ describe('User', function(){ .post('/users/logout') .expect(200) .send({sid: sid}) - .end(verify(sid)); + .end(verify(sid, done)); } + }); + + it('Logout a user using the instance method.', function(done) { + login(logout); - function verify(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); - }); - } + 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(){ From d9b5daba0ea756a8e35cc98735b9b2ff76ba6a10 Mon Sep 17 00:00:00 2001 From: Ritchie Martori Date: Fri, 12 Jul 2013 17:03:13 -0700 Subject: [PATCH 22/39] Validate uniqueness and format of User email. --- README.md | 12 ++++++++++-- lib/models/user.js | 5 +++++ test/user.test.js | 46 +++++++++++++++++++++++++++++++++++++++++++++- 3 files changed, 60 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 4d560d345..117b7bd52 100644 --- a/README.md +++ b/README.md @@ -98,6 +98,12 @@ Define an asteroid 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. @@ -933,8 +939,10 @@ User.login({"email": "foo@bar.com", "password": "bar"}, function(err, session) { }); }); -// logout a user by username (server side only) - +// logout a user (server side only) +User.findOne({email: 'foo@bar.com'}, function(err, user) { + user.logout(); +}); **REST** diff --git a/lib/models/user.js b/lib/models/user.js index 1d720a52f..9b1e8e9f1 100644 --- a/lib/models/user.js +++ b/lib/models/user.js @@ -287,6 +287,11 @@ User.setup = function () { 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; } diff --git a/test/user.test.js b/test/user.test.js index dee770e48..c455efe25 100644 --- a/test/user.test.js +++ b/test/user.test.js @@ -10,6 +10,8 @@ asteroid.User.session.attachTo(userMemory); asteroid.User.email.setup({transports: [{type: 'STUB'}]}); describe('User', function(){ + + beforeEach(function (done) { app.use(asteroid.cookieParser()); @@ -21,7 +23,49 @@ describe('User', function(){ }); afterEach(function (done) { - Session.destroyAll(done); + asteroid.User.destroyAll(function (err) { + 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(); + }); + }); + }); }); describe('User.login', function() { From acfaee2fb0c3128f645d913e69cc3f46d430d5e4 Mon Sep 17 00:00:00 2001 From: Ritchie Martori Date: Mon, 15 Jul 2013 10:56:42 -0700 Subject: [PATCH 23/39] Remove data argument name from user tests --- test/user.test.js | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/test/user.test.js b/test/user.test.js index c455efe25..91f02166c 100644 --- a/test/user.test.js +++ b/test/user.test.js @@ -5,6 +5,7 @@ var passport = require('passport'); var userMemory = asteroid.createDataSource({ connector: asteroid.Memory }); + asteroid.User.attachTo(userMemory); asteroid.User.session.attachTo(userMemory); asteroid.User.email.setup({transports: [{type: 'STUB'}]}); @@ -201,7 +202,7 @@ describe('User', function(){ .post('/users') .expect('Content-Type', /json/) .expect(200) - .send({data: {email: 'bar@bat.com', password: 'bar'}}) + .send({email: 'bar@bat.com', password: 'bar'}) .end(function(err, res){ if(err) return done(err); }); @@ -240,7 +241,7 @@ describe('User', function(){ .post('/users') .expect('Content-Type', /json/) .expect(302) - .send({data: {email: 'bar@bat.com', password: 'bar'}}) + .send({email: 'bar@bat.com', password: 'bar'}) .end(function(err, res){ if(err) return done(err); }); From 3f7e4b693a6bf5140d7788e50818c0836b7037c7 Mon Sep 17 00:00:00 2001 From: Ritchie Martori Date: Mon, 15 Jul 2013 11:32:00 -0700 Subject: [PATCH 24/39] Refactor Model into class. Make createModel() just sugar. --- lib/asteroid.js | 92 +----------------------------------- lib/models/model.js | 110 ++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 112 insertions(+), 90 deletions(-) create mode 100644 lib/models/model.js diff --git a/lib/asteroid.js b/lib/asteroid.js index ffa202600..094e1d70e 100644 --- a/lib/asteroid.js +++ b/lib/asteroid.js @@ -151,95 +151,7 @@ asteroid.createDataSource = function (name, options) { */ asteroid.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.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(ModelCtor, args); - }); - } - } - - return ModelCtor; + return asteroid.Model.extend(name, properties, options); } /** @@ -300,7 +212,7 @@ asteroid.memory = function (name) { * Built in models / services */ -asteroid.Model = asteroid.createModel('model'); +asteroid.Model = require('./models/model'); asteroid.Email = require('./models/email'); asteroid.User = require('./models/user'); asteroid.Session = require('./models/session'); diff --git a/lib/models/model.js b/lib/models/model.js new file mode 100644 index 000000000..e987404f5 --- /dev/null +++ b/lib/models/model.js @@ -0,0 +1,110 @@ +/** + * Module Dependencies. + */ + +var ModelBuilder = require('jugglingdb').ModelBuilder +var modeler = new ModelBuilder(); + +/** + * Extends from the built in `asteroid.Model` type. + */ + +var Model = module.exports = modeler.define('model'); + +Model.shared = true; +Model.sharedCtor = function (data, id, fn) { + var ModelCtor = this; + + 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 +Model.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 +Model.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); + }); + } +} + +/*! + * Setup extended models. + */ + +Model.setup = function () { + var ModelCtor = this; + + 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 From aa8d1bb85335ade39e7b199a9d1c3757f1308d80 Mon Sep 17 00:00:00 2001 From: Ritchie Martori Date: Mon, 15 Jul 2013 14:07:17 -0700 Subject: [PATCH 25/39] Added bcrypt for password hashing --- lib/models/acl.js | 16 +++++++++++++++- lib/models/model.js | 16 +++++++++++++--- lib/models/user.js | 17 +++++++++++++++-- test/user.test.js | 26 ++++++++++++++++++++++++-- 4 files changed, 67 insertions(+), 8 deletions(-) diff --git a/lib/models/acl.js b/lib/models/acl.js index d10f2c3c3..14a6cf8c5 100644 --- a/lib/models/acl.js +++ b/lib/models/acl.js @@ -12,6 +12,20 @@ // Class level permissions +// 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: '*' + +// users only section +allow: '*' to: ['find', 'read', 'create'] +allow: 'owner' to: ['*.destroy', '*.save'] + // scopes -// URL level permissions \ No newline at end of file +// URL level permissions + + diff --git a/lib/models/model.js b/lib/models/model.js index e987404f5..b77433ad0 100644 --- a/lib/models/model.js +++ b/lib/models/model.js @@ -2,16 +2,21 @@ * Module Dependencies. */ -var ModelBuilder = require('jugglingdb').ModelBuilder +var ModelBuilder = require('jugglingdb').ModelBuilder; var modeler = new ModelBuilder(); /** - * Extends from the built in `asteroid.Model` type. + * Define the built in asteroid.Model. */ var Model = module.exports = modeler.define('model'); Model.shared = true; + +/*! + * For **remoting**. Construct objects when calling instance methods remotely. + */ + Model.sharedCtor = function (data, id, fn) { var ModelCtor = this; @@ -87,12 +92,17 @@ Model.afterRemote = function (name, fn) { } /*! - * Setup extended models. + * Called when a model is extended. */ Model.setup = function () { var ModelCtor = this; + // each model has its + // own access control + // list + Model.acl = []; + ModelCtor.sharedCtor.accepts = [ {arg: 'data', type: 'object', http: {source: 'body'}}, {arg: 'id', type: 'any', http: {source: 'url'}} diff --git a/lib/models/user.js b/lib/models/user.js index 9b1e8e9f1..e57cc1407 100644 --- a/lib/models/user.js +++ b/lib/models/user.js @@ -5,7 +5,9 @@ var Model = require('../asteroid').Model , asteroid = require('../asteroid') , path = require('path') + , SALT_WORK_FACTOR = 10 , crypto = require('crypto') + , bcrypt = require('bcrypt') , passport = require('passport') , LocalStrategy = require('passport-local').Strategy; @@ -128,8 +130,14 @@ User.logout = function (sid, fn) { */ User.prototype.hasPassword = function (plain, fn) { - // TODO - bcrypt - fn(null, this.password === plain); + if(this.password && plain) { + bcrypt.compare(plain, this.password, function(err, isMatch) { + if(err) return fn(err); + fn(null, isMatch); + }); + } else { + fn(null, false); + } } /** @@ -233,6 +241,11 @@ User.confirm = function (uid, token, redirect, fn) { }); } +User.setter.password = function (plain) { + var salt = bcrypt.genSaltSync(this.constructor.settings.saltWorkFactor || SALT_WORK_FACTOR); + this._password = bcrypt.hashSync(plain, salt); +} + /** * Setup an extended user model. */ diff --git a/test/user.test.js b/test/user.test.js index 91f02166c..bed60fd51 100644 --- a/test/user.test.js +++ b/test/user.test.js @@ -162,11 +162,33 @@ describe('User', function(){ 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 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(); + }); + }); + }); + }); + }); + }); + }); }); }); From 49da6f42493655f3860cfad73190ab0ce6275234 Mon Sep 17 00:00:00 2001 From: Ritchie Martori Date: Mon, 15 Jul 2013 18:22:33 -0700 Subject: [PATCH 26/39] Fix login bug. --- lib/models/user.js | 26 +++++++++++++++----------- test/user.test.js | 40 ++++++++++++++++++++++++++++++---------- 2 files changed, 45 insertions(+), 21 deletions(-) diff --git a/lib/models/user.js b/lib/models/user.js index e57cc1407..2410d3672 100644 --- a/lib/models/user.js +++ b/lib/models/user.js @@ -16,13 +16,9 @@ var Model = require('../asteroid').Model */ var properties = { - id: {type: String, required: true}, 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 email: String, emailVerified: Boolean, verificationToken: String, @@ -62,8 +58,17 @@ var User = module.exports = Model.extend('user', properties); User.login = function (credentials, fn) { var UserCtor = this; + var query = {}; - this.findOne({username: credentials.username}, function(err, user) { + 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) { @@ -240,12 +245,6 @@ User.confirm = function (uid, token, redirect, fn) { } }); } - -User.setter.password = function (plain) { - var salt = bcrypt.genSaltSync(this.constructor.settings.saltWorkFactor || SALT_WORK_FACTOR); - this._password = bcrypt.hashSync(plain, salt); -} - /** * Setup an extended user model. */ @@ -253,6 +252,11 @@ User.setter.password = function (plain) { 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); + } + asteroid.remoteMethod( UserModel.login, { diff --git a/test/user.test.js b/test/user.test.js index bed60fd51..73efdcf6b 100644 --- a/test/user.test.js +++ b/test/user.test.js @@ -1,4 +1,4 @@ -var User = asteroid.User; +var User = asteroid.User.extend('user'); var Session = asteroid.Session; var passport = require('passport'); @@ -6,26 +6,28 @@ var userMemory = asteroid.createDataSource({ connector: asteroid.Memory }); -asteroid.User.attachTo(userMemory); -asteroid.User.session.attachTo(userMemory); -asteroid.User.email.setup({transports: [{type: 'STUB'}]}); 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(asteroid.cookieParser()); app.use(asteroid.auth()); app.use(asteroid.rest()); - app.model(asteroid.User); + app.model(User); - asteroid.User.create({email: 'foo@bar.com', password: 'bar'}, done); + User.create({email: 'foo@bar.com', password: 'bar'}, done); }); afterEach(function (done) { - asteroid.User.destroyAll(function (err) { - Session.destroyAll(done); + User.destroyAll(function (err) { + User.session.destroyAll(done); }); }); @@ -67,6 +69,11 @@ describe('User', function(){ }); }); }); + + it('Hashes the given password.', function() { + var u = new User({username: 'foo', password: 'bar'}); + assert(u.password !== 'bar'); + }); }); describe('User.login', function() { @@ -168,6 +175,19 @@ describe('User', function(){ }); }); + 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) { From fbf0e35f1d633ed5673006526a88899fdecde637 Mon Sep 17 00:00:00 2001 From: Ritchie Martori Date: Mon, 15 Jul 2013 19:45:27 -0700 Subject: [PATCH 27/39] Remove updateAttribute as remote method --- lib/models/model.js | 114 +++++++++++++++++++-------------------- test/data-source.test.js | 1 - 2 files changed, 56 insertions(+), 59 deletions(-) diff --git a/lib/models/model.js b/lib/models/model.js index b77433ad0..e2cdb53d6 100644 --- a/lib/models/model.js +++ b/lib/models/model.js @@ -17,64 +17,6 @@ Model.shared = true; * For **remoting**. Construct objects when calling instance methods remotely. */ -Model.sharedCtor = function (data, id, fn) { - var ModelCtor = this; - - 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 -Model.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 Model.afterRemote = function (name, fn) { var self = this; @@ -103,6 +45,62 @@ Model.setup = function () { // list Model.acl = []; + Model.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); + }); + } + } + ModelCtor.sharedCtor.accepts = [ {arg: 'data', type: 'object', http: {source: 'body'}}, {arg: 'id', type: 'any', http: {source: 'url'}} diff --git a/test/data-source.test.js b/test/data-source.test.js index fb33ead48..832a9d446 100644 --- a/test/data-source.test.js +++ b/test/data-source.test.js @@ -61,7 +61,6 @@ describe('DataSource', function() { existsAndShared('isNewRecord', false); existsAndShared('_adapter', false); existsAndShared('destroy', true); - existsAndShared('updateAttribute', true); existsAndShared('updateAttributes', true); existsAndShared('reload', true); From 4be6ebceb7c169d5bb218afd64845308af33607b Mon Sep 17 00:00:00 2001 From: Ritchie Martori Date: Mon, 15 Jul 2013 20:14:04 -0700 Subject: [PATCH 28/39] Fix inheritance bug --- lib/models/model.js | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/lib/models/model.js b/lib/models/model.js index e2cdb53d6..f989940aa 100644 --- a/lib/models/model.js +++ b/lib/models/model.js @@ -43,9 +43,9 @@ Model.setup = function () { // each model has its // own access control // list - Model.acl = []; + ModelCtor.acl = []; - Model.sharedCtor = function (data, id, fn) { + ModelCtor.sharedCtor = function (data, id, fn) { if(typeof data === 'function') { fn = data; data = null; From 407a50f493c8a215efd66bf8ab4559839a4d2ad9 Mon Sep 17 00:00:00 2001 From: Ritchie Martori Date: Tue, 16 Jul 2013 10:25:02 -0700 Subject: [PATCH 29/39] Fix model remoting issue. --- lib/models/model.js | 42 +++++++++++++++++++----------------------- lib/models/user.js | 2 +- 2 files changed, 20 insertions(+), 24 deletions(-) diff --git a/lib/models/model.js b/lib/models/model.js index f989940aa..cee50fa3f 100644 --- a/lib/models/model.js +++ b/lib/models/model.js @@ -13,26 +13,6 @@ var Model = module.exports = modeler.define('model'); Model.shared = true; -/*! - * For **remoting**. Construct objects when calling instance methods remotely. - */ - -// after remote hook -Model.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); - }); - } -} - /*! * Called when a model is extended. */ @@ -62,11 +42,11 @@ Model.setup = function () { } if(id && data) { - var model = new ModelCtor(data); + var model = new ModelCtor(data, {remote: true}); model.id = id; fn(null, model); } else if(data) { - fn(null, new ModelCtor(data)); + fn(null, new ModelCtor(data, {remote: true})); } else if(id) { ModelCtor.find(id, function (err, model) { if(err) { @@ -101,6 +81,22 @@ Model.setup = function () { } } + // 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'}} @@ -110,7 +106,7 @@ Model.setup = function () { {path: '/'}, {path: '/:id'} ]; - + return ModelCtor; } diff --git a/lib/models/user.js b/lib/models/user.js index 2410d3672..f99f127f2 100644 --- a/lib/models/user.js +++ b/lib/models/user.js @@ -18,7 +18,7 @@ var Model = require('../asteroid').Model var properties = { realm: {type: String, }, username: {type: String, required: true}, - password: {type: String, transient: true}, // Transient property + password: {type: String, hideRemotely: true}, // Transient property email: String, emailVerified: Boolean, verificationToken: String, From 2f773115fea9131e09958670de7047a163c1a462 Mon Sep 17 00:00:00 2001 From: Raymond Feng Date: Tue, 16 Jul 2013 10:49:25 -0700 Subject: [PATCH 30/39] rename asteroid to loopback --- README.md | 132 +++++++++--------- example/colors/app.js | 6 +- example/simple-data-source/app.js | 6 +- example/todos/app.js | 10 +- index.js | 10 +- lib/asteroid.js | 218 ------------------------------ lib/middleware/auth.js | 6 +- lib/middleware/rest.js | 2 +- lib/models/email.js | 6 +- lib/models/model.js | 2 +- lib/models/session.js | 6 +- lib/models/user.js | 18 +-- package.json | 4 +- test/README.md | 56 ++++---- test/app.test.js | 4 +- test/asteroid.test.js | 48 ------- test/data-source.test.js | 4 +- test/geo-point.test.js | 2 +- test/model.test.js | 18 +-- test/support.js | 10 +- test/user.test.js | 14 +- 21 files changed, 158 insertions(+), 424 deletions(-) delete mode 100644 lib/asteroid.js delete mode 100644 test/asteroid.test.js diff --git a/README.md b/README.md index 117b7bd52..c8c3c7812 100644 --- a/README.md +++ b/README.md @@ -1,10 +1,10 @@ -# asteroid +# loopback v0.9.0 ## Install - slnode install asteroid -g + slnode install loopback -g ## Server API @@ -12,7 +12,7 @@ v0.9.0 - [Model](#model) - [DataSource](#data-source) - [Connectors](#connectors) - - [Asteroid Types](#asteroid-types) + - [Loopback Types](#loopback-types) - [GeoPoint](#geo-point) - [REST Router](#rest-router) - [Bundled Models](#bundled-models) @@ -26,10 +26,10 @@ _TODO_ ### App -Create an asteroid application. +Create an loopback application. - var asteroid = require('asteroid'); - var app = asteroid(); + var loopback = require('loopback'); + var app = loopback(); app.get('/', function(req, res){ res.send('hello world'); @@ -48,12 +48,12 @@ Create an asteroid application. Expose a `Model` to remote clients. // create a testing data source - var memory = asteroid.memory(); + var memory = loopback.memory(); var Color = memory.createModel('color', {name: String}); Color.attachTo(memory); app.model(Color); - app.use(asteroid.rest()); + app.use(loopback.rest()); **Note:** this will expose all [shared methods](#shared-methods) on the model. @@ -69,10 +69,10 @@ Get the app's exposed models. ### Model -An Asteroid `Model` is a vanilla JavaScript class constructor with an attached set of properties and options. A `Model` instance is created by passing a data object containing properties to the `Model` constructor. A `Model` constructor will clean the object passed to it and only set the values matching the properties you define. +An Loopback `Model` is a vanilla JavaScript class constructor with an attached set of properties and options. A `Model` instance is created by passing a data object containing properties to the `Model` constructor. A `Model` constructor will clean the object passed to it and only set the values matching the properties you define. // valid color - var Color = asteroid.createModel('color', {name: String}); + var Color = loopback.createModel('color', {name: String}); var red = new Color({name: 'red'}); console.log(red.name); // red @@ -88,9 +88,9 @@ A model defines a list of property names, types and other validation metadata. A Some [DataSources](#data-source) may support additional `Model` options. -Define an asteroid model. +Define an loopback model. - var User = asteroid.createModel('user', { + var User = loopback.createModel('user', { first: String, last: String, age: Number @@ -154,7 +154,7 @@ Validate the model instance. #### Model.properties -An object containing a normalized set of properties supplied to `asteroid.createModel(name, properties)`. +An object containing a normalized set of properties supplied to `loopback.createModel(name, properties)`. Example: @@ -163,10 +163,10 @@ Example: b: {type: 'Number'}, c: {type: 'String', min: 10, max: 100}, d: Date, - e: asteroid.GeoPoint + e: loopback.GeoPoint }; - var MyModel = asteroid.createModel('foo', props); + var MyModel = loopback.createModel('foo', props); console.log(MyModel.properties); @@ -191,8 +191,8 @@ Outputs: Attach a model to a [DataSource](#data-source). Attaching a [DataSource](#data-source) updates the model with additional methods and behaviors. - var oracle = asteroid.createDataSource({ - connector: require('asteroid-connector-oracle'), + var oracle = loopback.createDataSource({ + connector: require('loopback-connector-oracle'), host: '111.22.333.44', database: 'MYDB', username: 'username', @@ -296,7 +296,7 @@ Define a static model method. Setup the static model method to be exposed to clients as a [remote method](#remote-method). - asteroid.remoteMethod( + loopback.remoteMethod( User.login, { accepts: [ @@ -350,13 +350,13 @@ Define an instance method. Define a remote model instance method. - asteroid.remoteMethod(User.prototype.logout); + loopback.remoteMethod(User.prototype.logout); #### Remote Methods Both instance and static methods can be exposed to clients. A remote method must accept a callback with the conventional `fn(err, result, ...)` signature. -##### asteroid.remoteMethod(fn, [options]); +##### loopback.remoteMethod(fn, [options]); Expose a remote method. @@ -364,7 +364,7 @@ Expose a remote method. myApi.getStats('products', fn); } - asteroid.remoteMethod( + loopback.remoteMethod( Product.stats, { returns: {arg: 'stats', type: 'array'}, @@ -394,7 +394,7 @@ An arguments description defines either a single argument as an object or an ord **Types** -Each argument may define any of the [asteroid types](#asteroid-types). +Each argument may define any of the [loopback types](#loopback-types). **Notes:** @@ -464,7 +464,7 @@ During `afterRemote` hooks, `ctx.result` will contain the data about to be sent ##### Rest -When [asteroid.rest](#asteroidrest) is used the following `ctx` properties are available. +When [loopback.rest](#loopbackrest) is used the following `ctx` properties are available. ###### ctx.req @@ -522,15 +522,15 @@ TODO: implement / document #### Shared Methods -Any static or instance method can be decorated as `shared`. These methods are exposed over the provided transport (eg. [asteroid.rest](#rest)). +Any static or instance method can be decorated as `shared`. These methods are exposed over the provided transport (eg. [loopback.rest](#rest)). ### Data Source -An Asteroid `DataSource` provides [Models](#model) with the ability to manipulate data. Attaching a `DataSource` to a `Model` adds [instance methods](#instance-methods) and [static methods](#static-methods) to the `Model`. The added methods may be [remote methods](#remote-methods). +An Loopback `DataSource` provides [Models](#model) with the ability to manipulate data. Attaching a `DataSource` to a `Model` adds [instance methods](#instance-methods) and [static methods](#static-methods) to the `Model`. The added methods may be [remote methods](#remote-methods). Define a data source for persisting models. - var oracle = asteroid.createDataSource({ + var oracle = loopback.createDataSource({ connector: 'oracle', host: '111.22.333.44', database: 'MYDB', @@ -665,8 +665,8 @@ Disable remote access to a data source operation. Each [connector](#connector) h // all rest data source operations are // disabled by default - var oracle = asteroid.createDataSource({ - connector: require('asteroid-connector-oracle'), + var oracle = loopback.createDataSource({ + connector: require('loopback-connector-oracle'), host: '...', ... }); @@ -709,22 +709,22 @@ Output: Create a data source with a specific connector. See **available connectors** for specific connector documentation. - var memory = asteroid.createDataSource({ - connector: asteroid.Memory + var memory = loopback.createDataSource({ + connector: loopback.Memory }); **Available Connectors** - - [Oracle](http://github.com/strongloop/asteroid-connectors/oracle) - - [In Memory](http://github.com/strongloop/asteroid-connectors/memory) - - TODO - [REST](http://github.com/strongloop/asteroid-connectors/rest) - - TODO - [MySQL](http://github.com/strongloop/asteroid-connectors/mysql) - - TODO - [SQLite3](http://github.com/strongloop/asteroid-connectors/sqlite) - - TODO - [Postgres](http://github.com/strongloop/asteroid-connectors/postgres) - - TODO - [Redis](http://github.com/strongloop/asteroid-connectors/redis) - - TODO - [MongoDB](http://github.com/strongloop/asteroid-connectors/mongo) - - TODO - [CouchDB](http://github.com/strongloop/asteroid-connectors/couch) - - TODO - [Firebird](http://github.com/strongloop/asteroid-connectors/firebird) + - [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) **Installing Connectors** @@ -732,7 +732,7 @@ Include the connector in your package.json dependencies and run `npm install`. { "dependencies": { - "asteroid-connector-oracle": "latest" + "loopback-connector-oracle": "latest" } } @@ -740,15 +740,15 @@ Include the connector in your package.json dependencies and run `npm install`. Use the `GeoPoint` class. - var GeoPoint = require('asteroid').GeoPoint; + var GeoPoint = require('loopback').GeoPoint; Embed a latitude / longitude point in a [Model](#model). - var CoffeeShop = asteroid.createModel('coffee-shop', { + var CoffeeShop = loopback.createModel('coffee-shop', { location: 'GeoPoint' }); -Asteroid Model's with a GeoPoint property and an attached DataSource may be queried using geo spatial filters and sorting. +Loopback Model's with a GeoPoint property and an attached DataSource may be queried using geo spatial filters and sorting. Find the 3 nearest coffee shops. @@ -792,9 +792,9 @@ The latitude point in degrees. Range: -90 to 90. The longitude point in degrees. Range: -180 to 180. -### Asteroid Types +### Loopback Types -Various APIs in Asteroid accept type descriptions (eg. [remote methods](#remote-methods), [asteroid.createModel()](#model)). The following is a list of supported types. +Various APIs in Loopback accept type descriptions (eg. [remote methods](#remote-methods), [loopback.createModel()](#model)). The following is a list of supported types. - `null` - JSON null - `Boolean` - JSON boolean @@ -804,18 +804,18 @@ Various APIs in Asteroid accept type descriptions (eg. [remote methods](#remote- - `Array` - JSON array - `Date` - a JavaScript date object - `Buffer` - a node.js Buffer object - - [GeoPoint](#geopoint) - an asteroid GeoPoint object. TODO + - [GeoPoint](#geopoint) - an loopback GeoPoint object. TODO ## Bundled Models -The Asteroid library is unopinioned in the way you define your app's data and logic. Asteroid also bundles useful pre-built models for common use cases. +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 - 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 - 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 `asteroid.createModel()` is really just extending the base `asteroid.Model` type using `asteroid.Model.extend()`. The bundled models extend from the base `asteroid.Model` allowing you to extend them arbitrarily. +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 @@ -823,13 +823,13 @@ Register and authenticate users of your app locally or against 3rd party service #### Create a User Model -Extend a vanilla Asteroid model using the built in User model. +Extend a vanilla Loopback model using the built in User model. // create a data source - var memory = asteroid.memory(); + var memory = loopback.memory(); // define a User model - var User = asteroid.User.extend('user'); + var User = loopback.User.extend('user'); // attach to the memory connector User.attachTo(memory); @@ -840,15 +840,15 @@ Extend a vanilla Asteroid model using the built in User model. // expose over the app's api app.model(User); -**Note:** By default the `asteroid.User` model uses the `asteroid.Session` model to persist sessions. You can change this by setting the `session` property. +**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 = asteroid.Session.extend('my-session'); + var MySession = loopback.Session.extend('my-session'); // define a custom User model - var User = asteroid.User.extend('user'); + var User = loopback.User.extend('user'); // use the custom session model User.session = MySession; @@ -978,7 +978,7 @@ Send an email to the user's supplied email address containing a link to reset th #### Remote Password Reset -The password reset email will send users to a page rendered by asteroid with fields required to reset the user's password. You may customize this template by defining a `resetTemplate` setting. +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'; @@ -993,30 +993,30 @@ Confirm the password reset. ### Session Model -Identify users by creating sessions when they connect to your asteroid app. By default the `asteroid.User` model uses the `asteroid.Session` model to persist sessions. You can change this by setting the `session` property. +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 = asteroid.Session.extend('my-session'); + var MySession = loopback.Session.extend('my-session'); // define a custom User model - var User = asteroid.User.extend('user'); + 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(asteroid.memory()); - MySession.attachTo(asteroid.memory()); + User.attachTo(loopback.memory()); + MySession.attachTo(loopback.memory()); ### Email Model -Send emails from your asteroid app. +Send emails from your loopback app. ### REST Router -Expose models over rest using the `asteroid.rest` router. +Expose models over rest using the `loopback.rest` router. - app.use(asteroid.rest()); + app.use(loopback.rest()); **REST Documentation** @@ -1024,7 +1024,7 @@ View generated REST documentation by visiting: [http://localhost:3000/_docs](htt ### SocketIO Middleware **Not Available** -**Coming Soon** - Expose models over socket.io using the `asteroid.sio()` middleware. +**Coming Soon** - Expose models over socket.io using the `loopback.sio()` middleware. - app.use(asteroid.sio); + app.use(loopback.sio); diff --git a/example/colors/app.js b/example/colors/app.js index 5572b2e2a..a7fdb01ff 100644 --- a/example/colors/app.js +++ b/example/colors/app.js @@ -1,7 +1,7 @@ -var asteroid = require('../../'); -var app = asteroid(); +var loopback = require('../../'); +var app = loopback(); -app.use(asteroid.rest()); +app.use(loopback.rest()); var schema = { name: String diff --git a/example/simple-data-source/app.js b/example/simple-data-source/app.js index 9b4f0569b..08d6d94a9 100644 --- a/example/simple-data-source/app.js +++ b/example/simple-data-source/app.js @@ -1,7 +1,7 @@ -var asteroid = require('../../'); -var app = asteroid(); +var loopback = require('../../'); +var app = loopback(); -app.use(asteroid.rest()); +app.use(loopback.rest()); var dataSource = app.dataSource('db', {adapter: 'memory'}); diff --git a/example/todos/app.js b/example/todos/app.js index f5411dc54..8a2dd3041 100644 --- a/example/todos/app.js +++ b/example/todos/app.js @@ -1,8 +1,8 @@ -var asteroid = require('../../'); -var app = asteroid(); +var loopback = require('../../'); +var app = loopback(); -app.use(asteroid.configure()); -app.use(asteroid.bodyParser()); -app.use(asteroid.routes()); +app.use(loopback.configure()); +app.use(loopback.bodyParser()); +app.use(loopback.routes()); app.listen(3000); \ No newline at end of file diff --git a/index.js b/index.js index 39bdd874d..e58027801 100644 --- a/index.js +++ b/index.js @@ -1,18 +1,18 @@ /** - * asteroid ~ public api + * loopback ~ public api */ -var asteroid = module.exports = require('./lib/asteroid'); +var loopback = module.exports = require('./lib/loopback'); /** * Connectors */ -asteroid.Connector = require('./lib/connectors/base-connector'); -asteroid.Memory = require('./lib/connectors/memory'); +loopback.Connector = require('./lib/connectors/base-connector'); +loopback.Memory = require('./lib/connectors/memory'); /** * Types */ -asteroid.GeoPoint = require('jugglingdb/lib/geo').GeoPoint; \ No newline at end of file +loopback.GeoPoint = require('jugglingdb/lib/geo').GeoPoint; \ No newline at end of file diff --git a/lib/asteroid.js b/lib/asteroid.js deleted file mode 100644 index 094e1d70e..000000000 --- a/lib/asteroid.js +++ /dev/null @@ -1,218 +0,0 @@ -/** - * Module dependencies. - */ - -var express = require('express') - , fs = require('fs') - , ejs = require('ejs') - , EventEmitter = require('events').EventEmitter - , path = require('path') - , proto = require('./application') - , utils = require('express/node_modules/connect').utils - , DataSource = require('jugglingdb').DataSource - , ModelBuilder = require('jugglingdb').ModelBuilder - , assert = require('assert') - , i8n = require('inflection'); - -/** - * Expose `createApplication()`. - */ - -var asteroid = exports = module.exports = createApplication; - -/** - * Framework version. - */ - -asteroid.version = require('../package.json').version; - -/** - * Expose mime. - */ - -asteroid.mime = express.mime; - -/** - * Create an asteroid application. - * - * @return {Function} - * @api public - */ - -function createApplication() { - var app = express(); - - utils.merge(app, proto); - - return app; -} - -/** - * Expose express.middleware as asteroid.* - * for example `asteroid.errorHandler` etc. - */ - -for (var key in express) { - Object.defineProperty( - asteroid - , key - , Object.getOwnPropertyDescriptor(express, key)); -} - -/** - * Expose additional asteroid middleware - * for example `asteroid.configure` etc. - */ - -fs - .readdirSync(path.join(__dirname, 'middleware')) - .filter(function (file) { - return file.match(/\.js$/); - }) - .forEach(function (m) { - asteroid[m.replace(/\.js$/, '')] = require('./middleware/' + m); - }); - -/** - * Error handler title - */ - -asteroid.errorHandler.title = 'Asteroid'; - -/** - * Create a data source with passing the provided options to the connector. - * - * @param {String} name (optional) - * @param {Object} options - * - * - connector - an asteroid connector - * - other values - see the specified `connector` docs - */ - -asteroid.createDataSource = function (name, options) { - var ds = new DataSource(name, options); - ds.createModel = function (name, properties, settings) { - var ModelCtor = asteroid.createModel(name, properties, settings); - ModelCtor.attachTo(ds); - - var hasMany = ModelCtor.hasMany; - - if(hasMany) { - ModelCtor.hasMany = function (anotherClass, params) { - var origArgs = arguments; - var thisClass = this, thisClassName = this.modelName; - params = params || {}; - if (typeof anotherClass === 'string') { - params.as = anotherClass; - if (params.model) { - anotherClass = params.model; - } else { - var anotherClassName = i8n.singularize(anotherClass).toLowerCase(); - for(var name in this.schema.models) { - if (name.toLowerCase() === anotherClassName) { - anotherClass = this.schema.models[name]; - } - } - } - } - - var pluralized = i8n.pluralize(anotherClass.modelName); - var methodName = params.as || - i8n.camelize(pluralized, true); - var proxyMethodName = 'get' + i8n.titleize(pluralized, true); - - // create a proxy method - var fn = this.prototype[proxyMethodName] = function () { - // this[methodName] cannot be a shared method - // because it is defined inside - // a property getter... - - this[methodName].apply(thisClass, arguments); - }; - - fn.shared = true; - fn.http = {verb: 'get', path: '/' + methodName}; - fn.accepts = {arg: 'where', type: 'object'}; - hasMany.apply(this, arguments); - }; - } - - return ModelCtor; - } - return ds; -} - -/** - * Create a named vanilla JavaScript class constructor with an attached set of properties and options. - * - * @param {String} name - must be unique - * @param {Object} properties - * @param {Object} options (optional) - */ - -asteroid.createModel = function (name, properties, options) { - return asteroid.Model.extend(name, properties, options); -} - -/** - * Add a remote method to a model. - * @param {Function} fn - * @param {Object} options (optional) - */ - -asteroid.remoteMethod = function (fn, options) { - fn.shared = true; - if(typeof options === 'object') { - Object.keys(options).forEach(function (key) { - fn[key] = options[key]; - }); - } - fn.http = fn.http || {verb: 'get'}; -} - -/** - * Create a template helper. - * - * var render = asteroid.template('foo.ejs'); - * var html = render({foo: 'bar'}); - * - * @param {String} path Path to the template file. - * @returns {Function} - */ - -asteroid.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. - */ - -asteroid.memory = function (name) { - name = name || 'default'; - var memory = ( - this._memoryDataSources - || (this._memoryDataSources = {}) - )[name]; - - if(!memory) { - memory = this._memoryDataSources[name] = asteroid.createDataSource({ - connector: asteroid.Memory - }); - } - - return memory; -} - -/* - * Built in models / services - */ - -asteroid.Model = require('./models/model'); -asteroid.Email = require('./models/email'); -asteroid.User = require('./models/user'); -asteroid.Session = require('./models/session'); diff --git a/lib/middleware/auth.js b/lib/middleware/auth.js index 79f8acd9b..c278aa8c7 100644 --- a/lib/middleware/auth.js +++ b/lib/middleware/auth.js @@ -2,7 +2,7 @@ * Module dependencies. */ -var asteroid = require('../asteroid') +var loopback = require('../loopback') , passport = require('passport'); /** @@ -17,13 +17,13 @@ module.exports = auth; function auth() { return function (req, res, next) { - var sub = asteroid(); + var sub = loopback(); // TODO clean this up sub._models = req.app._models; sub._remotes = req.app._remotes; - sub.use(asteroid.session({secret: 'change me'})) + sub.use(loopback.session({secret: 'change me'})) sub.use(passport.initialize()); sub.use(passport.session()); diff --git a/lib/middleware/rest.js b/lib/middleware/rest.js index a22dadcfc..468d0a443 100644 --- a/lib/middleware/rest.js +++ b/lib/middleware/rest.js @@ -2,7 +2,7 @@ * Module dependencies. */ -var asteroid = require('../asteroid'); +var loopback = require('../loopback'); var RemoteObjects = require('sl-remoting'); /** diff --git a/lib/models/email.js b/lib/models/email.js index bcc9cb391..e9358b2b2 100644 --- a/lib/models/email.js +++ b/lib/models/email.js @@ -2,8 +2,8 @@ * Module Dependencies. */ -var Model = require('../asteroid').Model - , asteroid = require('../asteroid') +var Model = require('../loopback').Model + , loopback = require('../loopback') , mailer = require("nodemailer"); /** @@ -19,7 +19,7 @@ var properties = { }; /** - * Extends from the built in `asteroid.Model` type. + * Extends from the built in `loopback.Model` type. */ var Email = module.exports = Model.extend('email', properties); diff --git a/lib/models/model.js b/lib/models/model.js index cee50fa3f..32e51364c 100644 --- a/lib/models/model.js +++ b/lib/models/model.js @@ -6,7 +6,7 @@ var ModelBuilder = require('jugglingdb').ModelBuilder; var modeler = new ModelBuilder(); /** - * Define the built in asteroid.Model. + * Define the built in loopback.Model. */ var Model = module.exports = modeler.define('model'); diff --git a/lib/models/session.js b/lib/models/session.js index 6ce1ed966..7bf76250e 100644 --- a/lib/models/session.js +++ b/lib/models/session.js @@ -2,8 +2,8 @@ * Module Dependencies. */ -var Model = require('../asteroid').Model - , asteroid = require('../asteroid') +var Model = require('../loopback').Model + , loopback = require('../loopback') , crypto = require('crypto'); /** @@ -17,7 +17,7 @@ var properties = { }; /** - * Extends from the built in `asteroid.Model` type. + * Extends from the built in `loopback.Model` type. */ var Session = module.exports = Model.extend('session', properties); diff --git a/lib/models/user.js b/lib/models/user.js index f99f127f2..2865668dc 100644 --- a/lib/models/user.js +++ b/lib/models/user.js @@ -2,8 +2,8 @@ * Module Dependencies. */ -var Model = require('../asteroid').Model - , asteroid = require('../asteroid') +var Model = require('../loopback').Model + , loopback = require('../loopback') , path = require('path') , SALT_WORK_FACTOR = 10 , crypto = require('crypto') @@ -41,7 +41,7 @@ var properties = { /** - * Extends from the built in `asteroid.Model` type. + * Extends from the built in `loopback.Model` type. */ var User = module.exports = Model.extend('user', properties); @@ -114,7 +114,7 @@ User.login = function (credentials, fn) { User.logout = function (sid, fn) { var UserCtor = this; - var Session = UserCtor.settings.session || asteroid.Session; + var Session = UserCtor.settings.session || loopback.Session; Session.findById(sid, function (err, session) { if(err) { @@ -183,7 +183,7 @@ User.prototype.verify = function (options, fn) { // Email model - var Email = options.mailer || this.constructor.email || asteroid.Email; + var Email = options.mailer || this.constructor.email || loopback.Email; crypto.randomBytes(64, function(err, buf) { if(err) { @@ -208,7 +208,7 @@ User.prototype.verify = function (options, fn) { options.text = options.text.replace('{href}', options.verifyHref); - var template = asteroid.template(options.template); + var template = loopback.template(options.template); Email.send({ to: options.to || user.email, subject: options.subject || 'Thanks for Registering', @@ -257,7 +257,7 @@ User.setup = function () { this._password = bcrypt.hashSync(plain, salt); } - asteroid.remoteMethod( + loopback.remoteMethod( UserModel.login, { accepts: [ @@ -268,7 +268,7 @@ User.setup = function () { } ); - asteroid.remoteMethod( + loopback.remoteMethod( UserModel.logout, { accepts: [ @@ -278,7 +278,7 @@ User.setup = function () { } ); - asteroid.remoteMethod( + loopback.remoteMethod( UserModel.confirm, { accepts: [ diff --git a/package.json b/package.json index 5f83d169d..0e5e3e010 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { - "name": "asteroid", - "description": "asteroid", + "name": "loopback", + "description": "loopback", "version": "0.9.0", "scripts": { "test": "mocha -R spec" diff --git a/test/README.md b/test/README.md index 44d20f69e..ea5f0300e 100644 --- a/test/README.md +++ b/test/README.md @@ -2,10 +2,10 @@ - [app](#app) - [app.model(Model)](#app-appmodelmodel) - [app.models()](#app-appmodels) - - [asteroid](#asteroid) - - [asteroid.createDataSource(options)](#asteroid-asteroidcreatedatasourceoptions) - - [asteroid.remoteMethod(Model, fn, [options]);](#asteroid-asteroidremotemethodmodel-fn-options) - - [asteroid.memory([name])](#asteroid-asteroidmemoryname) + - [loopback](#loopback) + - [loopback.createDataSource(options)](#loopback-loopbackcreatedatasourceoptions) + - [loopback.remoteMethod(Model, fn, [options]);](#loopback-loopbackremotemethodmodel-fn-options) + - [loopback.memory([name])](#loopback-loopbackmemoryname) - [DataSource](#datasource) - [dataSource.createModel(name, properties, settings)](#datasource-datasourcecreatemodelname-properties-settings) - [dataSource.operations()](#datasource-datasourceoperations) @@ -56,7 +56,7 @@ Expose a `Model` to remote clients.. ```js -var memory = asteroid.createDataSource({connector: asteroid.Memory}); +var memory = loopback.createDataSource({connector: loopback.Memory}); var Color = memory.createModel('color', {name: String}); app.model(Color); assert.equal(app.models().length, 1); @@ -67,38 +67,38 @@ assert.equal(app.models().length, 1); Get the app's exposed models.. ```js -var Color = asteroid.createModel('color', {name: String}); +var Color = loopback.createModel('color', {name: String}); var models = app.models(); assert.equal(models.length, 1); assert.equal(models[0].modelName, 'color'); ``` - -# asteroid - -## asteroid.createDataSource(options) + +# loopback + +## loopback.createDataSource(options) Create a data source with a connector.. ```js -var dataSource = asteroid.createDataSource({ - connector: asteroid.Memory +var dataSource = loopback.createDataSource({ + connector: loopback.Memory }); assert(dataSource.connector()); ``` - -## asteroid.remoteMethod(Model, fn, [options]); + +## loopback.remoteMethod(Model, fn, [options]); Setup a remote method.. ```js -var Product = asteroid.createModel('product', {price: Number}); +var Product = loopback.createModel('product', {price: Number}); Product.stats = function(fn) { // ... } -asteroid.remoteMethod( +loopback.remoteMethod( Product.stats, { returns: {arg: 'stats', type: 'array'}, @@ -113,16 +113,16 @@ assert.equal(Product.stats.http.verb, 'get'); assert.equal(Product.stats.shared, true); ``` - -## asteroid.memory([name]) + +## loopback.memory([name]) Get an in-memory data source. Use one if it already exists.. ```js -var memory = asteroid.memory(); +var memory = loopback.memory(); assertValidDataSource(memory); -var m1 = asteroid.memory(); -var m2 = asteroid.memory('m2'); -var alsoM2 = asteroid.memory('m2'); +var m1 = loopback.memory(); +var m2 = loopback.memory('m2'); +var alsoM2 = loopback.memory('m2'); assert(m1 === memory); assert(m1 !== m2); @@ -257,7 +257,7 @@ assert.equal(point.lat, 6.777); Create as Model property. ```js -var Model = asteroid.createModel('geo-model', { +var Model = loopback.createModel('geo-model', { geo: {type: 'GeoPoint'} }); @@ -385,7 +385,7 @@ user.isValid(function (valid) { Attach a model to a [DataSource](#data-source). ```js -var MyModel = asteroid.createModel('my-model', {name: String}); +var MyModel = loopback.createModel('my-model', {name: String}); assert(MyModel.find === undefined, 'should not have data access methods'); @@ -706,7 +706,7 @@ Book.create({title: 'Into the Wild', author: 'Jon Krakauer'}, function(err, book ## Model.properties -Normalized properties passed in originally by asteroid.createModel().. +Normalized properties passed in originally by loopback.createModel().. ```js var props = { @@ -714,10 +714,10 @@ var props = { n: {type: 'Number'}, o: {type: 'String', min: 10, max: 100}, d: Date, - g: asteroid.GeoPoint + g: loopback.GeoPoint }; -var MyModel = asteroid.createModel('foo', props); +var MyModel = loopback.createModel('foo', props); Object.keys(MyModel.properties).forEach(function (key) { var p = MyModel.properties[key]; @@ -743,7 +743,7 @@ Object.keys(MyModel.properties).forEach(function (key) { Create a new model by extending an existing model.. ```js -var User = asteroid.Model.extend('test-user', { +var User = loopback.Model.extend('test-user', { email: String }); diff --git a/test/app.test.js b/test/app.test.js index 72387eb95..a27748c4d 100644 --- a/test/app.test.js +++ b/test/app.test.js @@ -2,7 +2,7 @@ describe('app', function() { describe('app.model(Model)', function() { it("Expose a `Model` to remote clients.", function() { - var memory = asteroid.createDataSource({connector: asteroid.Memory}); + var memory = loopback.createDataSource({connector: loopback.Memory}); var Color = memory.createModel('color', {name: String}); app.model(Color); assert.equal(app.models().length, 1); @@ -11,7 +11,7 @@ describe('app', function() { describe('app.models()', function() { it("Get the app's exposed models.", function() { - var Color = asteroid.createModel('color', {name: String}); + var Color = loopback.createModel('color', {name: String}); var models = app.models(); assert.equal(models.length, 1); diff --git a/test/asteroid.test.js b/test/asteroid.test.js deleted file mode 100644 index 3b596931e..000000000 --- a/test/asteroid.test.js +++ /dev/null @@ -1,48 +0,0 @@ -describe('asteroid', function() { - describe('asteroid.createDataSource(options)', function(){ - it('Create a data source with a connector.', function() { - var dataSource = asteroid.createDataSource({ - connector: asteroid.Memory - }); - assert(dataSource.connector()); - }); - }); - - describe('asteroid.remoteMethod(Model, fn, [options]);', function() { - it("Setup a remote method.", function() { - var Product = asteroid.createModel('product', {price: Number}); - - Product.stats = function(fn) { - // ... - } - - asteroid.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); - }); - }); - - describe('asteroid.memory([name])', function(){ - it('Get an in-memory data source. Use one if it already exists.', function() { - var memory = asteroid.memory(); - assertValidDataSource(memory); - var m1 = asteroid.memory(); - var m2 = asteroid.memory('m2'); - var alsoM2 = asteroid.memory('m2'); - - assert(m1 === memory); - assert(m1 !== m2); - assert(alsoM2 === m2); - }); - }); -}); \ No newline at end of file diff --git a/test/data-source.test.js b/test/data-source.test.js index 832a9d446..155f8888c 100644 --- a/test/data-source.test.js +++ b/test/data-source.test.js @@ -2,8 +2,8 @@ describe('DataSource', function() { var memory; beforeEach(function(){ - memory = asteroid.createDataSource({ - connector: asteroid.Memory + memory = loopback.createDataSource({ + connector: loopback.Memory }); assertValidDataSource(memory); diff --git a/test/geo-point.test.js b/test/geo-point.test.js index e794835e8..223df816d 100644 --- a/test/geo-point.test.js +++ b/test/geo-point.test.js @@ -40,7 +40,7 @@ describe('GeoPoint', function() { assert.equal(point.lat, 6.777); }); it('Create as Model property', function() { - var Model = asteroid.createModel('geo-model', { + var Model = loopback.createModel('geo-model', { geo: {type: 'GeoPoint'} }); diff --git a/test/model.test.js b/test/model.test.js index 2b08634ff..9e43c51fe 100644 --- a/test/model.test.js +++ b/test/model.test.js @@ -3,7 +3,7 @@ describe('Model', function() { var User, memory; beforeEach(function () { - memory = asteroid.createDataSource({connector: asteroid.Memory}); + memory = loopback.createDataSource({connector: loopback.Memory}); User = memory.createModel('user', { 'first': String, 'last': String, @@ -109,7 +109,7 @@ describe('Model', function() { describe('Model.attachTo(dataSource)', function() { it("Attach a model to a [DataSource](#data-source)", function() { - var MyModel = asteroid.createModel('my-model', {name: String}); + var MyModel = loopback.createModel('my-model', {name: String}); assert(MyModel.find === undefined, 'should not have data access methods'); @@ -254,7 +254,7 @@ describe('Model', function() { } } - asteroid.remoteMethod( + loopback.remoteMethod( User.login, { accepts: [ @@ -266,7 +266,7 @@ describe('Model', function() { } ); - app.use(asteroid.rest()); + app.use(loopback.rest()); app.model(User); }); @@ -433,16 +433,16 @@ describe('Model', function() { }); describe('Model.properties', function(){ - it('Normalized properties passed in originally by asteroid.createModel().', function() { + it('Normalized properties passed in originally by loopback.createModel().', function() { var props = { s: String, n: {type: 'Number'}, o: {type: 'String', min: 10, max: 100}, d: Date, - g: asteroid.GeoPoint + g: loopback.GeoPoint }; - var MyModel = asteroid.createModel('foo', props); + var MyModel = loopback.createModel('foo', props); Object.keys(MyModel.properties).forEach(function (key) { var p = MyModel.properties[key]; @@ -466,7 +466,7 @@ describe('Model', function() { describe('Model.extend()', function(){ it('Create a new model by extending an existing model.', function() { - var User = asteroid.Model.extend('test-user', { + var User = loopback.Model.extend('test-user', { email: String }); @@ -531,7 +531,7 @@ describe('Model', function() { // }, // ... // } - // var oracle = asteroid.createDataSource({ + // var oracle = loopback.createDataSource({ // connector: 'oracle', // host: '111.22.333.44', // database: 'MYDB', diff --git a/test/support.js b/test/support.js index 24014c524..1983d420c 100644 --- a/test/support.js +++ b/test/support.js @@ -1,17 +1,17 @@ /** - * asteroid test setup and support. + * loopback test setup and support. */ assert = require('assert'); -asteroid = require('../'); -memoryConnector = asteroid.Memory; -GeoPoint = asteroid.GeoPoint; +loopback = require('../'); +memoryConnector = loopback.Memory; +GeoPoint = loopback.GeoPoint; app = null; TaskEmitter = require('sl-task-emitter'); request = require('supertest'); beforeEach(function () { - app = asteroid(); + app = loopback(); }); assertValidDataSource = function (dataSource) { diff --git a/test/user.test.js b/test/user.test.js index 73efdcf6b..9ef24b429 100644 --- a/test/user.test.js +++ b/test/user.test.js @@ -1,9 +1,9 @@ -var User = asteroid.User.extend('user'); -var Session = asteroid.Session; +var User = loopback.User.extend('user'); +var Session = loopback.Session; var passport = require('passport'); -var userMemory = asteroid.createDataSource({ - connector: asteroid.Memory +var userMemory = loopback.createDataSource({ + connector: loopback.Memory }); @@ -17,9 +17,9 @@ describe('User', function(){ User.setMaxListeners(22); beforeEach(function (done) { - app.use(asteroid.cookieParser()); - app.use(asteroid.auth()); - app.use(asteroid.rest()); + app.use(loopback.cookieParser()); + app.use(loopback.auth()); + app.use(loopback.rest()); app.model(User); User.create({email: 'foo@bar.com', password: 'bar'}, done); From 1059a7b8632fe27efeeb4b0c3acb88f83124ed5e Mon Sep 17 00:00:00 2001 From: Raymond Feng Date: Tue, 16 Jul 2013 11:05:38 -0700 Subject: [PATCH 31/39] Add renamed files --- lib/loopback.js | 218 ++++++++++++++++++++++++++++++++++++++++++ test/loopback.test.js | 48 ++++++++++ 2 files changed, 266 insertions(+) create mode 100644 lib/loopback.js create mode 100644 test/loopback.test.js diff --git a/lib/loopback.js b/lib/loopback.js new file mode 100644 index 000000000..14b60a1af --- /dev/null +++ b/lib/loopback.js @@ -0,0 +1,218 @@ +/** + * Module dependencies. + */ + +var express = require('express') + , fs = require('fs') + , ejs = require('ejs') + , EventEmitter = require('events').EventEmitter + , path = require('path') + , proto = require('./application') + , utils = require('express/node_modules/connect').utils + , DataSource = require('jugglingdb').DataSource + , ModelBuilder = require('jugglingdb').ModelBuilder + , assert = require('assert') + , i8n = require('inflection'); + +/** + * Expose `createApplication()`. + */ + +var loopback = exports = module.exports = createApplication; + +/** + * Framework version. + */ + +loopback.version = require('../package.json').version; + +/** + * Expose mime. + */ + +loopback.mime = express.mime; + +/** + * Create an loopback application. + * + * @return {Function} + * @api public + */ + +function createApplication() { + var app = express(); + + utils.merge(app, proto); + + return app; +} + +/** + * Expose express.middleware as loopback.* + * for example `loopback.errorHandler` etc. + */ + +for (var key in express) { + Object.defineProperty( + loopback + , key + , Object.getOwnPropertyDescriptor(express, key)); +} + +/** + * Expose additional loopback middleware + * for example `loopback.configure` etc. + */ + +fs + .readdirSync(path.join(__dirname, 'middleware')) + .filter(function (file) { + return file.match(/\.js$/); + }) + .forEach(function (m) { + loopback[m.replace(/\.js$/, '')] = require('./middleware/' + m); + }); + +/** + * Error handler title + */ + +loopback.errorHandler.title = 'Loopback'; + +/** + * Create a data source with passing the provided options to the connector. + * + * @param {String} name (optional) + * @param {Object} options + * + * - connector - an loopback connector + * - other values - see the specified `connector` docs + */ + +loopback.createDataSource = function (name, options) { + var ds = new DataSource(name, options); + ds.createModel = function (name, properties, settings) { + var ModelCtor = loopback.createModel(name, properties, settings); + ModelCtor.attachTo(ds); + + var hasMany = ModelCtor.hasMany; + + if(hasMany) { + ModelCtor.hasMany = function (anotherClass, params) { + var origArgs = arguments; + var thisClass = this, thisClassName = this.modelName; + params = params || {}; + if (typeof anotherClass === 'string') { + params.as = anotherClass; + if (params.model) { + anotherClass = params.model; + } else { + var anotherClassName = i8n.singularize(anotherClass).toLowerCase(); + for(var name in this.schema.models) { + if (name.toLowerCase() === anotherClassName) { + anotherClass = this.schema.models[name]; + } + } + } + } + + var pluralized = i8n.pluralize(anotherClass.modelName); + var methodName = params.as || + i8n.camelize(pluralized, true); + var proxyMethodName = 'get' + i8n.titleize(pluralized, true); + + // create a proxy method + var fn = this.prototype[proxyMethodName] = function () { + // this[methodName] cannot be a shared method + // because it is defined inside + // a property getter... + + this[methodName].apply(thisClass, arguments); + }; + + fn.shared = true; + fn.http = {verb: 'get', path: '/' + methodName}; + fn.accepts = {arg: 'where', type: 'object'}; + hasMany.apply(this, arguments); + }; + } + + return ModelCtor; + } + return ds; +} + +/** + * Create a named vanilla JavaScript class constructor with an attached set of properties and options. + * + * @param {String} name - must be unique + * @param {Object} properties + * @param {Object} options (optional) + */ + +loopback.createModel = function (name, properties, options) { + return loopback.Model.extend(name, properties, options); +} + +/** + * Add a remote method to a model. + * @param {Function} fn + * @param {Object} options (optional) + */ + +loopback.remoteMethod = function (fn, options) { + fn.shared = true; + if(typeof options === 'object') { + Object.keys(options).forEach(function (key) { + fn[key] = options[key]; + }); + } + 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/test/loopback.test.js b/test/loopback.test.js new file mode 100644 index 000000000..0f52636ba --- /dev/null +++ b/test/loopback.test.js @@ -0,0 +1,48 @@ +describe('loopback', function() { + describe('loopback.createDataSource(options)', function(){ + it('Create a data source with a connector.', function() { + var dataSource = loopback.createDataSource({ + connector: loopback.Memory + }); + assert(dataSource.connector()); + }); + }); + + describe('loopback.remoteMethod(Model, fn, [options]);', function() { + it("Setup a remote method.", function() { + 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); + }); + }); + + describe('loopback.memory([name])', function(){ + it('Get an in-memory data source. Use one if it already exists.', function() { + 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); + }); + }); +}); \ No newline at end of file From 1970f12988e9c9eee7111de1fc942963b14fd7d3 Mon Sep 17 00:00:00 2001 From: Raymond Feng Date: Tue, 16 Jul 2013 12:03:41 -0700 Subject: [PATCH 32/39] Rename jugglingdb to loopback-data --- index.js | 2 +- lib/application.js | 4 ++-- lib/connectors/memory.js | 2 +- lib/loopback.js | 4 ++-- lib/models/model.js | 2 +- package.json | 2 +- 6 files changed, 8 insertions(+), 8 deletions(-) diff --git a/index.js b/index.js index e58027801..8594093ef 100644 --- a/index.js +++ b/index.js @@ -15,4 +15,4 @@ loopback.Memory = require('./lib/connectors/memory'); * Types */ -loopback.GeoPoint = require('jugglingdb/lib/geo').GeoPoint; \ No newline at end of file +loopback.GeoPoint = require('loopback-data/lib/geo').GeoPoint; \ No newline at end of file diff --git a/lib/application.js b/lib/application.js index 703e630ed..5e573ad21 100644 --- a/lib/application.js +++ b/lib/application.js @@ -2,8 +2,8 @@ * Module dependencies. */ -var DataSource = require('jugglingdb').DataSource - , ModelBuilder = require('jugglingdb').ModelBuilder +var DataSource = require('loopback-data').DataSource + , ModelBuilder = require('loopback-data').ModelBuilder , assert = require('assert') , RemoteObjects = require('sl-remoting'); diff --git a/lib/connectors/memory.js b/lib/connectors/memory.js index ce027f27d..3bfa4a75c 100644 --- a/lib/connectors/memory.js +++ b/lib/connectors/memory.js @@ -13,7 +13,7 @@ var Connector = require('./base-connector') , util = require('util') , inherits = util.inherits , assert = require('assert') - , JdbMemory = require('jugglingdb/lib/adapters/memory'); + , JdbMemory = require('loopback-data/lib/adapters/memory'); /** * Create a new `Memory` connector with the given `options`. diff --git a/lib/loopback.js b/lib/loopback.js index 14b60a1af..a5466db00 100644 --- a/lib/loopback.js +++ b/lib/loopback.js @@ -9,8 +9,8 @@ var express = require('express') , path = require('path') , proto = require('./application') , utils = require('express/node_modules/connect').utils - , DataSource = require('jugglingdb').DataSource - , ModelBuilder = require('jugglingdb').ModelBuilder + , DataSource = require('loopback-data').DataSource + , ModelBuilder = require('loopback-data').ModelBuilder , assert = require('assert') , i8n = require('inflection'); diff --git a/lib/models/model.js b/lib/models/model.js index 32e51364c..e512a4af6 100644 --- a/lib/models/model.js +++ b/lib/models/model.js @@ -2,7 +2,7 @@ * Module Dependencies. */ -var ModelBuilder = require('jugglingdb').ModelBuilder; +var ModelBuilder = require('loopback-data').ModelBuilder; var modeler = new ModelBuilder(); /** diff --git a/package.json b/package.json index 0e5e3e010..49d5f0de4 100644 --- a/package.json +++ b/package.json @@ -8,7 +8,7 @@ "dependencies": { "debug": "latest", "express": "~3.1.1", - "jugglingdb": "git+ssh://git@github.com:strongloop/jugglingdb.git", + "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", "bcrypt": "~0.7.6", From d128ed43869713dc1f57247f3cb25ae231442f8c Mon Sep 17 00:00:00 2001 From: Ritchie Martori Date: Tue, 16 Jul 2013 12:51:59 -0700 Subject: [PATCH 33/39] Remove remote option object --- lib/models/model.js | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/lib/models/model.js b/lib/models/model.js index e512a4af6..8a5bf5e0c 100644 --- a/lib/models/model.js +++ b/lib/models/model.js @@ -42,11 +42,11 @@ Model.setup = function () { } if(id && data) { - var model = new ModelCtor(data, {remote: true}); + var model = new ModelCtor(data); model.id = id; fn(null, model); } else if(data) { - fn(null, new ModelCtor(data, {remote: true})); + fn(null, new ModelCtor(data)); } else if(id) { ModelCtor.find(id, function (err, model) { if(err) { From cba94a23fca5c64daa76dea4fd2779e24a3204b5 Mon Sep 17 00:00:00 2001 From: Ritchie Martori Date: Tue, 16 Jul 2013 13:39:03 -0700 Subject: [PATCH 34/39] Add memory docs and test --- README.md | 122 +++++++++++++++++++++++++++++++++++++++----- test/memory.test.js | 35 +++++++++++++ 2 files changed, 144 insertions(+), 13 deletions(-) create mode 100644 test/memory.test.js diff --git a/README.md b/README.md index c8c3c7812..9f43c8d04 100644 --- a/README.md +++ b/README.md @@ -205,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. @@ -310,6 +356,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. @@ -361,13 +409,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'} } ); @@ -715,16 +768,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** @@ -736,6 +789,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. 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 From 253d42a8e8132431c01b0c6b51043dd57814ec14 Mon Sep 17 00:00:00 2001 From: Ritchie Martori Date: Tue, 16 Jul 2013 13:41:17 -0700 Subject: [PATCH 35/39] Cleanup test markdown --- test/README.md | 320 ++++++++++++++++++++++++++++++----------- test/geo-point.test.js | 6 +- test/loopback.test.js | 4 +- test/model.test.js | 14 +- test/user.test.js | 20 +-- 5 files changed, 259 insertions(+), 105 deletions(-) diff --git a/test/README.md b/test/README.md index ea5f0300e..e65a4fd25 100644 --- a/test/README.md +++ b/test/README.md @@ -2,10 +2,6 @@ - [app](#app) - [app.model(Model)](#app-appmodelmodel) - [app.models()](#app-appmodels) - - [loopback](#loopback) - - [loopback.createDataSource(options)](#loopback-loopbackcreatedatasourceoptions) - - [loopback.remoteMethod(Model, fn, [options]);](#loopback-loopbackremotemethodmodel-fn-options) - - [loopback.memory([name])](#loopback-loopbackmemoryname) - [DataSource](#datasource) - [dataSource.createModel(name, properties, settings)](#datasource-datasourcecreatemodelname-properties-settings) - [dataSource.operations()](#datasource-datasourceoperations) @@ -13,6 +9,11 @@ - [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) @@ -41,6 +42,7 @@ - [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) @@ -74,61 +76,6 @@ assert.equal(models.length, 1); assert.equal(models[0].modelName, 'color'); ``` - -# 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); -``` - # DataSource @@ -188,7 +135,6 @@ existsAndShared('save', true); existsAndShared('isNewRecord', false); existsAndShared('_adapter', false); existsAndShared('destroy', true); -existsAndShared('updateAttribute', true); existsAndShared('updateAttributes', true); existsAndShared('reload', true); @@ -224,7 +170,7 @@ assert.equal(GeoPoint.distanceBetween(here, there, {type: 'feet'}), 2568169.0388 ## GeoPoint() -Create from string.. +Create from string. ```js var point = new GeoPoint('1.234,5.678'); @@ -238,7 +184,7 @@ assert.equal(point3.lng, 1.333); assert.equal(point3.lat, 5.111); ``` -Serialize as string.. +Serialize as string. ```js var str = '1.234,5.678'; @@ -246,7 +192,7 @@ var point = new GeoPoint(str); assert.equal(point.toString(), str); ``` -Create from array.. +Create from array. ```js var point = new GeoPoint([5.555, 6.777]); @@ -270,6 +216,99 @@ 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 @@ -368,7 +407,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}); @@ -555,7 +594,7 @@ 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; @@ -580,7 +619,7 @@ 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; @@ -706,7 +745,7 @@ Book.create({title: 'Into the Wild', author: 'Jon Krakauer'}, function(err, book ## Model.properties -Normalized properties passed in originally by loopback.createModel().. +Normalized properties passed in originally by loopback.createModel(). ```js var props = { @@ -740,7 +779,7 @@ Object.keys(MyModel.properties).forEach(function (key) { ## Model.extend() -Create a new model by extending an existing model.. +Create a new model by extending an existing model. ```js var User = loopback.Model.extend('test-user', { @@ -776,9 +815,64 @@ 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.. +Login a user by providing credentials. ```js request(app) @@ -792,6 +886,7 @@ request(app) assert(session.uid); assert(session.id); + assert.equal((new Buffer(session.id, 'base64')).length, 64); done(); }); @@ -799,7 +894,21 @@ request(app) ## User.logout -Logout a user by providing the current session id.. +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); @@ -826,33 +935,78 @@ function logout(err, sid) { .post('/users/logout') .expect(200) .send({sid: sid}) - .end(verify(sid)); + .end(verify(sid, done)); } +``` -function verify(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); - }); - } +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.. +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 @@ -888,7 +1042,7 @@ request(app) .post('/users') .expect('Content-Type', /json/) .expect(200) - .send({data: {email: 'bar@bat.com', password: 'bar'}}) + .send({email: 'bar@bat.com', password: 'bar'}) .end(function(err, res){ if(err) return done(err); }); @@ -929,7 +1083,7 @@ request(app) .post('/users') .expect('Content-Type', /json/) .expect(302) - .send({data: {email: 'bar@bat.com', password: 'bar'}}) + .send({email: 'bar@bat.com', password: 'bar'}) .end(function(err, res){ if(err) return done(err); }); diff --git a/test/geo-point.test.js b/test/geo-point.test.js index 223df816d..469076f67 100644 --- a/test/geo-point.test.js +++ b/test/geo-point.test.js @@ -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/loopback.test.js b/test/loopback.test.js index 0f52636ba..21ec540eb 100644 --- a/test/loopback.test.js +++ b/test/loopback.test.js @@ -1,6 +1,6 @@ describe('loopback', function() { describe('loopback.createDataSource(options)', function(){ - it('Create a data source with a connector.', function() { + it('Create a data source with a connector', function() { var dataSource = loopback.createDataSource({ connector: loopback.Memory }); @@ -33,7 +33,7 @@ describe('loopback', function() { }); describe('loopback.memory([name])', function(){ - it('Get an in-memory data source. Use one if it already exists.', function() { + it('Get an in-memory data source. Use one if it already exists', function() { var memory = loopback.memory(); assertValidDataSource(memory); var m1 = loopback.memory(); diff --git a/test/model.test.js b/test/model.test.js index 9e43c51fe..30afa286a 100644 --- a/test/model.test.js +++ b/test/model.test.js @@ -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) { @@ -285,7 +285,7 @@ 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('create', function(ctx, user, next) { @@ -308,7 +308,7 @@ 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; @@ -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'}, @@ -465,7 +465,7 @@ describe('Model', function() { }); describe('Model.extend()', function(){ - it('Create a new model by extending an existing model.', function() { + it('Create a new model by extending an existing model', function() { var User = loopback.Model.extend('test-user', { email: String }); @@ -545,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); // // @@ -569,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/user.test.js b/test/user.test.js index 9ef24b429..cdc3194cc 100644 --- a/test/user.test.js +++ b/test/user.test.js @@ -32,7 +32,7 @@ describe('User', function(){ }); describe('User.create', function(){ - it('Create a new user.', function(done) { + it('Create a new user', function(done) { User.create({email: 'f@b.com'}, function (err, user) { assert(!err); assert(user.id); @@ -41,7 +41,7 @@ describe('User', function(){ }); }); - it('Requires a valid email.', function(done) { + it('Requires a valid email', function(done) { User.create({}, function (err) { assert(err); User.create({email: 'foo@'}, function (err) { @@ -51,7 +51,7 @@ describe('User', function(){ }); }); - it('Requires a unique email.', function(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!'); @@ -60,7 +60,7 @@ describe('User', function(){ }); }); - it('Requires a password to login with basic auth.', function(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'); @@ -70,14 +70,14 @@ describe('User', function(){ }); }); - it('Hashes the given password.', function() { + 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) { + it('Login a user by providing credentials', function(done) { request(app) .post('/users/login') .expect('Content-Type', /json/) @@ -97,7 +97,7 @@ describe('User', function(){ }); describe('User.logout', function() { - it('Logout a user by providing the current session id (using node).', function(done) { + it('Logout a user by providing the current session id (using node)', function(done) { login(logout); function login(fn) { @@ -109,7 +109,7 @@ describe('User', function(){ } }); - it('Logout a user by providing the current session id (over rest).', function(done) { + it('Logout a user by providing the current session id (over rest)', function(done) { login(logout); function login(fn) { @@ -138,7 +138,7 @@ describe('User', function(){ } }); - it('Logout a user using the instance method.', function(done) { + it('Logout a user using the instance method', function(done) { login(logout); function login(fn) { @@ -167,7 +167,7 @@ describe('User', function(){ }); describe('user.hasPassword(plain, fn)', function(){ - it('Determine if the password matches the stored password.', function(done) { + 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'); From 0b5e0d4252252126194171a1e83c58f43c5c14e1 Mon Sep 17 00:00:00 2001 From: Ritchie Martori Date: Tue, 16 Jul 2013 13:46:33 -0700 Subject: [PATCH 36/39] More cleanup for test/README.md --- test/README.md | 40 ++++++++++++++++++++-------------------- test/app.test.js | 4 ++-- test/data-source.test.js | 4 ++-- test/geo-point.test.js | 4 ++-- test/loopback.test.js | 2 +- test/model.test.js | 30 +++++++++++++++--------------- 6 files changed, 42 insertions(+), 42 deletions(-) diff --git a/test/README.md b/test/README.md index e65a4fd25..85df4d759 100644 --- a/test/README.md +++ b/test/README.md @@ -55,7 +55,7 @@ # app ## app.model(Model) -Expose a `Model` to remote clients.. +Expose a `Model` to remote clients. ```js var memory = loopback.createDataSource({connector: loopback.Memory}); @@ -66,7 +66,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}); @@ -80,7 +80,7 @@ assert.equal(models[0].modelName, 'color'); # 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}); @@ -109,7 +109,7 @@ assert.isFunc(Color.prototype, 'reload'); ## dataSource.operations() -List the enabled and disabled operations.. +List the enabled and disabled operations. ```js // assert the defaults @@ -148,7 +148,7 @@ function existsAndShared(name, isRemoteEnabled) { # GeoPoint ## geoPoint.distanceTo(geoPoint, options) -Get the distance to another `GeoPoint`.. +Get the distance to another `GeoPoint`. ```js var here = new GeoPoint({lat: 10, lng: 10}); @@ -159,7 +159,7 @@ assert.equal(here.distanceTo(there, {type: 'meters'}), 782777.923052584); ## GeoPoint.distanceBetween(a, b, options) -Get the distance between two points.. +Get the distance between two points. ```js var here = new GeoPoint({lat: 10, lng: 10}); @@ -231,7 +231,7 @@ assert(dataSource.connector()); ## loopback.remoteMethod(Model, fn, [options]); -Setup a remote method.. +Setup a remote method. ```js var Product = loopback.createModel('product', {price: Number}); @@ -313,7 +313,7 @@ function count() { # 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'); @@ -325,7 +325,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'}}); @@ -336,7 +336,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']}); @@ -347,7 +347,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']}); @@ -364,7 +364,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}); @@ -377,7 +377,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'}); @@ -397,7 +397,7 @@ joe.save(function () { ## myModel.isValid() -Validate the model instance.. +Validate the model instance. ```js User.validatesNumericalityOf('age', {int: true}); @@ -435,7 +435,7 @@ assert(typeof MyModel.find === 'function', 'should have data access methods afte ## 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) { @@ -446,7 +446,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'}); @@ -460,7 +460,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) { @@ -499,7 +499,7 @@ 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) { @@ -542,7 +542,7 @@ Delete all Model instances from data source. ## Model.findById(id, callback) -Find an instance by id.. +Find an instance by id. ```js User.create({first: 'michael', last: 'jordan', id: 23}, function () { @@ -716,7 +716,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}); 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 155f8888c..f39866a2a 100644 --- a/test/data-source.test.js +++ b/test/data-source.test.js @@ -10,7 +10,7 @@ describe('DataSource', function() { }); 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'); @@ -37,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 diff --git a/test/geo-point.test.js b/test/geo-point.test.js index 469076f67..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}); diff --git a/test/loopback.test.js b/test/loopback.test.js index 21ec540eb..2bedb14b9 100644 --- a/test/loopback.test.js +++ b/test/loopback.test.js @@ -9,7 +9,7 @@ describe('loopback', function() { }); describe('loopback.remoteMethod(Model, fn, [options]);', function() { - it("Setup a remote method.", function() { + it("Setup a remote method", function() { var Product = loopback.createModel('product', {price: Number}); Product.stats = function(fn) { diff --git a/test/model.test.js b/test/model.test.js index 30afa286a..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(); @@ -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); @@ -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}); @@ -508,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()); From 6b1ac1ab79d49eb84530becad7160d113759f7c9 Mon Sep 17 00:00:00 2001 From: Ritchie Date: Wed, 17 Jul 2013 12:18:17 -0700 Subject: [PATCH 37/39] Add fields documentation --- README.md | 24 ++++++++++++++++++------ 1 file changed, 18 insertions(+), 6 deletions(-) diff --git a/README.md b/README.md index 9f43c8d04..ac9e75823 100644 --- a/README.md +++ b/README.md @@ -284,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. @@ -319,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) { From 7c7667151ac12a1c2758522157b0d8c3e90eb8db Mon Sep 17 00:00:00 2001 From: Ritchie Date: Wed, 17 Jul 2013 14:29:43 -0700 Subject: [PATCH 38/39] Manually merge rest adapter --- lib/middleware/rest.js | 14 +++++++++++--- 1 file changed, 11 insertions(+), 3 deletions(-) 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); } } } - From f7791fc36635cae7b9dc341db2bd22030354bfd8 Mon Sep 17 00:00:00 2001 From: Ritchie Date: Wed, 17 Jul 2013 14:30:38 -0700 Subject: [PATCH 39/39] Manually merge application --- lib/application.js | 77 +++++++++------------------------------------- 1 file changed, 14 insertions(+), 63 deletions(-) diff --git a/lib/application.js b/lib/application.js index 4ed7b9f9f..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. */ @@ -59,7 +44,6 @@ app.disuse = function (route) { */ app._models = []; -app._services = []; /** * Expose a model. @@ -68,8 +52,6 @@ app._services = []; */ app.model = function (Model) { - var remotes = this.remotes(); - this._models.push(Model); Model.shared = true; Model.app = this; @@ -85,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; +app.remoteObjects = function () { + var result = {}; + var models = this.models(); - service.app = this; - - // 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; } /** @@ -115,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