(function (angular) {
    'use strict';

    angular
        .module('movieClub.auth')
        .factory('authApi', authApi);

    function authApi($firebaseAuth, usersApi, firebaseRef) {
        var factory = {
                login: login,
                logout: logout,
                onAuth: onAuth,
                register: register
            },
            authRef = $firebaseAuth(firebaseRef);
        return factory;

        function login(email, password) {
            var credentials = {
                email: email,
                password: password
            };
            return authRef.$authWithPassword(credentials);
        }

        function logout() {
            authRef.$unauth();
        }

        function onAuth(func) {
            return authRef.$onAuth(func);
        }

        function register(username, email, password) {
            var credentials = {
                email: email,
                password: password
            };

            return authRef.$createUser(credentials)
                .then(function () {
                    return login(email, password)
                        .then(function (auth) {
                            var user = usersApi.getById(auth.uid);
                            user.username = username;
                            user.$save();
                            return user.$loaded();
                        });
                });
        }
    }

}(window.angular));

(function (angular) {
    'use strict';

    angular
        .module('movieClub.auth')
        .factory('authApi', authApi);

    function authApi($firebaseAuth, usersApi, firebaseRef) {
        var factory = {
                login: login,
                logout: logout,
                onAuth: onAuth,
                register: register
            },
            authRef = $firebaseAuth(firebaseRef);
        return factory;

        function login(email, password) {
            return authRef.$authWithPassword({email: email, password: password});
        }

        function logout() {
            authRef.$unauth();
        }

        function register(username, email, password) {
            return authRef.$createUser({email: email, password: password})
                .then(_.partial(login, email, password))
                .then(_.partialRight(addUsername, username));
        }

        function onAuth(func) {
            return authRef.$onAuth(func);
        }

        function addUsername(auth, username) {
            var user = usersApi.getById(auth.uid);
            user.username = username;
            user.$save();
            return user.$loaded();
        }
    }

}(window.angular));

Use promise chaining during registration
Use promise chaining during registration
