Fork me on GitHub

$auth 0.3.0

An extension for the scope which comes in a seperate package called angular-meteor-auth and provides us with authentication related methods and properties. For syntactic sugar, you may also use the $auth service, e.g. $auth.awaitUser() which is equivalent to $rootScope.$awaitUser().

Installation

You will need to add the package to your project and add it's module as a dependency to your AngularJS app:

meteor add accounts-base
meteor add angular-meteor-auth
angular.module('myApp', [
  'angular-meteor',
  'angular-meteor.auth'
]);

Note that accounts-basepackage needs to be installed in order for this module to work, otherwise an error will be thrown.

Properties

The following properties will be added to the $scope / view model during initialization and will be updated reactively:

  • currentUser - The current user logged in. Reactivated by Accounts.user.
  • currentUserId - The current user's id. Reactivated by Accounts.userId.
  • isLoggingIn - Inticates whenever we try to log in. Reactivated by Accounts.loggingIn.

Example

<div ng-show="vm.isLoggingIn">Logging in...</div>
<div ng-show="vm.currentUser">I am visible only for logged in users!</div>
<div ng-hide="vm.currentUser">I am visible only for guests!</div>

Methods

As an addition to the methods below, methods from v0.2.0 are also available.

$awaitUser

Waits for the user to finish the login process. Our waiting can be stopped manually or automatically once our $scope has been destroyed.


Arguments

Name Type Details Required
validationFn Function A validation function which will be invoked with the user once the login process has been succedded. If the returned value is true then the returned promised will be resolved. Else, if the returned value is 'false' the returned promise will be rejected with 'FORBIDDEN'. Else, if the returned value is a string or an error they will be rejected by the promise as is. No

Return value

Returns a promise which will be fulfilled accordingly. If the login process has been failed the promise will be rejected with 'AUTH_REQUIRED'. Else, the validation function will be invoked with the logged in user, and if the user is valid the promise will be resolved with the logged in user. Also, a 'stop' method is defined on the promise in case we would like to stop our waiting.


Examples

Running a piece of code only once logged in:

angular.module('myApp').directive('myComponent', function() {
  return {
    link: function($scope) {
      $scope.awaitUser().then(() => {
        let currentUser = $scope.currentUser;
      });
    }
  };
});

Usage with $auth service:

$stateProvider
  .state({
      template: '<my-component></my-component>',
      resolve: {
        user: ($auth) => {
          return $auth.awaitUser();
        }
      }
  });

Usage with validation method:

$stateProvider
  .state({
    template: '<my-component></my-component>',
    resolve: {
      user: ($auth) => {
        return $auth.awaitUser((user) => {
          if (user.firstName === 'Uri') {
            return true;
          }
          else {
            return 'You are not Uri!';
          }
        }
      }
    }
  });

Waiting for a regular user:

myModule.controller('MyCtrl', ['$scope', '$reactive', function($scope, $reactive) {
  $reactive(this).attach($scope);

  this.$awaitUser().then((user) => {
    console.log('The user has logged in successfully!', user);
  }, (err) => {
    console.log('There was an error in login process', err);
  });
}]);

Waiting for an admin:

myModule.controller('MyCtrl', ['$scope', '$reactive', function($scope, $reactive) {
  $reactive(this).attach($scope);

  this.$awaitUser((user) => {
    return user.role === "Admin";
  }).then((admin) => {
    console.log('An admin has logged in successfully!', admin);
  }, (err) => {
    if (err === "AUTH_REQUIRED")
      console.log('There was an error in login process');
    else if (err === "FORBIDDEN")
      console.log('A user has logged in who isn\'t an admin');
  });
}]);

$auth 0.2.0

$auth service is a part of angular-meteor-auth package, and it located inside angular-meteor.auth AngularJS module.

This service provides the functionality for authentication for your app.

$auth wraps Meteor's API for ease of use with AngularJS applications, and also provides the ability to access Meteor's Accounts package from the UI.

In order to use this service, you will need to add the package to your project and add it's module as a dependency to your AngularJS app:

meteor add angular-meteor-auth
angular.module('myApp', [
  'angular-meteor',
  'angular-meteor.auth'
]);

API Reference

waitForUser()

waitForUser is a method of $auth which waits for any user to log in.

It a wrapper for Meteor.loggingIn method, but it's return value is a promise which can be only resolved, when any user is done with the login process.

It is useful when you want to run part of your code only after the user logs in.

Usage example

angular.module('myApp').directive('myComponent', function() {
  return {
    link: function($auth) {
      $auth.waitForUser().then(() => {
        // Login is done!
      });
    }
  };
});

requireUser()

requireUser provides a useful functionality for performing a one-time login check, with a promise.

It's very useful for angular-ui-router's resolve functionality.

It's return value is a promise, which resolves when the login process is done, and the Meteor.user() is valid and not null.

Usage example with angular-ui-router:

$stateProvider
  .state({
    template: '<my-component></my-component>',
    resolve: {
    user: ($auth) => {
      return $auth.requireUser();
    }
  }
});

requireValidUser(validationMethod)

requireValidUser uses requireUser method, but adding another custom check that provided by the user.

It's return value is a promise, which resolves if the user is logged in and the custom validation method returns true.

If the user validation message returns anything other than true, the promise will rejected and the promise failure argument will be the return value of the validation message.

Usage example with angular-ui-router:

In this example, we will allow only logged in users, with firstName equals to Uri.

$stateProvider
  .state({
    template: '<my-component></my-component>',
    resolve: {
    user: ($auth) => {
      return $auth.requireValidUser((user) => {
        if (user.firstName === 'Uri') {
          return true;
        }
        else {
          return 'You are not Uri!';
        }
      });
    }
  }
});

$auth service also provides two useful properties that are useful in views:

currentUser

$auth.currentUser is a property of the $auth service, which contain the current logged in user in every time.

It automatically changes when the user logs in or logs out, and it can be used from the view or the AngularJS controller/components.

It's very useful for hiding / showing parts of the view depending on the login status.

Usage example inside a view

<div ng-show="$auth.currentUser">I am visible only for logged in users!</div>
<div ng-hide="$auth.currentUser">I am visible only for guests!</div>

Usage example inside a component

angular.module('myApp').directive('myComponent', function() {
  return {
    link: function($auth) {
      $auth.waitForUser().then(() => {
        let currentUser = $auth.currentUser;
      });
    }
  };
});

loggingIn

$auth.loggingIn is a property of the $auth service, which contain the current login status.

It's a wrapper for Meteor.loggingIn method.

It's value is true if a login method (such as Meteor.loginWithPassword, Meteor.loginWithFacebook, or Accounts.createUser) is currently in progress.

You can use this property in your view in order to display a spinner or a "Logging you in..." message!

Usage example inside a view

<div ng-show="$auth.loggingIn">Logging in...</div>
<div ng-show="$auth.currentUser">I am visible only for logged in users!</div>
<div ng-hide="$auth.currentUser">I am visible only for guests!</div>