Imports an authentication middleware
module to replace the server's auth
function, which is called when a remote
instance of vantage connects.

@param {Function} middleware
@param {Object} options
@return {Vantage}
@api public
516250
function(middleware, options) {
    if (this.server && this.server.auth) {
      this.server.auth(middleware, options);
    } else {
      throw new Error("vantage.auth is only available in Vantage.IO. Please use this (npm install vantage-io --save)");
    }
    return this;
  }
995208
function loadEndpoints(endpoints, options, auth) {
	if (Array.isArray(endpoints)) {
		endpoints.forEach(function(endpoint) {
			if (auth !== Boolean(endpoint.authenticated)) {
				//after endpoints refactored, remove this check
				return;
			}
			const conditional = endpoint.hasOwnProperty("ifProp");
			if (conditional && options.configParams.get(endpoint.ifProp) || !conditional) {
				tryLoadRouter(endpoint, options);
			}
		});
	}
}
880700
function(connect, options, middlewares) {
					// make sure to put the middleware after "cors"
					// if "watch" is enabled, there will be another livereload middleware in between
					middlewares.splice(grunt.option('watch') ? 3 : 2, 0, [ '/' + testsuiteName + '/resources/sap/ui/Global.js', function(req, res, next) {
						fs.readFile(sapUiCoreBasePath + '/src/sap/ui/Global.js', { encoding: 'utf-8' } , function(err, data) {
							if (err) {
								res.writeHead(404);
								res.end();
							} else {
								res.writeHead(200, { 'Content-Type': 'application/javascript' });
								data = data.replace(/(?:\$\{version\}|@version@)/g, grunt.config("package.version"));
								data = data.replace(/(?:\$\{buildtime\}|@buildtime@)/g, sapUiBuildtime);
								res.write(data);
								res.end();
							}
						});
					} ], [ '/' + testsuiteName + '/resources/sap-ui-version.json', function(req, res, next) {

						var version = grunt.config('package.version');

						var sapUiVersionJson = {
							name: testsuiteName,
							version: version,
							buildTimestamp: sapUiBuildtime,
							scmRevision: '',
							gav: 'com.sap.openui5:testsuite:' + version,
							libraries: config.allLibraries.map(function(library) {
								return {
									name: library.name,
									version: version,
									buildTimestamp: sapUiBuildtime,
									scmRevision: ''
								};
							})
						};

						var data = JSON.stringify(sapUiVersionJson, null, "\t");

						res.writeHead(200, {
							'Content-Type': 'application/json'
						});
						res.write(data);
						res.end();

					} ]);

					var oCspConfig = {
						allowDynamicPolicySelection: true,
						allowDynamicPolicyDefinition: true,
						defaultPolicyIsReportOnly: true,
						definedPolicies: {
							"sap-target-level-1":
								"default-src 'self'; " +
								"script-src  'self' 'unsafe-eval'; " +
								"style-src   'self' 'unsafe-inline'; " +
								"font-src    'self' data:; " +
								"img-src     'self' * data: blob:; " +
								"frame-src   'self' https: data: blob:; " +
								"child-src   'self' https: data: blob:; " +
								"connect-src 'self' https: wss:;",
							"sap-target-level-2":
								"default-src 'self'; " +
								"script-src  'self'; " +
								"style-src   'self' 'unsafe-inline'; " +
								"font-src    'self' data:; " +
								"img-src     'self' * data: blob:; " +
								"frame-src   'self' https: data: blob:; " +
								"child-src   'self' https: data: blob:; " +
								"connect-src 'self' https: wss:;"
						}
					};
					middlewares.unshift(cspMiddleware("sap-ui-xx-csp-policy", oCspConfig));

					// Make sure .xml files are served with Content-Type application/xml instead of text/xml
					// as it causes issues with OData / datajs.
					// The new tooling (https://github.com/SAP/ui5-tooling) already uses the correct header.
					middlewares.unshift(function(req, res, next) {
						var sFilePath = url.parse(req.url).pathname;
						if (sFilePath && sFilePath.endsWith(".xml")) {
							res.setHeader("Content-Type", "application/xml");
						}
						next();
					});

					return middlewares;
				}
767727
function authenticate(passport, name, options, callback) {
  // normalize arguments
  if (typeof options === 'function') {
    callback = options
    options  = {}
  }
  options = options || {}

  if (callback) {
    // When the callback is set, neither `next`, `res.redirect` or `res.end`
    // are called. That is, a workaround to catch the `callback` is required.
    // The `passportAuthenticate()` method below will therefore set
    // `callback.resolve` and `callback.reject`. Then, once the authentication
    // finishes, the modified callback calls the original one and afterwards
    // triggers either `callback.resolve` or `callback.reject` to inform
    // `passportAuthenticate()` that we are ready.
    const _callback = callback
    callback = function(err, user, info, status) {
      try {
        Promise.resolve(_callback(err, user, info, status))
               .then(() => callback.resolve(false))
               .catch(err => callback.reject(err))
      } catch (err) {
        callback.reject(err)
      }
    }
  }

  const middleware = promisify(_authenticate(passport, name, options, callback))

  return function passportAuthenticate(ctx, next) {
    // this functions wraps the connect middleware
    // to catch `next`, `res.redirect` and `res.end` calls
    const p = new Promise((resolve, reject) => {
      // mock the `req` object
      const req = createReqMock(ctx, options.assignProperty || passport._userProperty || 'user')

      function setBodyAndResolve(content) {
        if (content) ctx.body = content
        resolve(false)
      }

      // mock the `res` object
      const res = {
        redirect: function(url) {
          ctx.redirect(url)
          resolve(false)
        },
        set: ctx.set.bind(ctx),
        setHeader: ctx.set.bind(ctx),
        end: setBodyAndResolve,
        send: setBodyAndResolve,
        set statusCode(status) {
          ctx.status = status
        },
        get statusCode() {
          return ctx.status
        }
      }

      req.res = res

      // update the custom callback above
      if (callback) {
        callback.resolve = resolve
        callback.reject  = reject
      }

      // call the connect middleware
      middleware(req, res).then(resolve, reject)
    })

    return p.then(cont => {
      // cont equals `false` when `res.redirect` or `res.end` got called
      // in this case, call next to continue through Koa's middleware stack
      if (cont !== false) {
        return next()
      }
    })
  }
}
1046157
function tryLoadRouter(endpoint, options) {
	const args = [];
	var isEndpoint = typeof endpoint.endpoint === 'string';
	if (isEndpoint) {
		args.push(endpoint.endpoint);
		args.push(responseTime({digits: 2, header: "X-Total-Response-Time", suffix: true}));
	}
	if (endpoint.authenticated) {
		args.push(options.authenticate);
		if (endpoint.checkAuthenticated === undefined || endpoint.checkAuthenticated) {
			args.push(checkAuthenticated);
		}
	}
	if (isEndpoint) {
		args.push(options.basicMiddleware);
	}
	if (isEndpoint && csrf && (endpoint.checkCSRF === undefined || endpoint.checkCSRF)) { // perform CSRF by default
		args.push(csrf);
		args.push(function(req, res, next) {
			var preamble = options.configParams.get("orion_cookies_name_premable") || "";
			var tokenCookie = preamble + 'x-csrf-token';
			if (!req.cookies[tokenCookie]) {
				var cookieOptions;
				var cookiesPath = options.configParams.get("orion_cookies_path");
				if (cookiesPath) {
					cookieOptions = {path: cookiesPath};
				}
				res.cookie(tokenCookie, req.csrfToken(), cookieOptions);
			}
			next();
		});
	}
	if (endpoint.checkAccess) {
		args.push(checkAccessRights);
	}
	try {
		const mod = require(endpoint.module);
		let fn = null;
		if (typeof mod.router === 'function') {
			fn = mod.router;
		} else if(typeof mod === 'function') {
			fn = mod;
		} else {
			logger.log("Endpoint did not provide the API 'router' function: " + JSON.stringify(endpoint, null, '\t'));
			return;
		}
		if(fn) {
			const router = fn(options);
			if (!router) {
				return; //endpoint does not want to take part in routing, quit
			}
			args.push(router);
			options.app.use.apply(options.app, args);
		}
	} catch (err) {
		logger.error("Failed to load module: " + err.message + "..." + err.stack);
	}
}
444521
function(opts){
  //setup options
  this.opts = new ObjectManage({
    username: '',
    password: '',
    domain: 'cdn.oose.io',
    prism: {
      host: null,
      port: 5971
    }
  })
  this.opts.$load(opts)
  //set properties
  this.api = {}
  this.authenticated = false
  this.connected = false
  this.session = {}
}
1292025
function(provider, options) {
      var authType;
      if (_.isString(provider)) {
        authType = provider;
        provider = Parse.User._authProviders[provider];
      } else {
        authType = provider.getAuthType();
      }
      if (_.has(options, 'authData')) {
        var authData = this.get('authData') || {};
        authData[authType] = options.authData;
        this.set('authData', authData);

        // Overridden so that the user can be made the current user.
        var newOptions = _.clone(options) || {};
        newOptions.success = function(model) {
          model._handleSaveResult(true);
          if (options.success) {
            options.success.apply(this, arguments);
          }
        };
        return this.save({'authData': authData}, newOptions);
      } else {
        var self = this;
        var promise = new Parse.Promise();
        provider.authenticate({
          success: function(provider, result) {
            self._linkWith(provider, {
              authData: result,
              success: options.success,
              error: options.error
            }).then(function() {
              promise.resolve(self);
            });
          },
          error: function(provider, error) {
            if (options.error) {
              options.error(self, error);
            }
            promise.reject(error);
          }
        });
        return promise;
      }
    }
1198935
function loadMiddlewareModules (options)
  {
    var middlewareStackClasses = [];

    options.internalMiddleware.forEach (function (moduleName)
    {
      var module = require (moduleName);
      if (!module.middleware)
        util.fatal ('No middleware found on module %.', moduleName);
      if (module.options)
        extend (options, module.options);
      middlewareStackClasses.push (module.middleware);
    });

    if (options.externalMiddleware)
      options.externalMiddleware.forEach (function (info)
      {
        var module = require (info.load);
        if (module.options)
          extend (options, new module.options ());
        var target = info.before || info.after
          , i = middlewareStackClasses.indexOf (target);
        if (~i)
          util.fatal ("Can't locate the % middleware module for inserting %.", target, info.load);
        middlewareStackClasses.splice (i + (info.before ? 0 : 1), 0, module.middleware);
      });

    return middlewareStackClasses;
  }
1257190
function startSkeletonApplication(options) {
  debug('Starting to create application skeleton');
  const configWithDefaults = defaults(
    options, {
      redirects: {
        'documentation-from-root': {
          match: /^\/$/,
          target: '/docs',
        },
      },
      ioc: {
      },
      customMiddleware: {
        beforeSwagger: [],
        afterSwagger: [],
        beforeController: [],
      },
      codegen: {
        controllerStubFolder: 'controllers',
        temporaryDirectory: './.temp',
        templateSet: templates,
      },
      service: {
        listenPort: 10010,
      },
      cors: {
      },
    });

  // If the swagger input is a string, then load it as a filename
  const swaggerFile = configWithDefaults.service.swagger;
  const swagger = typeof swaggerFile === 'string' ?
    yamljs.load(swaggerFile) : swaggerFile;

  // Create service instances
  const app = connect();
  const ioc = connectIoc(configWithDefaults.ioc);

  // Generate custom application code
  generateApplicationCode(
    swagger,
    configWithDefaults.codegen);

  initializeSwagger(swagger, (middleware) => {
    // Pre-request handling middleware
    app.use(query());                                    // Query-string parsing
    app.use(fiddleware.respondJson());                   // res.json(data, status) support.
    app.use(ioc.middleware);                             // Somersault IoC for controllers.
    app.use(cors(configWithDefaults.cors));              // Cross-origin
    app.use(cookieParser());
    // Custom middleware
    for (const item of configWithDefaults.customMiddleware.beforeSwagger) {
      app.use(item);
    }

    // Swagger-tools middleware
    app.use(middleware.swaggerMetadata());
    app.use(middleware.swaggerValidator());

    for (const item of configWithDefaults.customMiddleware.beforeController) {
      app.use(item);
    }

    app.use(middleware.swaggerRouter({
      controllers: path.join(
        configWithDefaults.codegen.temporaryDirectory,
        configWithDefaults.codegen.controllerStubFolder),
    }));
    app.use(middleware.swaggerUi());

    // Post-request handling middleware
    app.use(redirect(configWithDefaults.redirects));      // Redirect / to /docs

    // Custom middleware
    for (const item of configWithDefaults.customMiddleware.afterSwagger) {
      app.use(item);
    }

    app.use(errorHandler());                              // When there's an exception.

    const server = app.listen(configWithDefaults.service.listenPort);
    app.close = function closeServer() {
      server.close();
    };
  });

  return app;
}
1055579
async function createApp(middlewareConfig) {
  const app = new Koa()

  const middleware = await setupMiddleware(middlewareConfig, app)

  if (app.env == 'production') {
    app.proxy = true
  }

  return {
    app,
    middleware,
  }
}
468981
function createDefaultMiddleware(connect, options) {
    var middlewares = [];
    if (!Array.isArray(options.base)) {
      options.base = [options.base];
    }
    // Options for serve-static module. See https://www.npmjs.com/package/serve-static
    var defaultStaticOptions = {};
    var directory = options.directory || options.base[options.base.length - 1];
    options.base.forEach(function(base) {
      // Serve static files.
      var path = base.path || base;
      var staticOptions = base.options || defaultStaticOptions;
      middlewares.push(serveStatic(path, staticOptions));
    });
    // Make directory browse-able.
    middlewares.push(serveIndex(directory.path || directory, directory.options));
    return middlewares;
  }
1367494
function createMiddleware(options = {}) {
  const middlewareOptions = Object.assign({}, defaults, options);

  return ({ getState }) => next => action => {
    // Do not process actions without an [RSAA] property
    if (!isRSAA(action)) {
      return next(action);
    }

    return (async () => {
      // Try to dispatch an error request FSA for invalid RSAAs
      const validationErrors = validateRSAA(action);
      if (validationErrors.length) {
        const callAPI = action[RSAA];
        if (callAPI.types && Array.isArray(callAPI.types)) {
          let requestType = callAPI.types[0];
          if (requestType && requestType.type) {
            requestType = requestType.type;
          }
          next({
            type: requestType,
            payload: new InvalidRSAA(validationErrors),
            error: true
          });
        }
        return;
      }

      // Parse the validated RSAA action
      const callAPI = action[RSAA];
      var {
        endpoint,
        body,
        headers,
        options = {},
        fetch: doFetch = middlewareOptions.fetch,
        ok = middlewareOptions.ok
      } = callAPI;
      const { method, credentials, bailout, types } = callAPI;
      const [requestType, successType, failureType] = normalizeTypeDescriptors(
        types
      );

      // Should we bail out?
      try {
        if (
          (typeof bailout === 'boolean' && bailout) ||
          (typeof bailout === 'function' && bailout(getState()))
        ) {
          return;
        }
      } catch (e) {
        return next(
          await actionWith(
            {
              ...failureType,
              payload: new RequestError('[RSAA].bailout function failed'),
              error: true
            },
            [action, getState()]
          )
        );
      }

      // Process [RSAA].endpoint function
      if (typeof endpoint === 'function') {
        try {
          endpoint = endpoint(getState());
        } catch (e) {
          return next(
            await actionWith(
              {
                ...failureType,
                payload: new RequestError('[RSAA].endpoint function failed'),
                error: true
              },
              [action, getState()]
            )
          );
        }
      }

      // Process [RSAA].body function
      if (typeof body === 'function') {
        try {
          body = body(getState());
        } catch (e) {
          return next(
            await actionWith(
              {
                ...failureType,
                payload: new RequestError('[RSAA].body function failed'),
                error: true
              },
              [action, getState()]
            )
          );
        }
      }

      // Process [RSAA].headers function
      if (typeof headers === 'function') {
        try {
          headers = headers(getState());
        } catch (e) {
          return next(
            await actionWith(
              {
                ...failureType,
                payload: new RequestError('[RSAA].headers function failed'),
                error: true
              },
              [action, getState()]
            )
          );
        }
      }

      // Process [RSAA].options function
      if (typeof options === 'function') {
        try {
          options = options(getState());
        } catch (e) {
          return next(
            await actionWith(
              {
                ...failureType,
                payload: new RequestError('[RSAA].options function failed'),
                error: true
              },
              [action, getState()]
            )
          );
        }
      }

      // We can now dispatch the request FSA
      if (
        typeof requestType.payload === 'function' ||
        typeof requestType.meta === 'function'
      ) {
        next(await actionWith(requestType, [action, getState()]));
      } else {
        next(requestType);
      }

      let res;
      try {
        // Make the API call
        res = await doFetch(endpoint, {
          ...options,
          method,
          body: body || undefined,
          credentials,
          headers: headers || {}
        });
      } catch (e) {
        // The request was malformed, or there was a network error
        return next(
          await actionWith(
            {
              ...failureType,
              payload: new RequestError(e.message),
              error: true
            },
            [action, getState()]
          )
        );
      }

      let isOk;
      try {
        isOk = ok(res);
      } catch (e) {
        return next(
          await actionWith(
            {
              ...failureType,
              payload: new InternalError('[RSAA].ok function failed'),
              error: true
            },
            [action, getState(), res]
          )
        );
      }

      // Process the server response
      if (isOk) {
        return next(await actionWith(successType, [action, getState(), res]));
      } else {
        return next(
          await actionWith(
            {
              ...failureType,
              error: true
            },
            [action, getState(), res]
          )
        );
      }
    })();
  };
}
42814
function login(options) {
  const defaultHost = options.host;
  return async function loginHandler(ctx) {
    const loginCallbackPath = options.loginCallbackPath;
    const loginPath = options.loginPath;
    // ctx.session should be exists
    if (ctx.session) {
      ctx.session.userauthLoginReferer = formatReferer(ctx, loginPath, options.rootPath);
      debug('set loginReferer into session: %s', ctx.session.userauthLoginReferer);
    }

    const host = defaultHost || ctx.host;
    const protocol = options.protocol || ctx.protocol;
    const currentURL = protocol + '://' + host + loginCallbackPath;
    const loginURL = options.loginURLFormatter(currentURL, options.rootPath, ctx);
    debug('login redrect to loginURL: %s', loginURL);
    redirect(ctx, loginURL);
  };
}
681826
function user_auth_request(options) {
  return function(req, res, next) {
    const { client, } = options;
    const service_name = client.service_name;
    req.controllerData = req.controllerData || {};
    // console.log('user_auth_request', { selectedUserAuthToken, client });
    if (!client.user_email) {
      next();
    } else if (selectedUserAuthToken[service_name] &&
      selectedUserAuthToken[service_name].extensionattributes &&
      selectedUserAuthToken[service_name].extensionattributes.passport[`oauth2client_${service_name}`] &&
      selectedUserAuthToken[service_name].extensionattributes.passport[`oauth2client_${service_name}`].accesstoken) {
      req.controllerData.authorization_header = 'Bearer ' + selectedUserAuthToken[service_name].extensionattributes.passport[`oauth2client_${service_name}`].accesstoken;
      next();
    } else {
      const coreDataModel = passportLocals.auth.getAuthCoreDataModel({ entitytype: client.user_entity_type, });

      coreDataModel.load({
        query: { email: client.user_email, },
      })
        .then(user => {
          // console.log({ user });
          selectedUserAuthToken[service_name] = user;
          if (user) {
            req.controllerData.authorization_header = 'Bearer ' + selectedUserAuthToken[service_name].extensionattributes.passport[`oauth2client_${service_name}`].accesstoken;
          }
          // console.log('req.controllerData.authorization_header', req.controllerData.authorization_header);
          next();
        })
        .catch(next);
    }
  };
}
270153
function register(server, options, next) {
	Schema.validate(options, function (error, config) {
		if (error) {
			next(error);
		} else {
			let methodsAsync = {};
			const dirs = config.methods;
			_.each(dirs, (dir) => {
				const relativePath = path.relative(__dirname, process.cwd() + '/' + dir);
				importDirectory(module, relativePath, {
					visit: function (obj) {
						if (!_.isUndefined(obj)) {
							let methods = _.isArray(obj) ? obj : [obj]; 
							_.each(methods, (method) => {
								if (_.isObject(method) && _.isFunction(method.method)) {
									const instance = _.clone(method);
									// store the oringial method
									const asyncMethod = method.method;
									// convert async function to normal thunky function
									instance.method = function (...args) {
										// the handler after function is called
										const after = args[args.length - 1];
										// call the async method, since asyn function return promise, use then and catch to handle result and error by handler
										asyncMethod.apply(this, args).then((result) => after(null, result)).catch((err) => after(err));
									};
									server.method(instance);
								}
							});
						}
					}
				});
			});
			_.each(server.methods, (method, name) => {
				methodsAsync[name] = function (...args) {
					// async function is a function return promise
					// convert back the async function
					return new Promise((resolve, reject) => {
						// call the thunky function
						server.methods[name].apply(server.methods, args.concat([(err, result) => {
							// reject if error exists, resolve if error not exists
							if (err) {
								reject(err);
							} else {
								resolve(result);
							}
						}]));
					});
				};
				// drop cache should also support async
				if (method.cache) {
					methodsAsync[name].cache = Promise.promisifyAll(method.cache);
				}
			});
			server.decorate('server', config.name, methodsAsync);
			next();
		}
	});
}
1113819
def middleware(func):
    
    @wraps(func)
    def parse(*args, **kwargs):
        """ get middleware from route, execute middleware in order """
        middleware = copy.deepcopy(kwargs['middleware'])
        kwargs.pop('middleware')
        if request.method == "OPTIONS":
            # return 200 json response for CORS
            return JsonResponse(200)
        if middleware is None:
            return func(*args, **kwargs)
        for mware in middleware:
            ware = mware()
            if ware.status is False:
                return ware.response
            return func(*args, **kwargs)
    return parse
877364
function () {
    _options.auth0 = merge(
      _options.auth0,
      {
        domain: process.env.AUTH0_DOMAIN,
        clientID: process.env.AUTH0_CLIENT_ID,
        clientSecret: process.env.AUTH0_CLIENT_SECRET
      }
    );
  }