diff --git a/README.md b/README.md index f67d3780..4d560d34 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 9957c6b2..1d720a52 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 03aa348e..dee770e4 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)); - } - - 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); - }); - } + .end(verify(sid, done)); } }); + + it('Logout a user using the instance method.', function(done) { + login(logout); + + function login(fn) { + User.login({email: 'foo@bar.com', password: 'bar'}, fn); + } + + function logout(err, session) { + User.findOne({email: 'foo@bar.com'}, function (err, user) { + user.logout(verify(session.id, done)); + }); + } + }); + + function verify(sid, done) { + assert(sid); + + return function (err) { + if(err) return done(err); + + Session.findById(sid, function (err, session) { + assert(!session, 'session should not exist after logging out'); + done(err); + }); + } + } }); describe('user.hasPassword(plain, fn)', function(){