From bf1b92fdf138a79616f1c2880e083d91631d4b06 Mon Sep 17 00:00:00 2001
From: muerwre <gotham48@gmail.com>
Date: Mon, 3 Dec 2018 15:35:07 +0700
Subject: [PATCH] fixed config paths

---
 .eslintrc                                   |  5 +-
 .gitignore                                  |  3 +
 README.md                                   | 12 +--
 backend/bin/www                             | 96 +++++----------------
 backend/config/db.js                        | 15 ++--
 backend/config/social.js                    |  6 --
 backend/routes/auth/social/vk.js            |  6 +-
 config/backend.example.js                   | 27 ++++++
 src/config.js => config/frontend.example.js |  8 +-
 src/components/panels/UserPanel.jsx         |  5 +-
 src/constants/api.js                        | 11 ++-
 src/constants/providers.js                  |  2 -
 src/constants/types.js                      |  2 -
 src/modules/Map.js                          |  2 +-
 src/modules/Poly.js                         |  4 +-
 src/modules/Router.js                       |  4 +-
 src/utils/renderer.js                       |  6 +-
 webpack.config.js                           |  2 +-
 18 files changed, 92 insertions(+), 124 deletions(-)
 delete mode 100644 backend/config/social.js
 create mode 100644 config/backend.example.js
 rename src/config.js => config/frontend.example.js (58%)

diff --git a/.eslintrc b/.eslintrc
index eb2cac7..61b5a5e 100755
--- a/.eslintrc
+++ b/.eslintrc
@@ -54,7 +54,7 @@
               "$containers": "src/containers",
               "$constants": "src/constants",
               "$sprites": "src/sprites",
-              "$config": "src/config",
+              "$config": "config",
               "$styles": "src/styles",
               "$redux": "src/redux",
               "$utils": "src/utils",
@@ -62,8 +62,7 @@
             },
 
             "extensions": [".js", ".jsx", ".scss"],
-
-            "modules": ["src", "node_modules"]
+            "modules": ["config", "src", "node_modules"]
           }
         }
       }
diff --git a/.gitignore b/.gitignore
index 1ff48ae..9cd8d72 100644
--- a/.gitignore
+++ b/.gitignore
@@ -14,5 +14,8 @@ yarn-error.log
 /osrm/pbf
 /osrm/pbf/*
 
+/config/frontend.js
+/config/backend.js
+
 # Bundle
 *.js.map
diff --git a/README.md b/README.md
index fa7bf86..aef3fbc 100644
--- a/README.md
+++ b/README.md
@@ -4,7 +4,7 @@ Bicycle routes app with automatic routes, map screenshots, stickers and other fe
 ## Prerequisites
 node, osrm-server
 
-### Installing 
+### Installing
 First, download and install the project
 ```
 git clone https://github.com/muerwre/orchidMap.git
@@ -22,18 +22,20 @@ Next you need to edit start_server.sh to specify address, port for server and pa
 
 After that run start_server.sh in screen or by the way you feel comfortable.
 
-Next edit ```./src/config.js``` and specify OSRM url there. By default, OSRM starts at ```http://localhost:5000/```
+Next edit ```./config/frontend.js``` and specify OSRM url there. By default, OSRM starts at ```https://localhost:5001/```
 
-### Frontend
-Configs are placed in ```./src/config.js``` and ```./src/constants/```
+### Common setup
+Look at ```/config/``` folder, there's backend and frontend .example.js files, just rename them to .js only.
 
+### Client
+Configs are placed in ```./config/frontend.js```
 
 For development launch ```npm start``` and visit ```http://localhost:8000/```
 
 For production launch ```npm build```, the output will be placed at ```./dist``` folder, you should configure your http server to serve index html from that folder.
 
 ### Backend
-Take a look at ```./backend/config/``` files, especially at ```db.js```. Your api server will be spawned at ```http://localhost:3000/```
+Take a look at ```./config/backend.js```. By default your api server will be spawned at ```http://localhost:3000/```
 
 For development launch ```npm serve-dev```, it will launch dev server, reloading on every code update
 
diff --git a/backend/bin/www b/backend/bin/www
index b4595df..0c7ba0f 100755
--- a/backend/bin/www
+++ b/backend/bin/www
@@ -1,90 +1,34 @@
 #!/usr/bin/env node
-
-/**
- * Module dependencies.
- */
+const { CONFIG } = require('../../config/backend');
 
 const app = require('../app');
-const debug = require('debug')('orchid-backend:server');
+const fs = require('fs');
 const http = require('http');
+const https = require('https');
 
-/**
- * Get port from environment and store in Express.
- */
+if (CONFIG.HTTP.ENABLED) {
+  const httpPort = CONFIG.HTTP.PORT;
+  app.set('port', httpPort);
 
-const port = normalizePort(process.env.PORT || '3000');
-app.set('port', port);
+  const httpServer = http.createServer(app);
+  httpServer.listen(httpPort);
 
-/**
- * Create HTTP server.
- */
-
-const server = http.createServer(app);
-
-/**
- * Listen on provided port, on all network interfaces.
- */
-
-server.listen(port);
-server.on('error', onError);
-server.on('listening', onListening);
-
-/**
- * Normalize a port into a number, string, or false.
- */
-
-function normalizePort(val) {
-  const port = parseInt(val, 10);
-
-  if (isNaN(port)) {
-    // named pipe
-    return val;
-  }
-
-  if (port >= 0) {
-    // port number
-    return port;
-  }
-
-  return false;
+  httpServer.on('error', console.log);
+  httpServer.on('listening', console.log);
 }
 
-/**
- * Event listener for HTTP server "error" event.
- */
+if (CONFIG.HTTPS.ENABLED) {
+  const sslPort = CONFIG.HTTPS.PORT;
+  app.set('port', sslPort);
 
-function onError(error) {
-  if (error.syscall !== 'listen') {
-    throw error;
-  }
+  const privateKey = fs.readFileSync(CONFIG.HTTPS.PRIVATE_KEY, 'utf8');
+  const certificate = fs.readFileSync(CONFIG.HTTPS.CERTIFICATE, 'utf8');
+  const ca = fs.readFileSync(CONFIG.HTTPS.CA, 'utf8');
 
-  const bind = typeof port === 'string'
-    ? 'Pipe ' + port
-    : 'Port ' + port;
+  const sslServer = https.createServer({ privateKey, certificate, ca }, app);
 
-  // handle specific listen errors with friendly messages
-  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;
-  }
+  sslServer.listen(sslPort);
+  sslServer.on('error', console.log);
+  sslServer.on('listening', console.log);
 }
 
-/**
- * Event listener for HTTP server "listening" event.
- */
-
-function onListening() {
-  const addr = server.address();
-  const bind = typeof addr === 'string'
-    ? 'pipe ' + addr
-    : 'port ' + addr.port;
-  debug('Listening on ' + bind);
-}
diff --git a/backend/config/db.js b/backend/config/db.js
index dc2e096..c87db48 100644
--- a/backend/config/db.js
+++ b/backend/config/db.js
@@ -1,15 +1,16 @@
-const user = 'user';
-const password = 'password';
-const hostname = 'vault48.org';
-const port = 27017;
-const db = 'map';
+const { CONFIG } = require('../../config/backend');
+
+const {
+  DB: {
+    USER, PASSWORD, HOSTNAME, PORT, DATABASE
+  }
+} = CONFIG;
 
 const mongoose = require('mongoose');
 mongoose.Promise = require('bluebird');
 
-mongoose.connect(`mongodb://${user}:${password}@${hostname}:${port}/${db}`, { });
+mongoose.connect(`mongodb://${USER}:${PASSWORD}@${HOSTNAME}:${PORT}/${DATABASE}`, { });
 const database = mongoose.connection;
 
 database.on('error', (err) => { console.error(`Database Connection Error: ${err}`); process.exit(2); });
 database.on('connected', () => { console.info('Succesfully connected to MongoDB Database'); });
-
diff --git a/backend/config/social.js b/backend/config/social.js
deleted file mode 100644
index 7238232..0000000
--- a/backend/config/social.js
+++ /dev/null
@@ -1,6 +0,0 @@
-module.exports.SOCIAL = {
-  VK: {
-    client_secret: 'Z71DsxoMF7PS9kayLuks',
-    client_id: 5987644,
-  }
-};
diff --git a/backend/routes/auth/social/vk.js b/backend/routes/auth/social/vk.js
index 9f64777..39d87c9 100644
--- a/backend/routes/auth/social/vk.js
+++ b/backend/routes/auth/social/vk.js
@@ -2,7 +2,7 @@ const { User } = require('../../../models');
 const axios = require('axios');
 const { generateUser } = require('../guest');
 const { STRINGS } = require('../../../config/strings');
-const { SOCIAL } = require('../../../config/social');
+const { CONFIG } = require('../../../../config/backend');
 
 const fetchUserData = async (req, res) => {
   const { query: { code } } = req;
@@ -12,8 +12,8 @@ const fetchUserData = async (req, res) => {
     'https://oauth.vk.com/access_token',
     {
       params: {
-        client_id: SOCIAL.VK.client_id,
-        client_secret: SOCIAL.VK.client_secret,
+        client_id: CONFIG.SOCIAL.VK.APP_ID,
+        client_secret: CONFIG.SOCIAL.VK.SECRET,
         code,
         redirect_uri: `http://${host}/auth/social/vk`,
       }
diff --git a/config/backend.example.js b/config/backend.example.js
new file mode 100644
index 0000000..5ff4226
--- /dev/null
+++ b/config/backend.example.js
@@ -0,0 +1,27 @@
+module.exports.CONFIG = {
+  HTTPS: {
+    ENABLED: false,
+    PORT: 3000,
+    PRIVATE_KEY: '/etc/letsencrypt/live/HOSTNAME.org/privkey.pem',
+    CERTIFICATE: '/etc/letsencrypt/live/HOSTNAME.org/cert.pem',
+    CA: '/etc/letsencrypt/live/hostname/chain.pem',
+  },
+  HTTP: {
+    ENABLED: false,
+    PORT: 3000,
+  },
+  DB: { // mongo db config
+    USER: 'user',
+    PASSWORD: 'password',
+    HOSTNAME: 'HOSTNAME.org',
+    PORT: 27017,
+    DATABASE: 'map',
+  },
+  SOCIAL: {
+    VK: {
+      ENABLED: false,
+      SECRET: 'YOUR_VK_SECRET', // secret token
+      APP_ID: 0, // numeric
+    }
+  }
+};
diff --git a/src/config.js b/config/frontend.example.js
similarity index 58%
rename from src/config.js
rename to config/frontend.example.js
index 1dba195..e2cb328 100644
--- a/src/config.js
+++ b/config/frontend.example.js
@@ -1,7 +1,11 @@
 import { DEFAULT_PROVIDER, PROVIDERS } from '$constants/providers';
 
-export const CONFIG = {
-  OSRM_URL: 'http://vault48.org:5000/route/v1',
+const API_ADDR = 'https://HOSTNAME.org:3000';
+const OSRM_URL = 'https://HOSTNAME.org:5001/route/v1';
+
+export const CLIENT = {
+  OSRM_URL,
+  API_ADDR,
   STROKE_WIDTH: 5,
 };
 
diff --git a/src/components/panels/UserPanel.jsx b/src/components/panels/UserPanel.jsx
index 238e418..d6d9da8 100644
--- a/src/components/panels/UserPanel.jsx
+++ b/src/components/panels/UserPanel.jsx
@@ -1,7 +1,6 @@
 import React from 'react';
 
 import { GuestButton } from '$components/user/GuestButton';
-import { TEST } from '$constants/api';
 import { DEFAULT_USER, ROLES } from '$constants/auth';
 import { UserButton } from '$components/user/UserButton';
 import { UserMenu } from '$components/user/UserMenu';
@@ -12,6 +11,7 @@ import type { UserType } from '$constants/types';
 import { Icon } from '$components/panels/Icon';
 
 import classnames from 'classnames';
+import { CLIENT } from '$config/frontend';
 
 type Props = {
   user: UserType,
@@ -62,8 +62,7 @@ export class Component extends React.PureComponent<Props, void> {
     const left = (width - 700) / 2;
 
     window.open(
-      // `https://oauth.vk.com/authorize?client_id=5987644&scope=&redirect_uri=${SERVER}/engine/oauthOrchid.php&response_type=code`,
-      `https://oauth.vk.com/authorize?client_id=5987644&scope=&redirect_uri=${TEST}/auth/social/vk`,
+      `https://oauth.vk.com/authorize?client_id=5987644&scope=&redirect_uri=${CLIENT.API_ADDR}/auth/social/vk`,
       'socialPopupWindow',
       `location=no,width=700,height=370,scrollbars=no,top=${top},left=${left},resizable=no`
     );
diff --git a/src/constants/api.js b/src/constants/api.js
index 3c1dd49..9767b3f 100644
--- a/src/constants/api.js
+++ b/src/constants/api.js
@@ -1,9 +1,8 @@
-export const SERVER = 'http://alpha-map.vault48.org';
-export const TEST = 'http://localhost:3000';
+import { CLIENT } from '$config/frontend';
 
 export const API = {
-  GET_GUEST: `${TEST}/auth`,
-  CHECK_TOKEN: `${TEST}/auth`,
-  GET_MAP: `${TEST}/route`,
-  POST_MAP: `${TEST}/route`,
+  GET_GUEST: `${CLIENT.API_ADDR}/auth`,
+  CHECK_TOKEN: `${CLIENT.API_ADDR}/auth`,
+  GET_MAP: `${CLIENT.API_ADDR}/route`,
+  POST_MAP: `${CLIENT.API_ADDR}/route`,
 };
diff --git a/src/constants/providers.js b/src/constants/providers.js
index 54d18ef..4df3c6f 100644
--- a/src/constants/providers.js
+++ b/src/constants/providers.js
@@ -1,6 +1,4 @@
 // Стили карт
-import { editor } from '$modules/Editor';
-
 const TILEMAPS = {
   WATERCOLOR: {
     name: 'Watercolor',
diff --git a/src/constants/types.js b/src/constants/types.js
index b1ee867..6ea581d 100644
--- a/src/constants/types.js
+++ b/src/constants/types.js
@@ -1,5 +1,3 @@
-import { ROLES } from '$constants/auth';
-
 export type UserType = {
   new_messages: Number,
   place_types: Object,
diff --git a/src/modules/Map.js b/src/modules/Map.js
index fd2f460..bee5d4d 100644
--- a/src/modules/Map.js
+++ b/src/modules/Map.js
@@ -1,7 +1,7 @@
 import { map, tileLayer } from 'leaflet';
 import 'leaflet/dist/leaflet.css';
 import 'leaflet-editable';
-import { PROVIDER } from '$config';
+import { PROVIDER } from '$config/frontend';
 import { DEFAULT_PROVIDER, PROVIDERS } from '$constants/providers';
 
 export class Map {
diff --git a/src/modules/Poly.js b/src/modules/Poly.js
index 8bb12d6..cf22668 100644
--- a/src/modules/Poly.js
+++ b/src/modules/Poly.js
@@ -2,7 +2,7 @@ import L from 'leaflet';
 import 'leaflet-geometryutil';
 import { simplify } from '$utils/simplify';
 import { findDistance, middleCoord } from '$utils/geom';
-import { CONFIG } from '$config';
+import { CLIENT } from '$config/frontend';
 
 const polyStyle = {
   color: 'url(#activePathGradient)',
@@ -50,7 +50,7 @@ export class Poly {
           latlngs[i - 1],
           [mid.lat, mid.lng]
         ],
-        { color: 'none', weight: CONFIG.STROKE_WIDTH }
+        { color: 'none', weight: CLIENT.STROKE_WIDTH }
       ).addTo(this.arrows);
 
       slide._path.setAttribute('marker-end', 'url(#long-arrow)');
diff --git a/src/modules/Router.js b/src/modules/Router.js
index 65214ca..5d28885 100644
--- a/src/modules/Router.js
+++ b/src/modules/Router.js
@@ -1,6 +1,6 @@
 import L from 'leaflet';
 import Routing from 'leaflet-routing-machine/src/index';
-import { CONFIG } from '$config';
+import { CLIENT } from '$config/frontend';
 import { DomMarker } from '$utils/DomMarker';
 
 export class Router {
@@ -22,7 +22,7 @@ export class Router {
     }).on('linetouched', this.lockPropagations);
 
     this.router = Routing.control({
-      serviceUrl: CONFIG.OSRM_URL,
+      serviceUrl: CLIENT.OSRM_URL,
       profile: 'bike',
       fitSelectedRoutes: false,
       routeLine,
diff --git a/src/utils/renderer.js b/src/utils/renderer.js
index c4a6761..a726e70 100644
--- a/src/utils/renderer.js
+++ b/src/utils/renderer.js
@@ -1,7 +1,7 @@
 import { editor } from '$modules/Editor';
-import { COLORS, CONFIG } from '$config';
+import { COLORS, CLIENT } from '$config/frontend';
 import saveAs from 'file-saver';
-import { DEFAULT_PROVIDER, PROVIDERS, replaceProviderUrl } from '$constants/providers';
+import { replaceProviderUrl } from '$constants/providers';
 
 const latLngToTile = latlng => {
   const { map } = editor.map;
@@ -119,7 +119,7 @@ export const composePoly = ({ points, ctx }) => {
   ctx.strokeStyle = 'red';
   ctx.lineCap = 'round';
   ctx.lineJoin = 'round';
-  ctx.lineWidth = CONFIG.STROKE_WIDTH + 0.5;
+  ctx.lineWidth = CLIENT.STROKE_WIDTH + 0.5;
 
   ctx.beginPath();
   ctx.moveTo(points[0].x, points[0].y);
diff --git a/webpack.config.js b/webpack.config.js
index 9dfe5c3..dba1b88 100644
--- a/webpack.config.js
+++ b/webpack.config.js
@@ -35,7 +35,7 @@ const resolve = {
     $containers: join(__dirname, 'src/containers'),
     $constants: join(__dirname, 'src/constants'),
     $sprites: join(__dirname, 'src/sprites'),
-    $config: join(__dirname, 'src/config'),
+    $config: join(__dirname, './config'),
     $styles: join(__dirname, 'src/styles'),
     $redux: join(__dirname, 'src/redux'),
     $utils: join(__dirname, 'src/utils'),