validateFunc: (decoded, request, callback) => { // Do your checks to see if the person is valid. return P.try(() => { if (users[decoded.id]) { return true } return UserService.requireValidUser(decoded.id) }) .then(() => { // Passed ok. console.error('Auth successful: User id', decoded.id) callback(null, true) }) .catch(() => { // Failed ! console.error('Auth failed: Could not find user id', decoded.id) callback(null, false) }) },
.then((refs) => Promise.try(function() { if (!refs.length) { return; } return compiler.dropFKRefs(runner, refs); }) .then(function() { let sql = `alter table ${table} change ${wrapped} ${ column.Type }`; if (String(column.Null).toUpperCase() !== 'YES') { sql += ` NOT NULL`; } else { // This doesn't matter for most cases except Timestamp, where this is important sql += ` NULL`; } if (column.Default !== void 0 && column.Default !== null) { sql += ` DEFAULT '${column.Default}'`; } return runner.query({ sql, }); }) .then(function() { if (!refs.length) { return; } return compiler.createFKRefs( runner, refs.map(function(ref) { if (ref.REFERENCED_COLUMN_NAME === from) { ref.REFERENCED_COLUMN_NAME = to; } if (ref.COLUMN_NAME === from) { ref.COLUMN_NAME = to; } return ref; }) ); })
function createCard (cardText, list, position) { return Promise.try(function () { return mainBoard || init() }).then(function (board) { return checkDefaultLists(list) }).then(function (result) { return t.postAsync('/1/cards', { name: cardText, pos: position || 'top', due: null, idList: result.targetList, urlSource: null }) }).then(function () { console.log('Created card:', cardText) }).catch(function (err) { console.log('Error creating card', err) }) }
/** * Handles squirrel events if any. Then quits if any. * * @param {electron.app} app * @returns {Promise<boolean>} Are we handling squirrel events? False if we are not. */ function handleSquirrelStartupEvent(app) { if (process.platform !== 'win32') { return bluebird.resolve(false); } return bluebird.try(function () { const appName = 'Rodeo', squirrelCommand = process.argv[1], execPath = process.execPath, systemRoot = process.env.SystemRoot; log('info', 'squirrel saw', {squirrelCommand, execPath, systemRoot}); switch (squirrelCommand) { case '--squirrel-install': return bluebird.all([ shortcuts.create(execPath), contextMenu.install(execPath, systemRoot), commands.addToPath(appName, execPath, systemRoot) ]).then(() => app.quit()) .return(true); case '--squirrel-updated': return bluebird.all([ shortcuts.update(execPath, appName, os.homedir()), contextMenu.install(execPath, systemRoot), commands.addToPath(appName, execPath, systemRoot) ]).then(() => app.quit()) .return(true); case '--squirrel-uninstall': return bluebird.all([ shortcuts.remove(execPath), contextMenu.uninstall(systemRoot), commands.removeFromPath(execPath, systemRoot) ]).then(() => app.quit()) .return(true); case '--squirrel-obsolete': app.quit(); return true; default: return false; } }); }
function determineRootDir(state) { return Promise.try(function () { // var rootDir = path.normalize(['src', 'cdn'].join('/')); // state.rootDir = rootDir; state.rootDir = state.args.dir || state.config.server.root; return state; }); // return fs.existsAsync(rootDir) // .then(function (exists) { // console.log('Exists? ', exists); // if (!exists) { // throw new Error('root dir ' + rootDir + ' does not exist or is not accessible to you'); // } // config.rootDir = rootDir; // console.log('Got root dir: ', rootDir); // return config; // }); }
.then((res) => { return Promise .try(function() { expect(res).to.have.status(config.status); if (config.contentType) expect(res).to.have.header('content-type', exports.contentTypes[config.contentType] || config.contentType); if (typeof config.check === 'function') config.check(res); return null; }) .catch(err => { done.note(`res.text: ${res.text}`); throw err; }) })
return data => { const eventData = cloneDeep(data); const routingKey = `${producer.getName()}.${entityName}.${actionName}`; return Promise.try(() => populate(eventData, options, database)) .then(populated => producer.sendMessage(routingKey, populated)) .tap(() => { logger.debug('Published DB event', { 'data.id': eventData.id, event: routingKey, }); }) .catch(error => { logger.error('Error while publishing DB event', { error, 'data.id': eventData.id, event: routingKey, }); }); };
var cli = module.exports = function (argv, options) { return Promise.try(function () { //default argv from process.argv if (!argv) argv = process.argv.slice(2); //new a parser this argv var parser = new Parser(argv, options); //load cli xml return parser .loadCliConfig() .then(parser.normolizeFlags.bind(parser)) .then(parser.helpUsage.bind(parser)) .then(parser.assignOptions.bind(parser)) .then(parser.validateRequireds.bind(parser)) .then(parser.validateUnknowns.bind(parser)) .then(parser.getCLI.bind(parser)) }) }
module.exports = (errorCode) => { return Promise .try(() => { info('touching') }) .then(() => { return touch.sync(`/var/tmp/__ha-garage-${moment().format()}.exit`) }) .then(() => { info('touched') }) .catch((err) => { error('touch failed.', 'err:', err) }) .finally(() => { error('Exiting process') process.exit(errorCode) }) }
.then((res) => P.try(() => P.each(res.rows, (row) => { // Decorate the row result with the _ttl attribute. if (options.withTTL) { dbu.assignMaxTTL(row); } handler(row); })).then(() => { if (!res || res.pageState === null) { return P.resolve(); } else { // Break the promise chain, so that we don't hold onto a // previous page's memory. process.nextTick(() => P.try(() => processPage(res.pageState)).catch((e) => { // there's something going on, just log it // since we have broken the promise chain options.log('error/cassandra/backgroundUpdates', e); })); } }));
module.exports = function Quakey(data) { return Promise .try(function() { var result = tv4.validateMultiple(data, SCHEMA); return !result ? data : Error(tv4.error); }) .then(function() { const url = URL + querystring.stringify(data); return Promise.fromCallback(function(done) { client.get(url, function(data, res) { done(null, data.features || "None") }) }) }) }
/** * When Electron is ready, we can start making windows */ function onReady() { let windowName, window; return bluebird.try(function () { if (argv.design) { windowName = 'designWindow'; window = browserWindows.create(windowName, { url: 'file://' + path.join(staticFileDir, windowUrls[windowName]) }); window.show(); } else if (_.size(argv._)) { const statSearch = _.map(argv._, arg => { return files.getStats(arg) .catch(_.noop) .then(stats => { return {name: path.resolve(arg), stats}; }); }); return bluebird.all(statSearch).then(function (files) { log('info', 'files', files); const file = _.head(_.compact(files)); if (file) { if (file.stats.isDirectory()) { return startMainWindowWithWorkingDirectory(file.name); } else { return startMainWindowWithOpenFile(file.name, file.stats); } } else { log('info', 'no files found with', argv._); return startStartupWindow(); } }); } else if (argv.startup === false) { return startMainWindow(); } else { return startStartupWindow(); } }).then(attachIpcMainEvents) .catch(error => log('error', error)); }
putUpdateMember: function(req, res, next) { // Checks if we have permission to update Promise.try(function() { // User updates self if (req.user.id === +req.params.id) { return; } // Otherwise admin updates members of organization return Promise.join(dbUtils.getUserAsync({id: req.params.id}), dbUtils.getOrgAsync({admin_id: req.user.id}), function(member, org) { if (member.organization_id !== org.id) { throw new Error(403); } }); }).then(function() { req.body.id = req.params.id; return dbUtils.updateUserAsync(req.body); }).then(function() { controllerUtils.serveStatus(res, 204); }) .catch(function(error) { controllerUtils.checkError(res, error); }); },
.then(function() { // Save all nested endpoints and events if (options && options.deep) { return BbPromise.try(function () { return _this.endpoints; }) .each(function(endpoint) { return endpoint.save(); }) .then(function () { return _this.events; }) .each(function(event) { return event.save(); }) } })
return readUserInfo.password().then((password) => { return BB.try(() => { if (conf.otp) return return readUserInfo.otp('Enter one-time password from your authenticator: ').then((otp) => { conf = conf.concat({otp}) }) }).then(() => { log.info('profile', 'disabling tfa') return pulseTillDone.withPromise(profile.set({tfa: {password: password, mode: 'disable'}}, conf)).then(() => { if (conf.json) { output(JSON.stringify({tfa: false}, null, 2)) } else if (conf.parseable) { output('tfa\tfalse') } else { output('Two factor authentication disabled.') } }) }) })
return buffer(req).then(function (body) { var file = path.join(opts.dirname, tapename(req, body, opts)); return Promise.try(function () { return require.resolve(file); }).catch(ModuleNotFoundError, function (/* err */) { if (opts.noRecord) { throw new RecordingDisabledError('Recording Disabled'); } else { return proxy(req, body, host).then(function (pres) { if (_.inRange(pres.statusCode, opts.recordStatusCodes[0], opts.recordStatusCodes[1])) { return record(pres.req, pres, file); } else { throw new StatusCodeOutOfRangeError('Status code out of range, skipping recording', pres); } }); } }); }).then(function (file) {
return function() { return Promise.try(function() { if (animationSkipped) { // Lol who needs proper flow control throw new Error('SKIP IT'); } // Write a character or multiple characters to the buffer. var chars = message.slice(index, index + charsPerInterval); index += charsPerInterval; // Ensure we stay scrolled to the bottom. el.scrollTop = el.scrollHeight; // If this is going to <style> it's more complex; otherwise, just write. if (mirrorToStyle) { writeChar(el, chars); } else { writeSimpleChar(el, chars); } }) .then(function() { if (index < message.length) { // Schedule another write. var thisInterval = interval; var thisSlice = message.slice(index - 2, index + 1); if (!isDev) { if (endOfSentence.test(thisSlice)) thisInterval *= 70; if (endOfBlock.test(thisSlice)) thisInterval *= 50; } return thisInterval; } }) .then(function wait(thisInterval) { if (typeof thisInterval !== "number") return; if (paused) { return Promise.delay(thisInterval).then(wait.bind(null, thisInterval)); } else { return Promise.delay(thisInterval) .then(writeTo(el, message, index, interval, mirrorToStyle, charsPerInterval)); } }); };
setWrapper: function(path, val, opts) { var resourceid; opts = opts || {}; return Promise.try(function() { resourceid = pointer.parse(path)[0]; // Do all the sanitizing outside of this function. // Update the content of the resource to fill in revisions for versioned links // and list this resource as a parent of each child. Also adds parent/child relationships. if (opts.skipSet) return; return rev_graph().updateVersionedLinksInObj(val, resourceid, path) }).then(function(new_val) { if (opts.skipSet) return; return db.set('resources', path, new_val); }).then(function() { if (opts.skipQueueRevUpdate) return; return rev_graph().queueRevForUpdate(resourceid); // should be synchronous }); },
/** * @override */ rawInsert (rawDoc) { return Q.try(() => { if (this.schema) { return this.schema.validate(rawDoc); } }) .then(() => { return this.rawQry().insert(rawDoc).run(); }) .then((ret) => { let newDoc = _.extend({}, rawDoc); if (!newDoc[this.pk] && ret.generated_keys) { newDoc[this.pk] = ret.generated_keys[0]; } return newDoc; }); }
return summary(teams).then(function (s) { var i, updated; // Store AI's proposed trade in database, if it's different updated = false; for (i = 0; i < 2; i++) { if (teams[i].tid !== teams0[i].tid) { updated = true; break; } if (teams[i].pids.toString() !== teams0[i].pids.toString()) { updated = true; break; } if (teams[i].dpids.toString() !== teams0[i].dpids.toString()) { updated = true; break; } } return Promise.try(function () { var tx; if (updated) { tx = dao.tx("trade", "readwrite"); dao.trade.put({ ot: tx, value: { rid: 0, teams: teams } }); return tx.complete(); } }).then(function () { if (s.warning) { return g.teamRegionsCache[teams[1].tid] + ' GM: "Something like this would work if you can figure out how to get it done without breaking the salary cap rules."'; } return g.teamRegionsCache[teams[1].tid] + ' GM: "How does this sound?"'; }); });
List.prototype.removeFile = function (path) { var self = this return Promise.try(function () { var pattern = self._isIncluded(path) var file = self._findFile(path, pattern) if (!pattern || !file) { log.debug('Removed file "%s" ignored. Does not match any file in the list.', path) return self.files } self.buckets.get(pattern.pattern).delete(file) log.info('Removed file "%s".', path) self._emitModified() return self.files }) }
AuthorizationCodeGrantType.prototype.getAuthorizationCode = function(request, client) { if (!request.body.code) { throw new InvalidRequestError('Missing parameter: `code`'); } if (!is.vschar(request.body.code)) { throw new InvalidRequestError('Invalid parameter: `code`'); } return Promise.try(this.model.getAuthorizationCode, request.body.code) .then(function(code) { if (!code) { throw new InvalidGrantError('Invalid grant: authorization code is invalid'); } if (!code.client) { throw new ServerError('Server error: `getAuthorizationCode()` did not return a `client` object'); } if (!code.user) { throw new ServerError('Server error: `getAuthorizationCode()` did not return a `user` object'); } if (code.client.id !== client.id) { throw new InvalidGrantError('Invalid grant: authorization code is invalid'); } if (!(code.expiresAt instanceof Date)) { throw new ServerError('Server error: `expiresAt` must be a Date instance'); } if (code.expiresAt < new Date()) { throw new InvalidGrantError('Invalid grant: authorization code has expired'); } if (code.redirectUri && !is.uri(code.redirectUri)) { throw new InvalidGrantError('Invalid grant: `redirect_uri` is not a valid URI'); } return code; }); };
enableCloudSync (id, password) { Dispatcher.enableCloudSync('start'); let auth = new Auth('cloud'); return Q.try(() => { if (!this.auth.isLocalType) { throw new Error('Diary already linked to cloud account'); } }) .then(() => { Dispatcher.enableCloudSync('progress', 'Creating account'); return auth.signUp(id, password); }) .then(() => { this._id = id; this._auth = auth; Dispatcher.enableCloudSync('progress', 'Saving diary'); return this._saveEntriesToStorage(this.confirmedEntries); }) .then(() => { // remove all traces of local diary return Storage.local.removeLocalDiary(this.id); }) .then(() => { // start sync this._startSync(); Dispatcher.enableCloudSync('result'); Dispatcher.alertUser('Cloud sync enabled!'); }) .catch((err) => { this.logger.error(err); Dispatcher.enableCloudSync('error', err); throw err; }); }
/** * Get user data by token * @param context value object containing: accessToken | refreshToken * @return Promise with object with user, and info; or null - if not found */ findUserByToken(context) { return Bb.try(() => { if (context.accessToken) { return AccessToken .findOne({ token: context.accessToken }) .then((accessToken) => { // if it's expired if (accessToken && Math.round( (Date.now() - accessToken.createdAt) / 1000) > this.tokenLife) { return accessToken .remove() .then(() => { throw new Error('Token expired'); }); } else { return accessToken; } }) ; } else if (context.refreshToken) { return RefreshToken.findOne({ token: context.refreshToken }); } else { throw new Error('Wrong context!'); } }) .then((token) => { if (token) { return User .findOne({ _id: token.userId }) .then((user) => { if (!user) { throw new Error('Unknown user'); } const info = { scope: token.scopes }; return { obj: user, info }; }); } else { return { obj: false }; } }); }
exports.getDefinition = function (options) { if (!options.layerId && options.key) { // Legacy coloration/filter specification return exports.getLegacyLayer({ key: options.key, val: options.val, surveyId: options.surveyId, grid: options.grid }); } return Promise.try(function () { if (options.layerId) { return CacheItem.findOneAndUpdateAsync({ _id: { cache: CACHE_NAME, key: options.layerId } }, { $set: { accessed: new Date() } }, { new: true }).then(function (item) { if (item) { return { query: JSON.parse(item.contents.query), select: JSON.parse(item.contents.select), styles: item.contents.styles }; } }); } return { query: {}, select: {}, styles: themes.coverage }; }); };
.then(() => { if (!socket.isConnected) { // since we may enter this function multiple times for the same // event source's IPC we don't want to repeat the connection // process each time - so let's track things in a promise if (!this._connectionPromise[ownerId]) { this._connectionPromise[ownerId] = Q.try(() => { log.debug(`Connecting socket ${ownerId}`); // wait for node to connect first. if (ethereumNode.state !== ethereumNode.STATES.CONNECTED) { return new Q((resolve, reject) => { const onStateChange = (newState) => { if (ethereumNode.STATES.CONNECTED === newState) { ethereumNode.removeListener('state', onStateChange); log.debug(`Ethereum node connected, resume connecting socket ${ownerId}`); resolve(); } }; ethereumNode.on('state', onStateChange); }); } }) .then(() => { return socket.connect(Settings.rpcConnectConfig, { timeout: 5000, }); }) .then(() => { log.debug(`Socket connected, id=${ownerId}`); }) .finally(() => { delete this._connectionPromise[ownerId]; }); } return this._connectionPromise[ownerId]; } })
AuthorizeHandler.prototype.getClient = function(request) { var clientId = request.body.client_id || request.query.client_id; if (!clientId) { throw new InvalidRequestError('Missing parameter: `client_id`'); } if (!is.vschar(clientId)) { throw new InvalidRequestError('Invalid parameter: `client_id`'); } var redirectUri = request.body.redirect_uri || request.query.redirect_uri; if (redirectUri && !is.uri(redirectUri)) { throw new InvalidRequestError('Invalid request: `redirect_uri` is not a valid URI'); } return Promise.try(this.model.getClient, clientId) .then(function(client) { if (!client) { throw new InvalidClientError('Invalid client: client credentials are invalid'); } if (!client.grants) { throw new InvalidClientError('Invalid client: missing client `grants`'); } if (!_.contains(client.grants, 'authorization_code')) { throw new UnauthorizedClientError('Unauthorized client: `grant_type` is invalid'); } if (!client.redirectUris || 0 === client.redirectUris.length) { throw new InvalidClientError('Invalid client: missing client `redirectUri`'); } if (redirectUri && !_.contains(client.redirectUris, redirectUri)) { throw new InvalidClientError('Invalid client: `redirect_uri` does not match client value'); } return client; }); };
/* * @input: Array of Entry objects. (PDF only) * add temp URL to object. */ function OCR(filesEntries){ var newArr; // Creates a new array and uses same object. // Only difference is new field, which holds PDF URL. Promise.try(function (){ return filesEntries; }).map(function (entry) { // Will transform array to include temp (4 hrs) URLs. return dropbox.getTempLink(entry['path_display']); }).map(function (entryWithTemp){ // Same array but now with temp URL (4 hrs) // Transform array for elements with response obj. return Watson.document_conversion(entryWithTemp); }).map(function (newEntry){ // New objects: { name: <filename>, text: <ocr>} // The beef of application; detect sensitive data. return riskAnalysis(newEntry); }).filter(function (file){ if (file.clean) { // File is clean, no need to do anything, remove. return false; } else { // File may include sensitive information, keep. return true; } }).then(function (compromisedFiles){ var amountCompromised = compromisedFiles.length; console.log(amountCompromised + " uploaded file(s) includes sensitive information."); if (amountCompromised < 1){ // No files compromised. // Notify FB user. Facebook.sendTextMessage('Checked, and double checked. All your files look clean!') } else { // Loop through caught into and send to user via FB Messenger. compromisedFiles.forEach(function (file){ Facebook.processAnalysis(file); }); } }); }
.then(function(patch) { var last_patch_set; var is_same_commit; if (patch.length !== 0) { last_patch_set = _.last(patch[0].patchSets); is_same_commit = (last_patch_set.revision === git.hashFor("HEAD")); if (is_same_commit) { if (!last_patch_set.isDraft || is_draft) { throw new CliError("This commit has already been sent to Gerrit."); } return prompt_undraft(); } } return Q.try(function() { if (last_patch_set && last_patch_set.isDraft && !is_draft) { return prompter.confirm("The last patch set was sent as a *draft*, would you like to send this patch set as a draft as well?", true) .then(function(confirmed) { is_draft = confirmed; }); } }) .then(function() { return gerrit.up(remote, branch, is_draft); }); });
it('Should purge caches on resource_change coming from RESTBase', (done) => { var udpServer = dgram.createSocket('udp4'); let closed = false; udpServer.on("message", function(msg) { try { msg = msg.slice(22, 22 + msg.readInt16BE(20)).toString(); if (msg.indexOf('User%3APchelolo%2FTest') >= 0) { assert.deepEqual(msg, 'http://en.wikipedia.beta.wmflabs.org/api/rest_v1/page/html/User%3APchelolo%2FTest/331536') udpServer.close(); closed = true; done(); } } catch (e) { udpServer.close(); closed = true; done(e); } }); udpServer.bind(4321); P.try(() => producer.produce('test_dc.resource_change', 0, Buffer.from(JSON.stringify({ meta: { topic: 'resource_change', schema_uri: 'resource_change/1', uri: 'http://en.wikipedia.beta.wmflabs.org/api/rest_v1/page/html/User%3APchelolo%2FTest/331536', request_id: uuid.now(), id: uuid.now(), dt: new Date().toISOString(), domain: 'en.wikipedia.beta.wmflabs.org' }, tags: ['restbase'] })))) .delay(common.REQUEST_CHECK_DELAY) .finally(() => { if (!closed) { udpServer.close(); done(new Error('Timeout!')); } }); });