Error when logging in on Forest with admin backend deployed on AWS in lambda function

Hi @Steve_Bunlon,

I do confirm that it was the issue.
Here is our app.js:

const express = require("express");
const requireAll = require("require-all");
const path = require("path");
const cookieParser = require("cookie-parser");
const bodyParser = require("body-parser");
const cors = require("cors");
const jwt = require("express-jwt");
const morgan = require("morgan");
const {
  ensureAuthenticated,
  PUBLIC_ROUTES,
} = require("forest-express-sequelize");

async function createApp() {
  const app = express();

  app.use(morgan("tiny"));
  app.use(bodyParser.json());
  app.use(bodyParser.urlencoded({ extended: false }));
  app.use(cookieParser());
  app.use(express.static(path.join(__dirname, "public")));

  let allowedOrigins = [/forestadmin\.com$/];

  if (process.env.CORS_ORIGINS) {
    allowedOrigins = allowedOrigins.concat(process.env.CORS_ORIGINS.split(","));
  }

  app.use(
    cors({
      origin: allowedOrigins,
      allowedHeaders: ["Authorization", "X-Requested-With", "Content-Type"],
      maxAge: 86400, // NOTICE: 1 day
      credentials: true,
    })
  );

  app.use(
    jwt({
      secret: process.env.FOREST_AUTH_SECRET,
      credentialsRequired: false,
    })
  );

  app.use("/forest", (request, response, next) => {
    if (PUBLIC_ROUTES.includes(request.url)) {
      return next();
    }
    return ensureAuthenticated(request, response, next);
  });

  requireAll({
    dirname: path.join(__dirname, "routes"),
    recursive: true,
    resolve: (Module) => app.use("/forest", Module),
  });

  const middlewares = requireAll({
    dirname: path.join(__dirname, "middlewares"),
    recursive: true,
    resolve: (Module) => Module(app),
  });

  await Promise.all(Object.keys(middlewares).map((key) => middlewares[key]));

  return app;
}

module.exports = createApp;

Here is our server.js:

require("dotenv").config();
const createApp = require("./app");
const debug = require("debug")("{name}:server");
const http = require("http");
const chalk = require("chalk");

function normalizePort(val) {
  const port = parseInt(val, 10);

  if (Number.isNaN(port)) {
    return val;
  }
  if (port >= 0) {
    return port;
  }

  return false;
}

async function createServer() {
  const port = normalizePort(
    process.env.PORT || process.env.APPLICATION_PORT || "3310"
  );

  const app = await createApp();
  app.set("port", port);

  const server = http.createServer(app);
  server.listen(port);

  function onError(error) {
    if (error.syscall !== "listen") {
      throw error;
    }

    const bind = typeof port === "string" ? `Pipe ${port}` : `Port ${port}`;

    switch (error.code) {
      case "EACCES":
        console.error(`${bind} requires elevated privileges`);
        process.exit(1);
        break;
      case "EADDRINUSE":
        console.error(`${bind} is already in use`);
        process.exit(1);
        break;
      default:
        throw error;
    }
  }

  function onListening() {
    const addr = server.address();
    const bind =
      typeof addr === "string" ? `pipe ${addr}` : `port ${addr.port}`;
    debug(`Listening on ${bind}`);

    console.log(chalk.cyan(`Your application is listening on ${bind}.`));
  }

  server.on("error", onError);
  server.on("listening", onListening);
}

createServer();

And as a bonus, here is our lambda.js (this is what is running on AWS lambda, we only use server,.js for local tests):

const awsServerlessExpress = require("aws-serverless-express");
const createApp = require("./app");

let app;
let server;

exports.handler = async (event, context) => {
  if (!app) {
    app = await createApp();
  }
  if (!server) {
    server = awsServerlessExpress.createServer(app);
  }
  return awsServerlessExpress.proxy(server, event, context, "PROMISE").promise;
};

2 Likes