@ngdoc function
@name isLoggedInAsync
@methodOf auth.service:Auth
@description
Waits for currentUser to resolve before checking if user is logged in

@param {Function} cb A Callback
192091
function isLoggedInAsync(cb) {
      if (currentUser.hasOwnProperty('$promise')) {
        currentUser.$promise.then(function () {
          cb(true);
        }).catch(function () {
          cb(false);
        });
      } else if (currentUser.hasOwnProperty('role')) {
        cb(true);
      } else {
        cb(false);
      }
    }
1069412
function saveUser(user, req, cb) {
  user.markModified('attributes');
  user.markModified('password');
  if (user.extensionattributes && user.extensionattributes.login && user.extensionattributes.login.flagged) {
    user.extensionattributes.login.flagged = false;
    user.extensionattributes.login.attempts = 0;
    user.extensionattributes.login.timestamp = moment().subtract(loginExtSettings.timeout.attempt_interval.time, loginExtSettings.timeout.attempt_interval.unit);
    user.markModified('extensionattributes');
  }
  user.save(function (err, usr) {
    if (err) {
      cb(err, null);
    }
    cb(null, usr, req);
  });
}
304322
def _check_cb(cb_):
    '''
    
    '''
    if cb_ is not None:
        if hasattr(cb_, '__call__'):
            return cb_
        else:
            log.error('log_callback is not callable, ignoring')
    return lambda x: x
234850
function(cb) {
      //console.log('tx running for ' + scope);
      // me.not_ready_ = true;
      // transaction should be active now
      var tx = me.mu_tx_.getTx();
      /**
       * @param {*} result result.
       * @param {boolean=} opt_is_error true if request has error.
       */
      var resultCallback2 = function(result, opt_is_error) {
        me.s_request_tx = tx; // so that we can abort it.
        if (opt_is_error) {
          goog.log.finer(me.logger, rq_label + ' ERROR');
          df.errback(result);
        } else {
          goog.log.finer(me.logger, rq_label + ' SUCCESS');
          df.callback(result);
        }
        me.s_request_tx = null;
      };
      me.r_no_++;
      rq_label = me.getLabel() + 'R' + me.r_no_;
      goog.log.finer(me.logger, rq_label + ' BEGIN');
      callback(tx, rq_label, resultCallback2);
      goog.log.finer(me.logger, rq_label + ' END');
      callback = null; // we don't call again.
    }
237918
public function whenLogged($callback)
    {
        $this->loggedInCallbacks[] = $callback;

        if ($this->isLogged()) {
            fire_callbacks($this->loggedInCallbacks, $this);
        }
    }
253850
function logIn(config, location, options) {
    return Q.Promise(function (resolve, reject) {
      if (isLoggedIn) {
        setLocation(location, options).then(resolve);
        return;
      }
      api.init(config.username, config.password, locWrap(location), config.provider, function (err) {
        if (err) {
          return reject(err);
        }
        isLoggedIn = true;
        resolve();
      });
    });
  }
1347648
function deleteAccount (name, cb) {
  assert(this instanceof CouchLogin)
  var u = '/_users/org.couchdb.user:' + name
  this.get(u, thenPut.bind(this))

  function thenPut (er, res, data) {
    if (er || res.statusCode !== 200) {
      return cb(er, res, data)
    }

    // user accts can't be just DELETE'd by non-admins
    // so we take the existing doc and just slap a _deleted
    // flag on it to fake it.  Works the same either way
    // in couch.
    data._deleted = true
    this.put(u + '?rev=' + data._rev, data, cb)
  }
}
43471
function(cb) {
        var timeout;
        this.chain(function(next) {
            function evaluate() {
                var ccb = cb.bind(api);
                var result = ccb();
                if (result) {
                    clearInterval(poll);
                    if (timeout !== undefined) clearTimeout(timeout);
                    next();
                }
            }
            var api = this;
            var poll = setInterval(evaluate, api._untilInterval || 30);
            // to set a timeout for condition to be met, set the _untilTimeout property to ms value
            if (api.untilTimeout) {
                timeout = setTimeout(function() {
                    if (poll !== undefined) {
                        clearInterval(poll);
                        // to catch timeout of until conditions, set onUntilTimeout handler
                        if (api.onUntilTimeout) api.onUntilTimeout(next);
                        // otherwise execution flow simply continues as if condition was met
                        else next();
                    }
                }, api.untilTimeout);
            }
        });
        return this;
    }
1239575
function connect(obj, cb) {
    if (obj.db) {
        return cb();
    }
    if (obj.pending) {
        return setImmediate(function () {
            connect(obj, cb);
        });
    }
    obj.pending = true;

    var url = constructMongoLink(obj.config.name, obj.config.prefix, obj.config.servers, obj.config.URLParam, obj.config.credentials);
    if (!url) {
        return cb(generateError(190));
    }

    mongoSkin.connect(url, obj.config.extraParam, function (err, db) {
        if (err) {
            obj.pending = false;
            return cb(err);
        } else {
            db.on('timeout', function () {
                console.log("Connection To Mongo has timed out!");
                obj.flushDb();
            });
            db.on('close', function () {
                console.log("Connection To Mongo has been closed!");
                obj.flushDb();
            });
            if (obj.db)
                obj.db.close();

            obj.db = db;
            obj.pending = false;
            return cb();
        }
    });

    /**
     *constructMongoLink: is a function that takes the below param and return the URL need to by mongoskin.connect
     *
     * @param dbName
     * @param prefix
     * @param servers
     * @param params
     * @param credentials
     * @returns {*}
     */
    function constructMongoLink(dbName, prefix, servers, params, credentials) {
        if (dbName && Array.isArray(servers)) {
            var url = "mongodb://";
            if (credentials && Object.hasOwnProperty.call(credentials, 'username') && credentials.hasOwnProperty.call(credentials, 'password')) {
                url = url.concat(credentials.username, ':', credentials.password, '@');
            }

            servers.forEach(function (element, index, array) {
                url = url.concat(element.host, ':', element.port, (index === array.length - 1 ? '' : ','));
            });

            url = url.concat('/');
            if (prefix) url = url.concat(prefix);
            url = url.concat(dbName);

            if (params && 'object' === typeof params && Object.keys(params).length) {
                url = url.concat('?');
                for (var i = 0; i < Object.keys(params).length; i++) {
                    url = url.concat(Object.keys(params)[i], '=', params[Object.keys(params)[i]], i === Object.keys(params).length - 1 ? '' : "&");
                }
            }
            return url;
        }
        return null;
    }
}
613485
function (registrationRequest, cb) {
            if (registrationRequest.$.password) {
                var ret = {
                    providerUserId: registrationRequest.get(this.$.usernameField),
                    authenticationData: this.createAuthenticationData(registrationRequest.$.password)
                };
                cb(null, ret);
            } else {
                cb("No password set");
            }
        }
601008
function(credentials){
      var socialLogin = false;
      if (credentials == undefined){
        credentials = {
          userid: $('#login_email').val(),
          password: $('#login_password').val()
        };
      } else if (typeof credentials === 'string'){
        socialLogin = true;
      }

      // Alter the UI to indicate that the login request is pending
      $('#login_button').attr('value', 'Logging in...');
      $('#register_button, #or').hide();

      var login = socialLogin ? cm.loginSocial.bind(cm) : cm.login.bind(cm);

      function loginError(msg){
        $('#login_button').attr('value', 'Login');
        $('#register_button, #or').show();
        todo.error('login', msg);
      }

      // Run CloudMine login request.
      login(credentials)
        .on('success', function(data){
          var services = data.profile.__services__;
          if(services){
            console.log("linked services:", services);
            data.profile.__services__.forEach(function(service){
              $('a.auth.' + service).hide();
            });
          }
          todo.process_login(data);
        })
        .on('unauthorized', function(data){
          loginError(data.errors[0]);
        })
        .on('error', function(data){
          loginError(data.errors ? data.errors[0] : "Error Logging in");
        })
    }
884199
function doLogin(req, user, callback) {
	req.logIn(user, function(err) {
		if (err) {
			logger.error(err);
			return callback(err);
		}
		user.login_timestamp = Date.now();
		fileUtil.getMetastoreSafe(req).then(function(store) {
			store.updateUser(user.username, user, function(err) {
				if (err) {
					logger.error(err);
					return callback(err);
				}
				callback(null);
			});
		}, function noMetastore(err) {
			callback(err);
		});
	});
}
151983
function (callback) {
                var self = this;
                flow()
                    .seq(function (cb) {
                        self.$handlers.stop(function () {
                            // ignore errors during stop
                            cb();
                        });
                    })
                    .seq(function (cb) {
                        self.$authenticationService.stop(function () {
                            cb();
                        });
                    })
                    .seq(function (cb) {
                        self.$filters.stop(function () {
                            // ignore errors during stop
                            cb();
                        });
                    })
                    .seq(function (cb) {
                        self.$endPoints.shutdown(function () {
                            // ignore errors during shutdown
                            cb();
                        });
                    })
                    .exec(function (err) {
                        callback && callback(err);

                        process.stdin.end();
                    });
            }
631624
function(handler, realm, cbauth) {
        var req = handler.httpRequest;
        this.init(realm, req);

        var username = this.digestParts["username"];
        // No username was given
        if (!username)
            return this.requireAuth(realm, "No digest authentication headers were found", cbauth);

        var self = this;
        this.getDigestHash(realm, username, function(err, hash) {
            // If this was false, the user account didn't exist
            if (err || !hash)
                return self.requireAuth(realm, err || "The supplied username was not on file", cbauth);

            if (typeof hash != "string") {
                handler.handleError(new Exc.jsDAV_Exception(
                    "The returned value from getDigestHash must be a string or null"));
                return cbauth(null, false);
            }

            // If this was false, the password or part of the hash was incorrect.
            self.validateA1(handler, hash, function(isValid) {
                if (!isValid)
                    return self.requireAuth(realm, "Incorrect username", cbauth);

                self.currentUser = username;
                cbauth(null, true);
            });
        });
    }
746930
function isLoggedInMiddleware() {
		return function isLoggedIn(req, res, next) {
			const AclUser = mongoose.model("TransomAclUser");

			if ((req.headers && req.headers.authorization) || (req.body && req.body.access_token) || (req.query && req.query.access_token)) {
				// Verify the authorization token or fail.
				passport.authenticate('bearer', {
					session: false
				}, function (err, user, info) {
					if (err) {
						return next(err);
					}
					if (!user || (info && info.indexOf("invalid_token") >= 0)) {
						// Something didn't work out.  Token Expired / Denied.
						debug("NOT LoggedIn - Invalid");
						return next(new restifyErrors.InvalidCredentialsError("Incorrect or expired credentials"));
					} else {
						// Properly authenticated!
						return next();
					}
				})(req, res, next);
			} else {
				// debug("No Authorization header or query access_token. Trying Anonymous.");
				if (localuser.anonymous !== false) {
					// Attempt anonymous login, if possible;
					AclUser.findOne({
						'username': 'anonymous',
						'active': true
					}, function (err, user) {
						if (err) {
							return next(err);
						}
						if (user) {
							req.locals = req.locals || {};
							req.locals.user = user;
							return next();
						}
						// Oh no, not authenticated
						debug("No bearer token provided or query access_token. No Anonymous user available.");
						return next(new restifyErrors.InvalidCredentialsError("No bearer token provided or query access_token. No Anonymous user available."));
					});
				} else {
					debug("No bearer token provided or query access_token.");
					return next(new restifyErrors.InvalidCredentialsError("No bearer token provided or query access_token."));
				}
			}
		}
	}
1161041
function(cb, thisArg) {
      var lastTask = this;
      while (lastTask.afterTask_)
        lastTask = lastTask.afterTask_;
      return lastTask.after(cb, thisArg);
    }
598562
function isTaskHandled(request, reply) {
        var taskName = request.query.task;

        // if no task or task handler, don't do anything
        if (!taskName && !taskHandlers[taskName]) { return false; }

        // if task info doesn't have service or method, don't do anything
        var taskInfo = taskHandlers[taskName];
        if (!taskInfo || !taskInfo.service || !taskInfo.method || !taskInfo.service[taskInfo.method]) {
            return false;
        }

        // if user is not logged in redirect to login then back to here
        if (!request.caller || !request.caller.user) {
            var currentUrl = request.url.pathname;
            var loginUrl = currentUrl + '?modal=auth&submodal=login&redirect=' + currentUrl;
            reply().redirect(loginUrl);
            return true;
        }

        // start collecting the service request
        var serviceReq = { caller: request.caller };

        // get the values from the request object to put into the service request
        _.each(taskInfo.params, function (param) {
            if (request.query[param]) {
                serviceReq[param] = request.query[param];
            }
        });

        // call the service method
        taskInfo.service[taskInfo.method](serviceReq)
            .then(function () {
                reply().redirect(request.path + '?notify=' + taskInfo.notifySuccess);
            })
            .catch(function (err) {
                log.error(err);
                reply().redirect(request.path + '?notify=' + taskInfo.notifyFailure);
            });

        return true;
    }