This API is deprecated since version 1.3.0 and no longer available since version 1.3.1

Accounts, users and authentication

Methods and $rootScope variables to support Meteor.user and Meteor's accounts system

This module has moved into a separate package here. Please update your existing code by adding that package or using regular Meteor.user and Meteor's accounts system functions.


Usage

$rootScope.currentUser

$rootScope.loggingIn

$meteor.waitForUser()

$meteor.requireUser()

$meteor.requireValidUser(validatorFn)

$meteor.loginWithPassword(user, password)

$meteor.createUser(options)

$meteor.changePassword(oldPassword, newPassword)

$meteor.forgotPassword(options)

$meteor.resetPassword(token, newPassword)

$meteor.verifyEmail(token)

$meteor.logout()

$meteor.logoutOtherClients()

$meteor.loginWithMeteorDeveloperAccount(options)
$meteor.loginWithFacebook(options)
$meteor.loginWithGithub(options)
$meteor.loginWithGoogle(options)
$meteor.loginWithMeetup(options)
$meteor.loginWithTwitter(options)
$meteor.loginWithWeibo(options)

Variables

$rootScope

Adding to $rootScope support for Meteor's currentUser and loggingIn

  • $rootScope.currentUser — The current logged in user and it's data. it is null if the user is not logged in. A reactive data source.
  • $rootScope.loggingIn — True if a login method (such as Meteor.loginWithPassword, Meteor.loginWithFacebook, or Accounts.createUser) is currently in progress. A reactive data source. Can be use to display animation while user is logging in.

Example

// In templates
ng-if="$root.currentUser"

// In controllers
if ($rootScope.currentUser)

Methods

Those methods are provided by the accounts-password package. See the Meteor's Passwords section

waitForUser();

Returns a promise fulfilled with the currentUser when the user subscription is ready.

This is useful when you want to grab the current user before the route is rendered.

If there is no logged in user, it will return null.

See the “Authentication with Routers” section of our tutorial for more information and a full example.


Example

// In route config ('ui-router' in the example, but works with 'ngRoute' the same way)
$stateProvider
  .state('home', {
    url: '/',
    templateUrl: 'client/views/home.ng.html',
    controller: 'HomeController'
    resolve: {
      "currentUser": ["$meteor", function($meteor){
        return $meteor.waitForUser();
      }]
    }
});


requireUser();

Resolves the promise successfully if a user is authenticated and rejects otherwise.
This is useful in cases where you want to require a route to have an authenticated user.
You can catch the rejected promise and redirect the unauthenticated user to a different page, such as the login page.
See the “Authentication with Routers” section of our tutorial for more information and a full example.


Example

// In route config ('ui-router' in the example, but works with 'ngRoute' the same way)
$stateProvider
  .state('home', {
    url: '/',
    templateUrl: 'client/views/home.ng.html',
    controller: 'HomeController'
    resolve: {
      "currentUser": ["$meteor", function($meteor){
        return $meteor.requireUser();
      }]
    }
  });

app.run(["$rootScope", "$state", function($rootScope, $state) {
  $rootScope.$on("$stateChangeError", function(event, toState, toParams, fromState, fromParams, error) {
    // We can catch the error thrown when the $meteor.requireUser() promise is rejected
    // and redirect the user back to the login page
    if (error === "AUTH_REQUIRED") {
        // It is better to use $state instead of $location. See Issue #283.
        $state.go('logIn');
    }
  });
}]);


requireValidUser(validatorFn);

Resolves the promise successfully if a user is authenticated and the validatorFn returns true; rejects otherwise.
This is useful in cases where you want to require a route to have an authenticated user and do extra validation like the user's role or group.
You can catch the rejected promise and redirect the unauthenticated user to a different page, such as the login page.
See the “Authentication with Routers” section of our tutorial for more information and a full example.
The mandatory validator function will be called with the authenticated user as the single param and it's expected to return true in order to resolve. If it returns a string, the promise will be rejected using said string as the reason. Any other return (false, null, undefined) will be rejected with the default "FORBIDDEN" reason.


Example

// In route config ('ui-router' in the example, but works with 'ngRoute' the same way)
$stateProvider
  .state('home', {
    url: '/',
    templateUrl: 'client/views/home.ng.html',
    controller: 'HomeController'
    resolve: {
      "currentUser": ["$meteor", function($meteor){
        return $meteor.requireUser();
      }]
    }
   })
   .state('admin', {
     url: '/admin',
     templateUrl: 'client/views/admin.ng.html',
     controller: 'AdminController'
     resolve: {
       "currentUser": ["$meteor", function($meteor){
         return $meteor.requireValidUser(function(user) {
           return user.username==='admin';
         });
       }]
     }
   })
   .state('admin2', {
     url: '/admin2',
     templateUrl: 'client/views/admin2.ng.html',
     controller: 'Admin2Controller'
     resolve: {
       "currentUser": ["$meteor", function($meteor){
         return $meteor.requireValidUser(function(user) {
           if (user.username==='admin2') {
             return true;
           }

           return 'UNAUTHORIZED';
         });
       }]
     }
  });

app.run(["$rootScope", "$state", function($rootScope, $state) {
  $rootScope.$on("$stateChangeError", function(event, toState, toParams, fromState, fromParams, error) {
    // We can catch the error thrown when the $meteor.requireUser() promise is rejected
    // or the custom error, and redirect the user back to the login page
    switch(error) {
      case "AUTH_REQUIRED":
        $state.go('logIn');
        break;
      case "FORBIDDEN":
        $state.go('forbidden');
        break;
      case "UNAUTHORIZED":
        $state.go('unauthorized');
        break;
      default:
        $state.go('internal-client-error');
    }
  });
}]);


loginWithPassword( :user, :password );

Log the user in with a password.


Parameters

Param Type Details Required
user Object / String

Either a string interpreted as a username or an email; or an object with a single key: email, username or id.

Yes
password String

The user's password.

Yes

#### Example $meteor.loginWithPassword(user, password).then(function(){ console.log('Login success'); }, function(err){ console.log('Login error - ', err); }); }

createUser( :options );

Create a new user. More information.

Options

Param Type Details Required
username String

A unique name for this user.

must provide username or email
email String

The user's email address.

must provide username or email
password String

The user's password. This is not sent in plain text over the wire.

Yes
profile Object

The user's profile, typically including the name field.

No

#### Example $meteor.createUser({ username:'moma', email:[email protected]', password: [email protected]', profile: {expertize: 'Developer'} }).then(function(){ console.log('Login success'); }, function(err){ console.log('Login error - ', err); }); }

changePassword( :oldPassword, :newPassword );

Change the current user's password. Must be logged in.

Options

Param Type Details Required
oldPassword String

The user's current password. This is not sent in plain text over the wire.

Yes
newPassword String

A new password for the user. This is not sent in plain text over the wire.

Yes

#### Example $meteor.changePassword('old', 'new232f3').then(function(){ console.log('Change password success'); }, function(err){ console.log('Error changing password - ', err); }); }

forgotPassword( :options );

Request a forgot password email.

Options

Param Type Details Required
email String

The email address to send a password reset link.

Yes

#### Example $meteor.forgotPassword({email: [email protected]'}).then(function(){ console.log('Success sending forgot password email'); }, function(err){ console.log('Error sending forgot password email - ', err); }); }

resetPassword( :token, :newPassword );

Reset the password for a user using a token received in email. Logs the user in afterwards.

Parameters

Param Type Details Required
token String

The token retrieved from the reset password URL.

Yes
newPassword String

A new password for the user. This is not sent in plain text over the wire.

Yes

#### Example $meteor.resetPassword($stateParams.token, 'new232f3').then(function(){ console.log('Reset password success'); }, function(err){ console.log('Error resetting password - ', err); }); }

verifyEmail( :token );

Marks the user's email address as verified. Logs the user in afterwards.

Parameters

Param Type Details Required
token String

The token retrieved from the reset password URL.

Yes

#### Example $meteor.verifyEmail($stateParams.token).then(function(){ console.log('Success verifying password '); }, function(err){ console.log('Error verifying password - ', err); }); }

loginWith'ExternalService'( :options );

Log the user in using an external service. Available functions are:
  • $meteor.loginWithFacebook
  • $meteor.loginWithTwitter
  • $meteor.loginWithGoogle
  • $meteor.loginWithGithub
  • $meteor.loginWithMeetup
  • $meteor.loginWithWeibo

options

Param Type Details Required
requestPermissions Array of Strings

A list of permissions to request from the user.

No
requestOfflineToken Boolean

If true, asks the user for permission to act on their behalf when offline. This stores an additional offline token in the services field of the user document. Currently only supported with Google.

No
forceApprovalPrompt Boolean

If true, forces the user to approve the app's permissions, even if previously approved. Currently only supported with Google.

No
userEmail String

An email address that the external service will use to pre-fill the login prompt. Currently only supported with Meteor developer accounts.

No
loginStyle String

Login style ("popup" or "redirect", defaults to the login service configuration). The "popup" style opens the login page in a separate popup window, which is generally preferred because the Meteor application doesn't need to be reloaded. The "redirect" style redirects the Meteor application's window to the login page, and the login service provider redirects back to the Meteor application which is then reloaded. The "redirect" style can be used in situations where a popup window can't be opened, such as in a mobile UIWebView. The "redirect" style however relies on session storage which isn't available in Safari private mode, so the "popup" style will be forced if session storage can't be used.

No

#### Example $meteor.loginWithFacebook({requestPermissions: ['email']}).then(function(){ console.log('Login success'); }, function(err){ console.log('Login error - ', err); }); }

logout();

Log the user out.
#### Returns
promise

Resolves with no arguments on success, or reject with a Error argument on failure.

Example

$meteor.logout().then(function(){
    console.log('Logout success');
  }, function(err){
    console.log('logout error - ', err);
  });
}


logoutOtherClients();

Log out other clients logged in as the current user, but does not log out the client that calls this function.
For example, when called in a user's browser, connections in that browser remain logged in, but any other browsers or DDP clients logged in as that user will be logged out.


Returns

promise

Resolves with no arguments on success, or reject with a Error argument on failure.

Example

$meteor.logoutOtherClients().then(function(){
    console.log('Logout success');
  }, function(err){
    console.log('logout error - ', err);
  });
}