express#NextFunction TypeScript Examples

The following examples show how to use express#NextFunction. 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: map-class.ts    From Discord-Bot-TypeScript-Template with MIT License 9 votes vote down vote up
export function mapClass(cls: ClassConstructor<object>): RequestHandler {
    return async (req: Request, res: Response, next: NextFunction) => {
        // Map to class
        let obj: object = plainToInstance(cls, req.body);

        // Validate class
        let errors = await validate(obj, {
            skipMissingProperties: true,
            whitelist: true,
            forbidNonWhitelisted: false,
            forbidUnknownValues: true,
        });
        if (errors.length > 0) {
            res.status(400).send({ error: true, errors: formatValidationErrors(errors) });
            return;
        }

        // Set validated class to locals
        res.locals.input = obj;
        next();
    };
}
Example #2
Source File: ensureAuthenticated.ts    From gobarber-api with MIT License 8 votes vote down vote up
export default function ensureAuthenticated(
  req: Request,
  res: Response,
  next: NextFunction,
): void {
  const authHeader = req.headers.authorization;

  if (!authHeader) {
    throw new AppError('JWT token is missing', 401);
  }

  const [, token] = authHeader.split(' ');

  try {
    const decoded = verify(token, authConfig.jwt.secret);

    const { sub } = decoded as ITokenPayload;

    req.user = {
      id: sub,
    };

    return next();
  } catch {
    throw new AppError('Invalid JWT token', 401);
  }
}
Example #3
Source File: resolver.ts    From one-platform with MIT License 7 votes vote down vote up
function resolver(req: Request, res: Response, next: NextFunction): void {
  const proxy = createProxyMiddleware({
    target: SPASHIP_ROUTER_HOST,
    secure: useSecureSSL,
    changeOrigin: true,
    toProxy: true,
    ignorePath: false,
    headers: {
      'X-OP-Authenticated': req.oidc.isAuthenticated() ? 'true' : 'false',
      ...(req.oidc.isAuthenticated() && {
        'X-OP-Auth-Token': req.oidc.accessToken?.access_token,
      }),
    },
    logProvider: logger.info,
  });

  proxy(req, res, next);
}
Example #4
Source File: server-utils.ts    From anthem with Apache License 2.0 7 votes vote down vote up
requestLogger = (
  req: Request,
  _: Response,
  next: NextFunction,
) => {
  if (ENV.ENABLE_LOGGING) {
    const { body } = req;
    const { operationName, variables } = body;

    // Don't log introspection query (clutter):
    if (Boolean(operationName) && operationName !== "IntrospectionQuery") {
      console.log(chalk.blue("Request Received:"));
      console.log(
        `- Query: ${operationName}\n- Variables: ${JSON.stringify(
          variables,
        )}\n`,
      );
    }
  }

  return next();
}
Example #5
Source File: helpers.ts    From End-to-End-Web-Testing-with-Cypress with MIT License 6 votes vote down vote up
ensureAuthenticated = (req: Request, res: Response, next: NextFunction) => {
  if (req.isAuthenticated()) {
    return next();
  }
  /* istanbul ignore next */
  res.status(401).send({
    error: "Unauthorized",
  });
}
Example #6
Source File: Handler.ts    From cyan with MIT License 6 votes vote down vote up
public static jsonBodyParser(options?: bodyParser.OptionsJson): HandlerFunction {
    const jsonParser = bodyParser.json(options);

    return (req: CyanRequest, res: CyanResponse, next: NextFunction) => {
      jsonParser(req as any, res as any, err => {
        // eslint-disable-line consistent-return
        if (err) {
          const respErr = new HttpError(HttpStatus.BadRequest, "The specified json body is invalid.");

          next(respErr);
          return;
        }

        next();
      });
    };
  }
Example #7
Source File: app.ts    From commercetools-sdk-typescript with MIT License 6 votes vote down vote up
// Global error handler
app.use(
  (
    error: ErrorRequestHandler,
    req: Request,
    res: Response,
    next: NextFunction
  ) => {
    // response to user with 403 error and details
    if (error) {
      next(error)
    } else {
      next()
    }
  }
)
Example #8
Source File: app.ts    From NextLevelWeek with MIT License 6 votes vote down vote up
/**
 * Tratando os erros.
 */
app.use((err: Error, req: Request, res: Response, _next: NextFunction) => {
    if (err instanceof AppError) {
        return res.status(err.statusCode).json({
            message: err.message,
        });
    }

    return res.status(500).json({
        status: "Error",
        message: `Internal server error ${err.message}`,
    });
});
Example #9
Source File: main.ts    From edu-server with MIT License 6 votes vote down vote up
async function bootstrap() {
  const app = await NestFactory.create(AppModule);

  // setup swagger-ui
  const document = SwaggerModule.createDocument(app, swaggerConfig);
  SwaggerModule.setup('api', app, document, customOptions);

  // Firebase Initialisation
  admin.initializeApp(firebaseAccountCredentials);

  app.enableCors();
  app.use(helmet());

  // The Cors handling middleware
  app.use((req: Request, res: Response, next: NextFunction) => {
    res.set('Access-Control-Allow-Origin', '*');
    res.set('Access-Control-Allow-Headers', '*');
    res.set('Access-Control-Allow-Methods', '*');
    if (req.method === 'OPTIONS') {
      res.status(200).end();
      return;
    }
    next();
  });
  app.useGlobalPipes(new ValidationPipe());

  const PORT = process.env.PORT || 5000;
  await app.listen(PORT);
  console.log('App is listening on port:', PORT);
}
Example #10
Source File: validateToken.ts    From IBM-HyperProtectMBaaS with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
validateToken = (req: Request, res: Response, next: NextFunction) => {
  const validTime = "1h"
 
  if (!req.headers.authorization) {
    return res.status(403).json({ error: 'No credentials sent!' });
  }

  //Get the jwt token from the header. Format --> Authorization: Bearer <token>
  const token = <string>req.get('authorization').split(' ')[1]
  console.log("Token : " + token)
  let jwtToken;

  try {
    jwtToken = <any>jwt.verify(token, config.get('jwtSecret'));
    res.locals.jwtToken = jwtToken;
  } catch (error) {
    //If token is not valid, respond with 401 (unauthorized)
    return res.status(401).send();
  }

  //The token is valid for 1 hour
  const { userId, username } = jwtToken;
  const newToken = jwt.sign({ userId, username }, config.get('jwtSecret'), {
    expiresIn: validTime
  });
  res.setHeader("token", newToken);

  next();
}
Example #11
Source File: auth.ts    From bitcoin-s-ts with MIT License 6 votes vote down vote up
verify = function(req: Request, res: Response, next: NextFunction) {
  // get token from request header
  const authHeader = req.headers["authorization"]
  if (authHeader) {
    // the request header contains the token "Bearer <token>", split the string and use the second value in the split array.
    const token = authHeader.split(" ")[1]

    jwt.verify(token, ACCESS_TOKEN_SECRET, (err: any, payload: any) => {
      if (err) { 
        res.status(403).send("Access Token Invalid")
      } else {
        // req.user = payload
        next() // proceed to the next action in the calling function
      }
    }) //end of jwt.verify()
  } else {
    res.status(401).send("No Authorization Header")
  }
}
Example #12
Source File: categories.middleware.ts    From budget-node with GNU General Public License v3.0 6 votes vote down vote up
export function categoryBelongsToAccount() {

  return function (req: Request, res: Response, next: NextFunction) {
    const user = req.user as User;
    const categoryId = req.params.id;

    if (!categoryId) {
      return next();
    }

    repository.getCategory(categoryId).then(category => {
      if (category.accountId === user.accountId) {
        return next();
      } else {
        res.status(401).json({ error: 'You are not authorized to perform this operation' });
        return next('Unauthorized');
      }
    }).catch(() => res.sendStatus(404));
  }

}
Example #13
Source File: statusCheckHandler.ts    From backstage with Apache License 2.0 6 votes vote down vote up
/**
 * Express middleware for status checks.
 *
 * This is commonly used to implement healthcheck and readiness routes.
 *
 * @public
 * @param options - An optional configuration object.
 * @returns An Express error request handler
 */
export async function statusCheckHandler(
  options: StatusCheckHandlerOptions = {},
): Promise<RequestHandler> {
  const statusCheck: StatusCheck = options.statusCheck
    ? options.statusCheck
    : () => Promise.resolve({ status: 'ok' });

  return async (_request: Request, response: Response, next: NextFunction) => {
    try {
      const status = await statusCheck();
      response.status(200).header('').send(status);
    } catch (err) {
      next(err);
    }
  };
}
Example #14
Source File: logger.ts    From TXQ with MIT License 6 votes vote down vote up
HandleLogger = (router: Router) => {
  if (!config.logs.logRequestsEnabled) {
    logger.debug('Request logging not activated');
  }
  let count = 0;
  router.use((req: Request, res: Response, next: NextFunction) => {
    req.logData = {
      method: req.method,
      url: req.originalUrl,
      query: JSON.stringify(req.query),
      body: 'hidden',
      reqid: ++count,
      ip: req.ip,
    };
    logger.info('request', req.logData);
    next();
  });
}
Example #15
Source File: validation.middleware.ts    From server-api with Apache License 2.0 6 votes vote down vote up
/**
 * Validate RequestBody and sent AsyncAPI document(s) for given path and method based on the OpenAPI Document.
 */
export async function validationMiddleware(options: ValidationMiddlewareOptions) {
  options.version = options.version || 'v1';
  const validate = await compileAjv(options);
  const documents = options.documents;

  return async function (req: Request, _: Response, next: NextFunction) {
    // validate request body
    try {
      await validateRequestBody(validate, req.body);
    } catch (err: unknown) {
      return next(err);
    }

    // validate AsyncAPI document(s)
    const parserConfig = prepareParserConfig(req);
    try {
      req.asyncapi = req.asyncapi || {};
      for (const field of documents) {
        const body = req.body[String(field)];
        if (Array.isArray(body)) {
          const parsed = await validateListDocuments(body, parserConfig);
          req.asyncapi.parsedDocuments = parsed;
        } else {
          const parsed = await validateSingleDocument(body, parserConfig);
          req.asyncapi.parsedDocument = parsed;
        }
      }

      next();
    } catch (err: unknown) {
      return next(tryConvertToProblemException(err));
    }
  };
}
Example #16
Source File: RemixController.ts    From remix-hexagonal-architecture with MIT License 6 votes vote down vote up
@All("*")
  handler(
    @Req() request: Request,
    @Res() response: Response,
    @Next() next: NextFunction,
    @Body() body: any
  ) {
    if (this.isStaticAsset(request)) return next();
    this.purgeRequireCacheInDev();

    return createRequestHandler({
      // `remix build` and `remix dev` output files to a build directory, you need
      // to pass that build to the request handler
      build: require(this.remixHandlerPath),

      // return anything you want here to be available as `context` in your
      // loaders and actions. This is where you can bridge the gap between Remix
      // and your server
      getLoadContext: () => ({
        actions: this.actions,
        loaders: this.loaders,
      }),
    })(request, response, next);
  }
Example #17
Source File: routes.tsx    From react-app-architecture with Apache License 2.0 6 votes vote down vote up
async function sendBlogsPage(req: PublicRequest, res: Response, next: NextFunction) {
  try {
    const response = await publicRequest<null, Array<Blog>>({
      url: 'blogs/latest',
      method: 'GET',
      params: { pageNumber: 1, pageItemCount: 1000 },
    });
    res.send(
      pageBuilder(
        req,
        {
          title: 'AfterAcademy | Open Source Blogs',
          description:
            'AfterAcademy open source blogs and articles with latest developments and trends',
        },
        {
          blogListState: {
            ...blogListDefaultState,
            isFetching: false,
            data: response.data ? response.data : null,
          },
        },
      ),
    );
  } catch (e) {
    next(e);
  }
}
Example #18
Source File: app.ts    From nodejs-backend-architecture-typescript with Apache License 2.0 6 votes vote down vote up
// Middleware Error Handler
// eslint-disable-next-line @typescript-eslint/no-unused-vars
app.use((err: Error, req: Request, res: Response, next: NextFunction) => {
  if (err instanceof ApiError) {
    ApiError.handle(err, res);
  } else {
    if (environment === 'development') {
      Logger.error(err);
      return res.status(500).send(err.message);
    }
    ApiError.handle(new InternalError(), res);
  }
});
Example #19
Source File: middleware.ts    From your_spotify with GNU General Public License v3.0 6 votes vote down vote up
withGlobalPreferences = async (req: Request, res: Response, next: NextFunction) => {
  try {
    const pref = await getGlobalPreferences();
    if (!pref) {
      logger.error('No global preferences, this is critical, try restarting the app');
      return;
    }
    (req as GlobalPreferencesRequest).globalPreferences = pref;
    return next();
  } catch (e) {
    return res.status(500).end();
  }
}
Example #20
Source File: security.ts    From vue-element-typescript-admin with MIT License 6 votes vote down vote up
accessTokenAuth = (req: Request, res: Response, next: NextFunction) => {
  const accessToken = req.header('X-Access-Token')
  if (!accessToken) {
    return res.status(401).json({
      code: 50001,
      message: 'Invalid Access Token'
    })
  }
  next()
}
Example #21
Source File: index.ts    From Dimensions with MIT License 6 votes vote down vote up
/**
 * POST
 *
 * Create queued matches
 */
router.post(
  '/:tournamentID/match-queue/',
  requireAdmin,
  async (req: Request, res: Response, next: NextFunction) => {
    if (!req.body.matchQueue)
      return next(new error.BadRequest('Missing matchQueue field'));
    if (!req.body.matchQueue.length)
      return next(new error.BadRequest('Must provide an array'));
    if (req.data.tournament.type === Tournament.Type.LADDER) {
      const t = <Tournament.Ladder>req.data.tournament;
      t.scheduleMatches(...req.body.matchQueue);
      res.json({
        error: null,
        message: `Queued ${req.body.matchQueue.length} matches`,
      });
    }
  }
);
Example #22
Source File: app.ts    From ecoleta with MIT License 6 votes vote down vote up
app.use((err: Error, request: Request, response: Response, _: NextFunction) => {
  if (err instanceof AppError) {
    return response.status(err.statusCode).json({
      status: 'error',
      message: err.message,
    });
  }

  console.log(err);

  return response.status(500).json({
    status: 'error',
    message: 'Internal server error',
  });
});
Example #23
Source File: Request.ts    From hypixel-skyblock-facade with MIT License 6 votes vote down vote up
/**
 * Runs an async function and catches the errors thrown in it
 * and returns them to the Express error handler.
 *
 * @param fn The function that should be handled asynchronously
 */
export function asyncWrap(fn: RequestHandler) {
  return (request: Request, response: Response, next: NextFunction) => {
    return Promise.resolve(fn(request, response, next)).catch(next)
  }
}
Example #24
Source File: logger.middleware.spec.ts    From whispr with MIT License 6 votes vote down vote up
describe('Logger Middleware', () => {
  it('log should hide token', () => {
    expect(headersToString({ atest: 'aValue', authorization: 'Bearer thatShouldBeHidden' })).toBe(
      '{"atest":"aValue","authorization":"[HIDDEN size=25]"}',
    );
  });
  it('middleware should let go through', () => {
    const next = jest.fn() as unknown as NextFunction;
    const res = jest.fn() as unknown as Response;

    const req = { headers: { atest: 'aValue', authorization: 'Bearer thatShouldBeHidden' } } as unknown as Request;
    logger(req, res, next);
    expect(next).toHaveBeenCalled();
  });
});
Example #25
Source File: metricsRouter.ts    From paystring with Apache License 2.0 6 votes vote down vote up
/**
 * Routes for the metrics report generated by Prometheus.
 */
metricsRouter
  .get('/', (_req: Request, res: Response, next: NextFunction): void => {
    res.set('Content-Type', 'text/plain')
    res.send(metrics.getMetrics())
    return next()
  })

  // Error handling middleware needs to be defined last
  .use(errorHandler)
Example #26
Source File: helpers.ts    From End-to-End-Web-Testing-with-Cypress with MIT License 6 votes vote down vote up
validateMiddleware = (validations: any[]) => {
  return async (req: Request, res: Response, next: NextFunction) => {
    await Promise.all(validations.map((validation: any) => validation.run(req)));

    const errors = validationResult(req);
    if (errors.isEmpty()) {
      return next();
    }

    res.status(422).json({ errors: errors.array() });
  };
}
Example #27
Source File: resolver.ts    From one-platform with MIT License 6 votes vote down vote up
export default function resolver(
  req: Request,
  res: Response,
  next: NextFunction
): void {
  const { uid, role, rhatUUID } = res.locals.user;

  /* Adding additional roles */
  role.push('user:' + uid, 'user:' + rhatUUID, 'op-users');

  const token = createHmac('sha1', COUCHDB_SECRET as string)
    .update(uid) // lgtm[js/weak-cryptographic-algorithm]
    .digest('hex');

  const proxy = createProxyMiddleware({
    target: COUCHDB_HOST,
    secure: useSecureSSL,
    changeOrigin: true,
    headers: {
      'X-Auth-CouchDB-UserName': uid,
      'X-Auth-CouchDB-Roles': role.join(','),
      'X-Auth-CouchDB-Token': token,
    },
    pathRewrite: {
      ['^/api/couchdb']: '',
    },
  });
  proxy(req, res, next);
}
Example #28
Source File: user.ts    From dropify with MIT License 6 votes vote down vote up
allowPermissionTo = (...roles: string[]) => {
  // roles = ["user","manager","admin", ...etc] , role="user" || "manager" || "admin"
  // roles = ["user","manager"] , role="user" || "manager"
  return (req: Request, _: Response, next: NextFunction) => {
    if (req.user.role && !roles.includes(req.user.role)) {
      return next(
        new ErrorResponse(`user don't have permision to perform this task`, 403)
      );
    }
    next();
  };
}
Example #29
Source File: app.ts    From rocketseat-gostack-11-desafios with MIT License 6 votes vote down vote up
app.use((err: Error, request: Request, response: Response, _: NextFunction) => {
  if (err instanceof AppError) {
    return response.status(err.statusCode).json({
      status: 'error',
      message: err.message,
    });
  }

  console.error(err);

  return response.status(500).json({
    status: 'error',
    message: 'Internal server error',
  });
});