Add user.logout() sugar method and update logout docs

This commit is contained in:
Ritchie Martori 2013-07-12 16:10:15 -07:00
parent a09b527000
commit 16617a3737
3 changed files with 66 additions and 15 deletions

View File

@ -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`.

View File

@ -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.
*/

View File

@ -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(){