'use strict';

// Load environment variables from .env file, where API keys and passwords are configured.
require('dotenv').config();
const configureI18n = require('./config/i18n');
const bluebird = require('bluebird');

process.env.NODE_ENV = process.env.NODE_ENV || 'development';
global.Promise = bluebird;

const { is } = require('ramda');
const express = require('express');
const compression = require('compression');
const bodyParser = require('body-parser');
const logger = require('morgan');
const lusca = require('lusca');
const gstore = require('gstore-node');
const { ValidationError, ValidatorError } = require('gstore-node/lib/error');
const passport = require('passport');
const expressValidator = require('express-validator');
const multer = require('multer');

require('./config/cloudinary')();
const authentication = require('./config/authentication');
const responseError = require('./utils/responseError');

/**
 * Controllers (route handlers).
 */
const homeController = require('./controllers/home');
const usersController = require('./controllers/users');
const beneficiariesController = require('./controllers/beneficiaries');
const projectsController = require('./controllers/projects');
const eventsController = require('./controllers/events');
const coursesController = require('./controllers/courses');

const datastore = require('./config/datastore');

/**
 * Create Express server.
 */
const app = express();

/**
 * Connect to Datastore
 */
gstore.connect(datastore);

/**
 * Express configuration.
 */
configureI18n(app);
if (process.env.NODE_ENV !== 'test') {
  app.use(logger(process.env.NODE_ENV === 'development' ? 'dev' : 'short'));
}
app.use((req, res, next) => {
  res.setHeader('Access-Control-Allow-Methods', 'GET,PUT,PATCH,POST,DELETE,OPTIONS');
  res.setHeader('Access-Control-Allow-Headers', 'Accept, Accept-Language, Content-Language, Content-Type, Authorization');
  const { origin } = req.headers;

  if ((/gcriva\.ml$/.test(origin) || /gcriva\.netlify\.com$/.test(origin)) || process.env.NODE_ENV === 'development') {
    res.setHeader('Access-Control-Allow-Origin', origin);
  }

  if (req.method === 'OPTIONS') {
    res.sendStatus(204);
  } else {
    next();
  }
});
app.use(compression());
app.use(bodyParser.json());
app.use(responseError);
app.use(expressValidator());
app.use(passport.initialize());
app.use(lusca.xframe('SAMEORIGIN'));
app.use(lusca.xssProtection(true));

app.use(authentication.authenticate);

/**
 * Primary app routes.
 */
app.get('/', homeController.index);
app.post('/login', usersController.postLogin);
app.post('/forgot', usersController.postForgot);
app.post('/reset/:token', usersController.postReset);
app.post('/signup', authentication.authorizeAdmin, usersController.signup);
app.post('/account', usersController.postUpdateProfile);
app.post('/account/password', usersController.postUpdatePassword);
app.post('/account/image', multer().single('picture'), usersController.updatePicture);
app.get('/users', authentication.authorizeAdmin, usersController.index);
app.delete('/users/delete', authentication.authorizeAdmin, usersController.delete);
app.get('/beneficiaries', beneficiariesController.index);
app.post('/beneficiaries', beneficiariesController.create);
app.get('/beneficiaries/:id', beneficiariesController.show);
app.delete('/beneficiaries/:id', beneficiariesController.delete);
app.put('/beneficiaries/:id', beneficiariesController.update);
app.get('/projects', projectsController.index);
app.get('/projects/:id', projectsController.show);
app.post('/projects', authentication.authorizeAdmin, projectsController.create);
app.put('/projects/:id', authentication.authorizeAdmin, projectsController.update);
app.delete('/projects/:id', authentication.authorizeAdmin, projectsController.delete);
app.get('/events', eventsController.index);
app.post('/events', eventsController.create);
app.put('/events/:id', eventsController.update);
app.delete('/events/:id', eventsController.delete);
app.get('/courses', coursesController.index);
app.post('/courses', coursesController.create);
app.put('/courses/:id', coursesController.update);
app.delete('/courses/:id', coursesController.delete);

/**
 * OAuth authentication routes. (Sign in)
 */
app.get('/auth/google', passport.authenticate('google', { scope: 'profile email' }));
app.get('/auth/google/callback', passport.authenticate('google', { failureRedirect: '/login' }), (req, res) => {
  res.redirect(req.session.returnTo || '/');
});


const isValidationError = is(ValidationError);
const isValidatorError = is(ValidatorError);

function handleModelErrors(error, req, res, next) {
  if (isValidationError(error) || isValidatorError(error)) {
    res.error(422, error);
  } else if (error.code === 404) {
    res.error(404, error.message);
  } else if (process.env.NODE_ENV === 'development') {
    // Show the entire error for debugging purposes
    console.error(error);
    res.error(500, error);
  } else {
    next(error);
  }
}
app.use(handleModelErrors);

module.exports = app;

@@ -1908,165 +1908,9 @@
 ');%0A
-  const %7B origin %7D = req.headers;%0A%0A  if ((/gcriva%5C.ml$/.test(origin) %7C%7C /gcriva%5C.netlify%5C.com$/.test(origin)) %7C%7C process.env.NODE_ENV === 'development') %7B%0A  
+%0A
   re
@@ -1956,20 +1956,13 @@
 n', 
-origin);%0A  %7D
+'*');
 %0A%0A  

Allow any origin