diff --git a/backend/src/activitypub/ActivityPub.js b/backend/src/activitypub/ActivityPub.js index da1056362..aa447a2d7 100644 --- a/backend/src/activitypub/ActivityPub.js +++ b/backend/src/activitypub/ActivityPub.js @@ -7,6 +7,7 @@ import router from './routes' import dotenv from 'dotenv' import Collections from './Collections' import uuid from 'uuid/v4' +import CONFIG from '../config' const debug = require('debug')('ea') let activityPub = null @@ -23,10 +24,7 @@ export default class ActivityPub { static init(server) { if (!activityPub) { dotenv.config() - activityPub = new ActivityPub( - process.env.CLIENT_URI || 'http://localhost:3000', - process.env.GRAPHQL_URI || 'http://localhost:4000', - ) + activityPub = new ActivityPub(CONFIG.CLIENT_URI, CONFIG.GRAPHQL_URI) // integrate into running graphql express server server.express.set('ap', activityPub) diff --git a/backend/src/activitypub/security/index.js b/backend/src/activitypub/security/index.js index 7f619acbe..2ecdec022 100644 --- a/backend/src/activitypub/security/index.js +++ b/backend/src/activitypub/security/index.js @@ -2,12 +2,13 @@ import dotenv from 'dotenv' import { resolve } from 'path' import crypto from 'crypto' import request from 'request' +import CONFIG from './../../config' const debug = require('debug')('ea:security') dotenv.config({ path: resolve('src', 'activitypub', '.env') }) export function generateRsaKeyPair(options = {}) { - const { passphrase = process.env.PRIVATE_KEY_PASSPHRASE } = options + const { passphrase = CONFIG.PRIVATE_KEY_PASSPHRASE } = options return crypto.generateKeyPairSync('rsa', { modulusLength: 4096, publicKeyEncoding: { @@ -31,7 +32,7 @@ export function createSignature(options) { url, headers = {}, algorithm = 'rsa-sha256', - passphrase = process.env.PRIVATE_KEY_PASSPHRASE, + passphrase = CONFIG.PRIVATE_KEY_PASSPHRASE, } = options if (!SUPPORTED_HASH_ALGORITHMS.includes(algorithm)) { throw Error(`SIGNING: Unsupported hashing algorithm = ${algorithm}`) diff --git a/backend/src/activitypub/utils/index.js b/backend/src/activitypub/utils/index.js index ee7ae2606..3927f4056 100644 --- a/backend/src/activitypub/utils/index.js +++ b/backend/src/activitypub/utils/index.js @@ -2,6 +2,7 @@ import { activityPub } from '../ActivityPub' import gql from 'graphql-tag' import { createSignature } from '../security' import request from 'request' +import CONFIG from './../../config' const debug = require('debug')('ea:utils') export function extractNameFromId(uri) { @@ -38,7 +39,7 @@ export function throwErrorIfApolloErrorOccurred(result) { export function signAndSend(activity, fromName, targetDomain, url) { // fix for development: replace with http url = url.indexOf('localhost') > -1 ? url.replace('https', 'http') : url - debug(`passhprase = ${process.env.PRIVATE_KEY_PASSPHRASE}`) + debug(`passhprase = ${CONFIG.PRIVATE_KEY_PASSPHRASE}`) return new Promise(async (resolve, reject) => { debug('inside signAndSend') // get the private key diff --git a/backend/src/bootstrap/neo4j.js b/backend/src/bootstrap/neo4j.js index 292983359..15c9c4533 100644 --- a/backend/src/bootstrap/neo4j.js +++ b/backend/src/bootstrap/neo4j.js @@ -1,5 +1,6 @@ import { v1 as neo4j } from 'neo4j-driver' import dotenv from 'dotenv' +import CONFIG from './../config' dotenv.config() @@ -7,9 +8,9 @@ let driver export function getDriver(options = {}) { const { - uri = process.env.NEO4J_URI || 'bolt://localhost:7687', - username = process.env.NEO4J_USERNAME || 'neo4j', - password = process.env.NEO4J_PASSWORD || 'neo4j', + uri = CONFIG.NEO4J_URI, + username = CONFIG.NEO4J_USERNAME, + password = CONFIG.NEO4J_PASSWORD, } = options if (!driver) { driver = neo4j.driver(uri, neo4j.auth.basic(username, password)) diff --git a/backend/src/config/index.js b/backend/src/config/index.js index 7a0387560..aa8b3a5dc 100644 --- a/backend/src/config/index.js +++ b/backend/src/config/index.js @@ -8,9 +8,22 @@ const requiredConfigs = { PRIVATE_KEY_PASSPHRASE: process.env.PRIVATE_KEY_PASSPHRASE, } +const neo4jConfigs = { + NEO4J_URI: process.env.NEO4J_URI || 'bolt://localhost:7687', + NEO4J_USERNAME: process.env.NEO4J_USERNAME || 'neo4j', + NEO4J_PASSWORD: process.env.NEO4J_PASSWORD || 'neo4j', +} + +const serverConfigs = { + GRAPHQL_PORT: process.env.GRAPHQL_PORT || 4000, + CLIENT_URI: process.env.CLIENT_URI || 'http://localhost:3000', + GRAPHQL_URI: process.env.GRAPHQL_URI || 'http://localhost:4000', +} + const developmentConfigs = { DEBUG: process.env.NODE_ENV !== 'production' && process.env.DEBUG === 'true', MOCKS: process.env.MOCKS === 'true', + DISABLED_MIDDLEWARES: process.env.DISABLED_MIDDLEWARES || '', } // check required configs and throw error @@ -22,5 +35,7 @@ Object.entries(requiredConfigs).map(entry => { export default { ...requiredConfigs, + ...neo4jConfigs, + ...serverConfigs, ...developmentConfigs, } diff --git a/backend/src/index.js b/backend/src/index.js index 2095d171f..f28e58947 100644 --- a/backend/src/index.js +++ b/backend/src/index.js @@ -1,17 +1,18 @@ import createServer from './server' import ActivityPub from './activitypub/ActivityPub' +import CONFIG from './config' const serverConfig = { - port: process.env.GRAPHQL_PORT || 4000, + port: CONFIG.GRAPHQL_PORT, // cors: { // credentials: true, - // origin: [process.env.CLIENT_URI] // your frontend url. + // origin: [CONFIG.CLIENT_URI] // your frontend url. // } } const server = createServer() server.start(serverConfig, options => { /* eslint-disable-next-line no-console */ - console.log(`GraphQLServer ready at ${process.env.GRAPHQL_URI} 🚀`) + console.log(`GraphQLServer ready at ${CONFIG.GRAPHQL_URI} 🚀`) ActivityPub.init(server) }) diff --git a/backend/src/jwt/decode.js b/backend/src/jwt/decode.js index d4485952d..b98357103 100644 --- a/backend/src/jwt/decode.js +++ b/backend/src/jwt/decode.js @@ -1,11 +1,12 @@ import jwt from 'jsonwebtoken' +import CONFIG from './../config' export default async (driver, authorizationHeader) => { if (!authorizationHeader) return null const token = authorizationHeader.replace('Bearer ', '') let id = null try { - const decoded = await jwt.verify(token, process.env.JWT_SECRET) + const decoded = await jwt.verify(token, CONFIG.JWT_SECRET) id = decoded.sub } catch (err) { return null diff --git a/backend/src/jwt/encode.js b/backend/src/jwt/encode.js index 49aa17bd0..97c6dcd66 100644 --- a/backend/src/jwt/encode.js +++ b/backend/src/jwt/encode.js @@ -1,15 +1,16 @@ import jwt from 'jsonwebtoken' import ms from 'ms' +import CONFIG from './../config' // Generate an Access Token for the given User ID export default function encode(user) { - const token = jwt.sign(user, process.env.JWT_SECRET, { + const token = jwt.sign(user, CONFIG.JWT_SECRET, { expiresIn: ms('1d'), - issuer: process.env.GRAPHQL_URI, - audience: process.env.CLIENT_URI, + issuer: CONFIG.GRAPHQL_URI, + audience: CONFIG.CLIENT_URI, subject: user.id.toString(), }) - // jwt.verifySignature(token, process.env.JWT_SECRET, (err, data) => { + // jwt.verifySignature(token, CONFIG.JWT_SECRET, (err, data) => { // console.log('token verification:', err, data) // }) return token diff --git a/backend/src/middleware/index.js b/backend/src/middleware/index.js index bef6ceac9..cdc1d298c 100644 --- a/backend/src/middleware/index.js +++ b/backend/src/middleware/index.js @@ -12,6 +12,7 @@ import includedFieldsMiddleware from './includedFieldsMiddleware' import orderByMiddleware from './orderByMiddleware' import validationMiddleware from './validation' import notificationsMiddleware from './notifications' +import CONFIG from './../config' export default schema => { let middleware = [ @@ -31,9 +32,8 @@ export default schema => { // add permisions middleware at the first position (unless we're seeding) // NOTE: DO NOT SET THE PERMISSION FLAT YOUR SELF - if (process.env.NODE_ENV !== 'production') { - const DISABLED_MIDDLEWARES = process.env.DISABLED_MIDDLEWARES || '' - const disabled = DISABLED_MIDDLEWARES.split(',') + if (CONFIG.DEBUG) { + const disabled = CONFIG.DISABLED_MIDDLEWARES.split(',') if (!disabled.includes('activityPub')) middleware.unshift(activityPubMiddleware) if (!disabled.includes('permissions')) middleware.unshift(permissionsMiddleware.generate(schema)) diff --git a/backend/src/middleware/nodes/locations.js b/backend/src/middleware/nodes/locations.js index a0adeb57f..62d1e3a65 100644 --- a/backend/src/middleware/nodes/locations.js +++ b/backend/src/middleware/nodes/locations.js @@ -2,6 +2,7 @@ import request from 'request' import { UserInputError } from 'apollo-server' import isEmpty from 'lodash/isEmpty' import asyncForEach from '../../helpers/asyncForEach' +import CONFIG from './../../config' const fetch = url => { return new Promise((resolve, reject) => { @@ -58,11 +59,12 @@ const createOrUpdateLocations = async (userId, locationName, driver) => { if (isEmpty(locationName)) { return } - const mapboxToken = process.env.MAPBOX_TOKEN const res = await fetch( `https://api.mapbox.com/geocoding/v5/mapbox.places/${encodeURIComponent( locationName, - )}.json?access_token=${mapboxToken}&types=region,place,country&language=${locales.join(',')}`, + )}.json?access_token=${CONFIG.MAPBOX_TOKEN}&types=region,place,country&language=${locales.join( + ',', + )}`, ) if (!res || !res.features || !res.features[0]) { diff --git a/backend/src/schema/resolvers/user_management.spec.js b/backend/src/schema/resolvers/user_management.spec.js index 9dff9e388..690d93f86 100644 --- a/backend/src/schema/resolvers/user_management.spec.js +++ b/backend/src/schema/resolvers/user_management.spec.js @@ -3,6 +3,7 @@ import Factory from '../seed/factories' import { GraphQLClient, request } from 'graphql-request' import jwt from 'jsonwebtoken' import { host, login } from '../jest/helpers' +import CONFIG from './config' const factory = Factory() @@ -185,7 +186,7 @@ describe('login', () => { }), ) const token = data.login - jwt.verify(token, process.env.JWT_SECRET, (err, data) => { + jwt.verify(token, CONFIG.JWT_SECRET, (err, data) => { expect(data.email).toEqual('test@example.org') expect(err).toBeNull() }) diff --git a/backend/src/seed/reset-db.js b/backend/src/seed/reset-db.js index 3197a6e18..095db240c 100644 --- a/backend/src/seed/reset-db.js +++ b/backend/src/seed/reset-db.js @@ -1,10 +1,11 @@ import { cleanDatabase } from './factories' import dotenv from 'dotenv' +import CONFIG from './config' dotenv.config() -if (process.env.NODE_ENV === 'production') { - throw new Error(`YOU CAN'T CLEAN THE DATABASE WITH NODE_ENV=${process.env.NODE_ENV}`) +if (!CONFIG.DEBUG) { + throw new Error(`YOU CAN'T CLEAN THE DATABASE WITH DEBUG=${CONFIG.DEBUG}`) } ;(async function() {