Returns a promise that resolves with {user:{...}, token:'...', ttl:X}, or rejects with {error:'...'[,error_description:'...',error_uri:'...']}
979003
function() {
        if (_oauth_client_id === "") {
          return $q.reject({error:'invalid_request', error_description:'RedirectLoginServiceProvider.OAuthClientID() not set'});
        }
        if (_oauth_authorize_uri === "") {
          return $q.reject({error:'invalid_request', error_description:'RedirectLoginServiceProvider.OAuthAuthorizeURI() not set'});
        }
        if (_oauth_redirect_uri === "") {
          return $q.reject({error:'invalid_request', error_description:'RedirectLoginServiceProvider.OAuthRedirectURI not set'});
        }

        // Never send a local fragment to remote servers
        var returnUri = new URI($location.url()).fragment("");
        var authorizeParams = {
          client_id: _oauth_client_id,
          response_type: 'token',
          state: makeState(returnUri.toString()),
          redirect_uri: _oauth_redirect_uri
        };

        if (_oauth_scope) {
          authorizeParams.scope = _oauth_scope;
        }

        if (_oauth_token_uri) {
          authorizeParams.response_type = "code";
          // TODO: add PKCE
        }

        var deferred = $q.defer();
        var uri = new URI(_oauth_authorize_uri);
        uri.query(authorizeParams);
        authLogger.log("RedirectLoginService.login(), redirecting", uri.toString());
        window.location.href = uri.toString();
        // Return a promise we never intend to keep, because we're redirecting to another page
        return deferred.promise;
      }
267780
function handleReset(req, res, next) {
		var p = new Promise(function (resolve, reject) {
			const currentToken = req.params.token || 'missing';
			const email = req.params.email || 'missing@email.com';
			const password = req.params.password;
			if (!password) {
				return reject(new restifyErrors.BadRequestError("New password is missing"));
			}
			const qry = {
				local_auth_type: 'password',
				active: true,
				email: email,
				verify_token: currentToken
			};
			AclUser.findOne(qry, function (err, usr) {
				if (err) {
					debug(`Error finding user for password reset`, err);
					return reject(new restifyErrors.InternalError(err));
				}
				if (!usr) {
					debug(`Password reset email address and reset token did not match`, email);
					return reject(new restifyErrors.InvalidCredentialsError("Email address and reset token did not match"));
				}
				usr.verify_token = "password-reset:" + usr.generateVerifyHash();
				usr.modifiedBy = 'password-reset';

				debug(`Updating ${email} with a password reset`);
				usr.setPassword(password, function () {
					usr.save(function (err, user) {
						if (err) {
							debug(`Error updating user during password reset`, err);
							return reject(new restifyErrors.InternalError(err));
						}
						const data = {
							'success': true,
							'message': "Password updated"
						};
						resolve(data);
					});
				});
			});
		}).then(function (data) {
			res.json(data);
			next();
		}).catch(function (err) {
			debug(`Password reset request failed`, err);
			next(err);
		});
	}
48913
function _Wrap(key, setFunction, _cacheGetter, _cacheSetter, ttl) {
    return new Promise((resolve, reject) => {
        // attempt to get the requested key (note, no prefix here, it's attached in the Get function)
        //  pass success directly through to resolve
        _cacheGetter.bind(this)(key).then(resolve, () => {
            // if cache miss, call the setFunction to get the new value we want
            setFunction().then((dataToCache) => {
                // work out ttl
                var options = {};
                if (ttl) {
                    //  if it's a function, call the function to get the required ttl
                    if (typeof ttl == "function") {
                        ttl = ttl();
                    }
                    options.ttl = ttl;
                }

                // store in cache
                _cacheSetter.bind(this)(key, dataToCache, options).then(() => {
                    // resolve with newly cached data
                    resolve(dataToCache);
                }, reject);
            }, reject);
        });
    });
}
1067293
function httpRequest(path, req, options)
{
    return new Promise(function(resolve, reject) {
        req = extend({}, defaults, req, options);
        req.url += path;

        request(req, function(error, response, body) {
            if (error || !(/^2/.test('' + response.statusCode)) || /action=".?login.lua"/.test(body)) {
                if (/action=".?login.lua"/.test(body)) {
                    // fake failed login if redirected to login page without HTTP 403
                    response.statusCode = 403;
                }
                reject({
                    error: error,
                    response: response,
                    options: req
                });
            }
            else {
                resolve(body.trim());
            }
        });
    });
}
550750
function(url, options, defaults) {
            var d = Q.defer();
            options = options || {};
            options = _.extend(options, defaults, {
                "url": url
            });
            var r = new Requests(options);
            r.on("done", function(content) {
                d.resolve(content);
            });
            r.on("error", function(err) {
                var e = new Error(err.textStatus+": "+err.content);
                e.textStatus = err.textStatus,
                e.httpRes = err.content;
                d.reject(e);
            });

            r.execute();
            return d.promise;
        }
45683
function Request__chain(promise, next) {

        if (!promise) {
            return new Promise(function (resolve, reject) {
                try {
                    resolve(next.apply(next, arguments));
                } catch (e) {
                    reject(new error.HttpError(500, {}, "Error on executing action", e));
                }
            });
        }

        return promise.then(function (data) {
            if (!!this.isPromiseChainStopped) {
                return promise;
            }
            return _handler(data);
        }.bind(this), this._handleError.bind(this));

        function _handler() {
            try {
                return next.apply(next, arguments);
            } catch (e) {
                throw new error.HttpError(500, {}, "Error on executing action", e);
            }
        }
    }
738678
function requestPromisfied(options) {
  return new Promise(function (resolve, reject) {
    (0, _request2.default)(options, function (err, res) {
      if (err) {
        reject(err);
      }
      resolve(res.body);
    });
  });
}
1294874
function loginP(authParams) {
  return new Promise((resolve, reject) =>
    this.login(authParams, (success, data) => {
      if (success) resolve(data);
      else reject(new Error(data));
    }));
}
849783
function(error) {
      if (this._resolved || this._rejected) {
        throw "A promise was rejected even though it had already been " +
          (this._resolved ? "resolved" : "rejected") + ".";
      }
      this._rejected = true;
      this._error = error;
      Parse._arrayEach(this._rejectedCallbacks, function(rejectedCallback) {
        rejectedCallback(error);
      });
      this._resolvedCallbacks = [];
      this._rejectedCallbacks = [];
    }
1193107
function executeRequest(opType, options) {
    if (token) {
        options.token = token;
    }

    // TODO: need to handle ETAG values
    var context = api.getOperationContext(opType, options);

    return new Promise((resolve, reject) => {
        request(context, (err, response, body) => {
            if (err || response.statusCode >= 400 || (context.method == 'GET' && !body)) {
                reject(new ApiError(response.statusCode, context, err));
            } else {
                resolve(body);
            }
        });
    });
}
685422
function tryFn(fn, args) {
  try {
    return Promise.resolve(fn.apply(null, args));
  } catch (e) {
    return Promise.reject(e);
  }
}
431434
function formAsPromise (req, modelName, formDsl) {

    return new Promise((resolve, reject) => {

        form(req, modelName, (err, decoratedForm) => {

            if (err) {
                return reject(err);
            }

            return resolve(decoratedForm);

        }, formDsl);

    });

}
124974
function wrapFunctionToReturnPromise(fn, Promise) {
	return function() {
		try {
			const result = fn.apply(this, arguments);
			if (result instanceof Promise) return result;
			return Promise.resolve(result);
		} catch (err) {
			return new Promise((resolve, reject) => { // jshint ignore:line
				reject(err);
			});
		}
	};
}
1332749
function () {
  /**
   * Renders an error view from a template and sends data to client
   * @param  {Object}   opts Configurable options (see periodicjs.core.responder for more details)
   * @param {string|Object} opts.err Error details for response
   * @param {Object} opts.req Express request object
   * @param {Object} opts.res Express response object
   * @param  {Function} [callback]   Optional callback function
   * @return {Object}      If callback is not defined returns a Promise which resolves after response has been sent
   */
  let fn = function handleDocumentQueryErrorResponse (opts = {}, callback) {
    let { err, req, res } = opts;
    if (opts.use_warning) this.protocol.warn(req, res, { err });
    else this.protocol.error(req, res, { err });
    if (req.query.format === 'json' || req.params.ext === 'json' || path.extname(req.originalUrl) === '.json' || req.is('json') || req.params.callback || req.is('application/json')) {
      return this.protocol.respond(req, res, { err });
    }
    else if (typeof callback === 'function') {
      return this.responder.error(err)
        .then(result => callback(null, result))
        .catch(callback);
    }
    else if (req.redirecturl) {
      req.redirectpath = (!req.redirectpath && req.redirecturl) ? req.redirecturl : req.redirectpath;
      return this.protocol.redirect(req, res);
    }
    else {
      return this._utility_responder.error(err, {})
        .then(result => {
          return this.protocol.respond(req, res, { responder_override: result });
        }, err => {
          return this.protocol.exception(req, res, { err });
        });
    }
  };
  let message = 'CoreController.handleDocumentQueryErrorResponse: Use CoreController.responder.error with an HTML adapter or CoreController._utility_responder.error instead';
  return wrapWithDeprecationWarning.call(this, fn, message);
}
1310337
function handleError(error, ignoreError) {
    appStore.setLoading(false)
    let reason

    if (error.response) {
        reason = handleResponseError(error)
    } else if (error.status >= 200 && error.status < 300) {
        reason = handleServiceError(error)
    } else {
        reason = handleRequestError(error)
    }

    if (ignoreError !== true) {
        appStore.setError(reason)
    }

    return Promise.reject(reason)
}
1112904
function promiseResult (options, data) {
		log(`promiseResult: data ${data}`);
		return new Promise((resolve, reject) => {
			/* Check cache to avoid I/O. */
			const cacheHit = checkCache(config, pattern);
			if (cacheHit !== RESPONSE_UNKNOWN) {
				log(`Cache hit: ${cacheHit}`);
				return resolve(cacheHit);
			}

			const req = https.request(options, (res) => {
				res.setEncoding('utf8');

				let response = '';
				res.on('data', (chunk) => {
					log(`Got data`);
					response += chunk;
				});

				res.on('end', () => {
					log(`end: I got ${JSON.stringify(response)}`);

					const result = serverResponseToRESPONSE(response);
					log(`end: result ${result}`);
					updateCache(config, postObject.pattern, result);

					if (result === RESPONSE_INVALID) {
						return reject(result);
					} else {
						return resolve(result);
					}
				});
			});

			req.on('error', (e) => {
				log(`Error: ${e}`);
				return reject(RESPONSE_INVALID);
			});

			// Write data to request body.
			log(`Writing to req:\n${data}`);
			req.write(data);
			req.end();
		});
	}
1142602
function promiseMiddleware (request, response, middleware) {
  return new promiseMiddleware.Promise(function (resolve, reject) {
    middleware(request, response, function next (error) {
      return error ? reject(error) : resolve()
    })
  })
}