express#Application TypeScript Examples

The following examples show how to use express#Application. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: server.ts    From TypeScript-in-Nodejs-Starter with MIT License 6 votes vote down vote up
/**
 * Adds a set of middleware only if the app runs on the production machine.
 * @param app The express application to add the set of production middleware to it.
 */
function setupProduction(app: Application): void {
  /* Only if the app runs on the production machine. */
  if (process.env.NODE_ENV === 'production') {
    /* Helmet helps you secure your Express apps by setting various HTTP headers. It's not a silver bullet, but it can help! */
    app.use(helmet());

    /* Gzip compressing can greatly decrease the size of the response body and hence increase the speed of a web app.
     * Use the compression middleware for gzip compression in your Express app.
     */
    app.use(compression());
  }
}
Example #2
Source File: oauth_routes.ts    From Deep-Lynx with MIT License 6 votes vote down vote up
public static mount(app: Application, middleware: any[]) {
        // OAuth application management
        app.get('/oauth/applications/create', csurf(), ...middleware, LocalAuthMiddleware, this.createOAuthApplicationPage);
        app.post('/oauth/applications', csurf(), ...middleware, LocalAuthMiddleware, this.createOAuthApplication);
        app.get('/oauth/applications', csurf(), ...middleware, LocalAuthMiddleware, this.listOAuthApplications);
        app.get('/oauth/applications/:oauthAppID', ...middleware, csurf(), LocalAuthMiddleware, this.oauthApplicationPage);
        app.put('/oauth/applications/:oauthAppID', ...middleware, csurf(), LocalAuthMiddleware, this.updateOAuthApplication);
        app.delete('/oauth/applications/:oauthAppID', ...middleware, csurf(), LocalAuthMiddleware, this.deleteOAuthApplication);

        // login, register and authorize
        app.get('/oauth', csurf(), this.loginPage);
        app.get('/logout', this.logout);
        app.post('/oauth', csurf(), LocalAuthMiddleware, this.login);

        // saml specific
        app.get('/login-saml', this.loginSaml);
        app.post('/oauth/saml', this.saml);

        app.get('/oauth/register', csurf(), this.registerPage);
        app.post('/oauth/register', csurf(), this.createNewUser);

        app.get('/oauth/authorize', csurf(), LocalAuthMiddleware, this.authorizePage);
        app.post('/oauth/authorize', csurf(), LocalAuthMiddleware, this.authorize);
        app.post('/oauth/exchange', this.tokenExchange);
        app.get('/oauth/token', this.getToken);

        // profile management and email validation/reset password
        app.get('/oauth/profile', csurf(), LocalAuthMiddleware, this.profile);
        app.post('/oauth/profile/keys', csurf(), LocalAuthMiddleware, this.generateKeyPair);
        app.delete('/oauth/profile/keys/:keyID', csurf(), LocalAuthMiddleware, this.deleteKeyPair);

        app.get('/validate-email', this.validateEmail);

        app.get('/reset-password', csurf(), this.resetPasswordPage);
        app.post('/reset-password', csurf(), this.initiatePasswordReset);
        app.post('/reset-password/reset', csurf(), this.resetPassword);
    }
Example #3
Source File: app.ts    From kfp-tekton-backend with Apache License 2.0 6 votes vote down vote up
function getRegisterHandler(app: Application, basePath: string) {
  return (
    func: (name: string | string[], handler: express.Handler) => express.Application,
    route: string | string[],
    handler: express.Handler,
  ) => {
    func.call(app, route, handler);
    return func.call(app, `${basePath}${route}`, handler);
  };
}
Example #4
Source File: index.ts    From tinyhouse with MIT License 6 votes vote down vote up
async function mount(app: Application) {
    const db = await connectDatabase();

    app.use(cookieParser(process.env.SECRET));

    const server = new ApolloServer({
        typeDefs,
        resolvers,
        context: ({ req, res }) => ({ db, req, res }),
    });
    await server.start();
    server.applyMiddleware({ app, path: "/api" });

    app.listen(port);

    console.log(`[app]: http://localhost:${port}`);
}
Example #5
Source File: swagger.ts    From monkeytype with GNU General Public License v3.0 6 votes vote down vote up
function addSwaggerMiddlewares(app: Application): void {
  app.use(
    swaggerStats.getMiddleware({
      name: "Monkeytype API",
      uriPath: "/stats",
      authentication: process.env.MODE !== "dev",
      apdexThreshold: 100,
      swaggerSpec: internalSwaggerSpec,
      onAuthenticate: (_req, username, password) => {
        return (
          username === process.env.STATS_USERNAME &&
          password === process.env.STATS_PASSWORD
        );
      },
      onResponseFinish: (_req, res, rrr) => {
        //@ts-ignore ignored because monkeyMessage doesnt exist in response
        rrr.http.response.message = res.monkeyMessage;
        if (process.env.MODE === "dev") {
          return;
        }
        const authHeader = rrr.http.request.headers?.authorization ?? "None";
        const authType = authHeader.split(" ");
        _.set(rrr.http.request, "headers.authorization", authType[0]);
        _.set(rrr.http.request, "headers['x-forwarded-for']", "");
      },
    })
  );

  app.use(
    ["/documentation", "/docs"],
    swaggerUi.serve,
    swaggerUi.setup(publicSwaggerSpec, SWAGGER_UI_OPTIONS)
  );
}
Example #6
Source File: auth.service.ts    From relate with GNU General Public License v3.0 6 votes vote down vote up
register(httpAdapter: AbstractHttpAdapter): void {
        if (!httpAdapter) {
            return;
        }

        const app: Application = httpAdapter.getInstance();

        this.registerAuthenticationHandlers(app);
    }
Example #7
Source File: setupDev.ts    From graphql-schema-registry with MIT License 6 votes vote down vote up
export default async function setupDev(app: Application) {
	const { default: webpackConfig } = await import(WEBPACK_FILE_LOCATION);
	const compiler = webpack(webpackConfig as webpack.Configuration);
	app.use(
		webpackDevMiddleware(compiler, {
			writeToDisk: true,
			publicPath: webpackConfig.output.publicPath,
		})
	);

	app.use(
		//  `webpack-hot-middleware` currently does not work reliably with Webpack 5:
		//  Ref: https://github.com/webpack-contrib/webpack-hot-middleware/pull/397
		webpackHotMiddleware(compiler, {
			log: false,
			path: `/__webpack_hmr`,
			heartbeat: 10 * 1000,
		})
	);
}
Example #8
Source File: social-auth.service.ts    From nestjs-angular-starter with MIT License 6 votes vote down vote up
constructor(
    @Inject('SOCIAL_AUTH_MODULE_CONFIG') private config: SocialAuthModuleConfig,
    adapterHost: HttpAdapterHost,
  ) {
    // Don't do anything on test as there is not instance of express
    if (appConfig.ENVIRONMENT === 'test') return;

    let expressApp: Application;

    try {
      // Get the express app in order to initialize social authentication
      expressApp = adapterHost.httpAdapter.getInstance() as Application;
    } catch (error) {
      // Fail with an error but continue
      Logger.error(error);
    }

    if (!expressApp)
      // TODO: This should throw an error instead
      Logger.warn(
        "Social authentication is not supported, couldn't get handle of express!",
      );
    else {
      // Now initialize the social authentication
      this.init(expressApp);
    }
  }
Example #9
Source File: index.ts    From lighthouse-audit-service with Apache License 2.0 6 votes vote down vote up
function configureMiddleware(
  app: Application,
  options: LighthouseAuditServiceOptions,
) {
  if (options.cors) {
    app.use(corsMiddleware());
  }
  app.use(compression());
  app.use(bodyParser.json());
  app.use(
    morgan('combined', {
      stream: {
        write(message: String) {
          logger.info(message);
        },
      },
    }),
  );
}
Example #10
Source File: bootstrap.ts    From spurtcommerce with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
bootstrapApp = async (): Promise<BootstrapSettings> => {
    const framework = await bootstrapMicroframework({
        loaders: [
            winstonLoader,
            iocLoader,
            eventDispatchLoader,
            typeormLoader,
            expressLoader,
            homeLoader,
        ],
    });
    return {
        app: framework.settings.getData('express_app') as Application,
        server: framework.settings.getData('express_server') as http.Server,
        connection: framework.settings.getData('connection') as Connection,
    } as BootstrapSettings;
}
Example #11
Source File: index.ts    From cookietrack-api with MIT License 5 votes vote down vote up
app: Application = express()
Example #12
Source File: app.ts    From TypeScript-in-Nodejs-Starter with MIT License 5 votes vote down vote up
app: Application = express()
Example #13
Source File: server.ts    From reactive-angular-course with MIT License 5 votes vote down vote up
app: Application = express()
Example #14
Source File: expressMiddleware.ts    From ts-di-starter with MIT License 5 votes vote down vote up
/**
   * Attach express middleware to app
   *
   * @param {app} app
   * @param {object} middleware
   * @param {object} controllers
   * @returns {void}
   */
  static attach(app: Application, middleware: ExpressMiddlewareInterface, controllers: ExpressControllersInterface): void {
    if (!isObject(app) || !isObject(middleware) || !isObject(controllers)) {
      throw new Err('must have app, middleware, and controllers');
    }

    // app.use(logger);
    app.use(defaultContentTypeMiddleware);

    app.use(middleware.logger.log);
    app.use(compression());
    app.use(
      bodyParser.json({
        limit: '50mb',
        verify: rawBodyVerify,
      })
    );
    app.use(bodyParser.urlencoded({ extended: true, verify: rawBodyVerify }));
    app.use(methodOverride());
    app.use(cookieParser());
    app.use(
      cors({
        exposedHeaders: ['demo-id', 'Date', 'ETag', 'timestamp', 'x-ratelimit-reset', 'x-ratelimit-remaining', 'x-ratelimit-limit', 'retry-after'],
      })
    );
    app.use((request, response, next) => {
      const token = request.get('authorization')?.replace(/^bearer(:)?\s+/i, '');
      if (token) {
        (request as any).token = token;
      }

      next();
    });
    app.enable('trust proxy');
    app.disable('x-powered-by');

    const haltOnTimedout = (req, res, next): void => !req.timedout && next();

    app.use(timeout(REQ_TIMEOUT_SEC));
    app.use(haltOnTimedout);

    app.use(async (err, req, res, next) => middleware.exceptionHandler.handleJsonParseError(err, req, res, next));

    // Set timestamp on response to calibrate client time
    app.use((request, response, next) => {
      response.set('timestamp', `${DateTime.utc().valueOf()}`);
      next();
    });

    // Add locals, so we don't have to check everywhere
    app.use((request, response, next) => {
      (request as any).locals = { ...(request as any).locals };
      next();
    });

    // All valid routes handled here
    app.use(api(middleware, controllers));

    // Handle errors that are otherwise unhandled for some reason
    app.use(async (err, req, res, next) => middleware.exceptionHandler.handleError(err, req, res, next));

    // Everything else is a 404
    app.use(async (req, res) => middleware.exceptionHandler.handleNotFound(req, res));
  }
Example #15
Source File: server.ts    From hadith-api with MIT License 5 votes vote down vote up
private application: Application
Example #16
Source File: app.ts    From speedy-im with MIT License 5 votes vote down vote up
app: Application = express()
Example #17
Source File: v1.ts    From hoprnet with GNU General Public License v3.0 5 votes vote down vote up
export function setupRestApi(
  service: Application,
  urlPath: string,
  node: Hopr,
  logs: LogStream,
  stateOps: StateOps,
  options: any
) {
  const router = express.Router()

  router.use(bodyParser.text({ type: '*/*' }))

  router.get('/version', (_, res) => res.send(node.getVersion()))
  router.get('/address/eth', (_, res) => res.send(node.getEthereumAddress().toHex()))
  router.get('/address/hopr', (_, res) => res.send(node.getId().toB58String()))

  const cmds = new Commands(node, stateOps)
  router.post('/command', async (req, res) => {
    await node.waitForRunning()
    logs.log('Node is running')
    if (!options.testNoAuthentication && options.apiToken !== undefined) {
      if (req.headers['x-auth-token'] !== options.apiToken) {
        logs.log('command rejected: authentication failed')
        res.status(403).send('authentication failed')
        return
      }
      logs.log('command accepted: authentication succeeded')
    } else {
      logs.log('command accepted: authentication DISABLED')
    }

    let response = ''
    let log = (s) => {
      response += s
      logs.log(s)
    }
    logs.log('executing API command', req.body, node.status)
    await cmds.execute(log, req.body)
    logs.log('command complete')
    res.send(response)
  })

  service.use(urlPath, router)
}
Example #18
Source File: user_routes.ts    From Deep-Lynx with MIT License 5 votes vote down vote up
public static mount(app: Application, middleware: any[]) {
        app.get('/users', ...middleware, authRequest('read', 'users'), this.listUsers);
        app.get('/users/permissions', ...middleware, this.listUserPermissions);
        app.delete('/users/:userID', middleware, authRequest('write', 'users'), this.deleteUser);
        app.put('/users/:userID', ...middleware, authRequest('write', 'users'), this.updateUser);

        // current user key/pair management
        app.get('/users/keys', ...middleware, this.listKeyPairs);
        app.post('/users/keys', ...middleware, this.generateKeyPair);
        app.delete('/users/keys/:keyID', ...middleware, this.deleteKeyPair);

        app.get('/users/invite', ...middleware, this.acceptContainerInvite);
        app.get('/users/invites', ...middleware, this.listOutstandingInvites);

        // this endpoint will return all users of the application, not users who have permissions in the container
        // we use the container to make sure the requester has permissions to view all users, but this could be
        // a little confusing
        app.get('/containers/:containerID/users', ...middleware, authInContainer('read', 'users'), this.listUsersForContainer);
        app.get('/containers/:containerID/users/:userID', ...middleware, authInContainer('read', 'users'), this.retrieveUser);

        app.post('/containers/:containerID/users/roles', ...middleware, authInContainer('write', 'users'), this.assignRole);
        app.get('/containers/:containerID/users/:userID/roles', ...middleware, authInContainer('read', 'users'), this.listUserRoles);

        app.post('/containers/:containerID/users/invite', ...middleware, authInContainer('write', 'users'), this.inviteUserToContainer);
        app.get('/containers/:containerID/users/invite', ...middleware, authInContainer('read', 'users'), this.listInvitedUsers);

        app.get('/containers/:containerID/service-users', ...middleware, authInContainer('read', 'users'), this.listServiceUsersForContainer);
        app.post('/containers/:containerID/service-users', ...middleware, authInContainer('write', 'users'), this.createServiceUserForContainer);
        app.delete(
            '/containers/:containerID/service-users/:serviceUserID',
            ...middleware,
            authInContainer('write', 'users'),
            this.deleteServiceUserForContainer,
        );
        app.get(
            '/containers/:containerID/service-users/:serviceUserID/permissions',
            ...middleware,
            authInContainer('read', 'users'),
            this.listServiceUserPermissions,
        );
        app.put(
            '/containers/:containerID/service-users/:serviceUserID/permissions',
            ...middleware,
            authInContainer('write', 'users'),
            this.setServiceUserPermissions,
        );

        app.get(
            '/containers/:containerID/service-users/:serviceUserID/keys',
            ...middleware,
            authInContainer('write', 'users'),
            this.listKeyPairsForServiceUser,
        );
        app.post(
            '/containers/:containerID/service-users/:serviceUserID/keys',
            ...middleware,
            authInContainer('write', 'users'),
            this.generateKeyPairForServiceUser,
        );
        app.delete(
            '/containers/:containerID/service-users/:serviceUserID/keys/:keyID',
            ...middleware,
            authInContainer('write', 'users'),
            this.deleteKeyPairForServiceUser,
        );
    }
Example #19
Source File: app.ts    From cloud-pricing-api with Apache License 2.0 5 votes vote down vote up
async function createApp(opts: ApplicationOptions = {}): Promise<Application> {
  const app = express();

  const logger = opts.logger || config.logger;

  if (!opts.disableRequestLogging) {
    app.use(
      pinoHttp({
        logger,
        customLogLevel(res, err) {
          if (err || res.statusCode === 500) {
            return 'error';
          }
          return 'info';
        },
        autoLogging: {
          ignorePaths: ['/health'],
        },
      })
    );
  }

  if (!opts.disableStats) {
    app.use(express.static(path.join(__dirname, 'public')));
    app.set('views', path.join(__dirname, 'views'));
    app.set('view engine', 'ejs');
    app.use(home);
  }

  app.use(express.json());
  app.use(
    (err: ResponseError, _req: Request, res: Response, next: NextFunction) => {
      if (err instanceof SyntaxError && err.status === 400) {
        res.status(400).send({ error: 'Bad request' });
      } else {
        next();
      }
    }
  );

  if (!opts.disableRequestLogging) {
    app.use((req: Request, _res: Response, next: NextFunction) => {
      if (!['/health', '/graphql'].includes(req.path)) {
        logger.debug({ body: req.body });
      }
      next();
    });
  }

  app.use(health);

  if (!opts.disableAuth) {
    app.use(auth);
  }

  if (!opts.disableStats) {
    app.use(events);
    app.use(stats);
  }

  const apolloConfig: ApolloServerExpressConfig = {
    schema: makeExecutableSchema({
      typeDefs,
      resolvers,
    }),
    introspection: true,
    plugins: [
      ApolloServerPluginLandingPageGraphQLPlayground(),
      () => new ApolloLogger(logger),
    ],
    ...opts.apolloConfigOverrides,
  };

  const apollo = new ApolloServer(apolloConfig);
  await apollo.start();

  apollo.applyMiddleware({ app });

  return app;
}
Example #20
Source File: Container.ts    From pdf-generator-service with MIT License 5 votes vote down vote up
public static async factory(app: Application): Promise<Container> {
    const container = new Container(app)
    await wire(container)
    return container
  }
Example #21
Source File: socket.ts    From foodie with MIT License 5 votes vote down vote up
export default function (app: Application, server: Server) {
    const io = require('socket.io')(server, {
        cors: {
            origin: config.cors.origin || 'http://localhost:3000',
            methods: ["GET", "POST", "PATCH"],
            credentials: true
        }
    });

    app.set('io', io);

    io.on("connection", (socket: SocketIO.Socket) => {
        socket.on("userConnect", (id) => {
            User
                .findById(id)
                .then((user) => {
                    if (user) {
                        socket.join(user._id.toString());
                        console.log('Client connected.');
                    }
                })
                .catch((e) => {
                    console.log('Invalid user ID, cannot join Socket.');
                });
        });

        socket.on("userDisconnect", (userID) => {
            socket.leave(userID);
            console.log('Client Disconnected.');
        });

        socket.on("onFollowUser", (data) => {
            console.log(data);
        });

        socket.on("user-typing", ({ user, state }) => {
            io.to(user.id).emit("typing", state)
        })

        socket.on("disconnect", () => {
            console.log('Client disconnected');
        });
    });
}
Example #22
Source File: app.ts    From kfp-tekton-backend with Apache License 2.0 5 votes vote down vote up
app: Application;
Example #23
Source File: setup-app.ts    From clean-architecture-api-boilerplate with MIT License 5 votes vote down vote up
setupApp = (app: Application): void => {
  app.set('trust proxy', 1); // you may change this depending on you setup
}
Example #24
Source File: app.ts    From expresso with MIT License 5 votes vote down vote up
private readonly application: Application
Example #25
Source File: index.ts    From monkeytype with GNU General Public License v3.0 5 votes vote down vote up
function addApiRoutes(app: Application): void {
  app.get("/leaderboard", (_req, res) => {
    res.sendStatus(404);
  });

  addSwaggerMiddlewares(app);

  app.use(
    (req: MonkeyTypes.Request, res: Response, next: NextFunction): void => {
      const inMaintenance =
        process.env.MAINTENANCE === "true" || req.ctx.configuration.maintenance;

      if (inMaintenance) {
        res.status(503).json({ message: "Server is down for maintenance" });
        return;
      }

      if (req.path === "/psas") {
        const clientVersion = req.headers["client-version"];
        recordClientVersion(clientVersion?.toString() ?? "unknown");
      }

      next();
    }
  );

  app.get(
    "/",
    asyncHandler(async (_req, _res) => {
      return new MonkeyResponse("ok", {
        uptime: Date.now() - APP_START_TIME,
        version,
      });
    })
  );

  app.get("/psa", (_req, res) => {
    res.json([
      {
        message:
          "It seems like your client version is very out of date as you're requesting an API endpoint that no longer exists. This will likely cause most of the website to not function correctly. Please clear your cache, or contact support if this message persists.",
        sticky: true,
      },
    ]);
  });

  _.each(API_ROUTE_MAP, (router: Router, route) => {
    const apiRoute = `${BASE_ROUTE}${route}`;
    app.use(apiRoute, router);
  });

  app.use(
    asyncHandler(async (req, _res) => {
      return new MonkeyResponse(
        `Unknown request URL (${req.method}: ${req.path})`,
        null,
        404
      );
    })
  );
}
Example #26
Source File: auth.service.ts    From relate with GNU General Public License v3.0 5 votes vote down vote up
registerAuthenticationHandlers(app: Application): void {
        app.get(AUTHENTICATION_ENDPOINT, async (req, res): Promise<void> => {
            const environment = await this.systemProvider.getEnvironment();
            const redirectTo = Str.from(req.query.redirectTo).toString();

            try {
                const {authUrl} = await environment.login(redirectTo);

                res.redirect(authUrl);
            } catch (e) {
                res.status(403);
                res.send(e.message);
            }
        });

        app.get(VALIDATION_ENDPOINT, async (req, res): Promise<void> => {
            const queryObject = req.query;

            if (queryObject.error) {
                res.status(401);
                res.send(`Login failed: ${queryObject.error}`);
                return;
            }

            try {
                const environment = await this.systemProvider.getEnvironment();
                const authToken = await environment.generateAuthToken(queryObject);

                // @todo: use signed cookies
                res.cookie(AUTH_TOKEN_HEADER, authToken);
                res.header(AUTH_TOKEN_HEADER, authToken);

                // @todo: this is Google OAuth specific
                if (queryObject.state) {
                    const state = Str.from(queryObject.state).toString();
                    res.redirect(getAuthRedirect(environment.httpOrigin, state, authToken));
                    return;
                }

                res.status(201);
                res.send('You are authenticated, you can close this tab now.');
            } catch (e) {
                res.status(403);
                res.send(e.message);
            }
        });

        app.get(VERIFICATION_ENDPOINT, async (req, res): Promise<void> => {
            const authToken = getRequestToken(req, AUTH_TOKEN_HEADER);
            const environment = await this.systemProvider.getEnvironment();

            try {
                await environment.verifyAuthToken(authToken);
                res.sendStatus(200);
            } catch (e) {
                res.clearCookie(AUTH_TOKEN_HEADER);
                res.status(403);
                res.send(e.message);
            }
        });
    }
Example #27
Source File: server.ts    From server with MIT License 5 votes vote down vote up
app: Application = express()
Example #28
Source File: BaseApi.ts    From node-boilerplate with Apache License 2.0 5 votes vote down vote up
public abstract register(express: Application): void;
Example #29
Source File: social-auth.service.ts    From nestjs-angular-starter with MIT License 5 votes vote down vote up
private init(express: Application): void {
    express.use(passport.initialize());
    this.initFacebook();
    this.initGoogle();
  }