Skip to content

m2m implementation. #82

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 12 commits into from
May 23, 2018
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .circleci/config.yml
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,7 @@ workflows:
- test
filters:
branches:
only: dev
only: 'dev'
- deployProd:
requires:
- test
Expand Down
2 changes: 1 addition & 1 deletion Dockerfile
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
FROM node:6.9.4
FROM node:8.2.1
LABEL version="1.0"
LABEL description="Projects microservice"

Expand Down
10 changes: 7 additions & 3 deletions config/custom-environment-variables.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"apiVersion": "API_VERSION",
"authSecret": "AUTH_SECRET",
"AUTH_SECRET": "AUTH_SECRET",
"logLevel": "LOG_LEVEL",
"version": "APP_VERSION",
"captureLogs": "CAPTURE_LOGS",
Expand Down Expand Up @@ -28,8 +28,12 @@
"minPoolSize": "DB_MIN_POOL_SIZE"
},
"analyticsKey": "SEGMENT_ANALYTICS_KEY",
"validIssuers": "VALID_ISSUERS",
"VALID_ISSUERS": "VALID_ISSUERS",
"jwksUri": "JWKS_URI",
"busApiUrl": "BUS_API_URL",
"busApiToken": "BUS_API_TOKEN"
"AUTH0_URL" : "AUTH0_URL",
"AUTH0_CLIENT_ID": "AUTH0_CLIENT_ID",
"AUTH0_CLIENT_SECRET": "AUTH0_CLIENT_SECRET",
"AUTH0_AUDIENCE": "AUTH0_AUDIENCE",
"TOKEN_CACHE_TIME" : "TOKEN_CACHE_TIME"
}
14 changes: 8 additions & 6 deletions config/default.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
{
"apiVersion": "v4",
"authSecret": "secret",
"authDomain": "topcoder-dev.com",
"AUTH_SECRET": "secret",
"logLevel": "info",
"version": "v4",
"captureLogs": "false",
Expand Down Expand Up @@ -33,9 +32,12 @@
"idleTimeout": 1000
},
"analyticsKey": "",
"validIssuers": "[\"https:\/\/topcoder-newauth.auth0.com\/\",\"https:\/\/api.topcoder-dev.com\"]",
"jwksUri": "",
"VALID_ISSUERS": "[\"https:\/\/topcoder-newauth.auth0.com\/\",\"https:\/\/api.topcoder-dev.com\"]",
"busApiUrl": "http://api.topcoder-dev.com",
"busApiToken": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJuYW1lIjoicHJvamVjdC1zZXJ2aWNlIiwiaWF0IjoxNTEyNzQ3MDgyLCJleHAiOjE1MjEzODcwODJ9.PHuNcFDaotGAL8RhQXQMdpL8yOKXxjB5DbBIodmt7RE",
"HEALTH_CHECK_URL": "_health"
"HEALTH_CHECK_URL": "_health",
"AUTH0_CLIENT_ID": "",
"AUTH0_CLIENT_SECRET": "",
"AUTH0_AUDIENCE": "",
"AUTH0_URL": "",
"TOKEN_CACHE_TIME": ""
}
1 change: 0 additions & 1 deletion config/development.json
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
{
"authDomain": "topcoder-dev.com",
"pubsubQueueName": "dev.project.service",
"pubsubExchangeName": "dev.projects",
"attachmentsS3Bucket": "topcoder-dev-media"
Expand Down
3 changes: 1 addition & 2 deletions config/test.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
{
"authSecret": "secret",
"authDomain": "topcoder-dev.com",
"AUTH_SECRET": "secret",
"logLevel": "debug",
"captureLogs": "false",
"logentriesToken": "",
Expand Down
36 changes: 29 additions & 7 deletions deploy.sh
Original file line number Diff line number Diff line change
Expand Up @@ -117,10 +117,6 @@ make_task_def(){
"name": "BUS_API_URL",
"value": "%s"
},
{
"name": "BUS_API_TOKEN",
"value": "%s"
},
{
"name": "SYSTEM_USER_CLIENT_ID",
"value": "%s"
Expand Down Expand Up @@ -156,6 +152,26 @@ make_task_def(){
{
"name": "SEGMENT_ANALYTICS_KEY",
"value": "%s"
},
{
"name": "AUTH0_URL",
"value": "%s"
},
{
"name": "AUTH0_AUDIENCE",
"value": "%s"
},
{
"name": "AUTH0_CLIENT_ID",
"value": "%s"
},
{
"name": "AUTH0_CLIENT_SECRET",
"value": "%s"
},
{
"name": "TOKEN_CACHE_TIME",
"value": "%s"
}
],
"portMappings": [
Expand All @@ -180,7 +196,6 @@ make_task_def(){
MEMBER_SERVICE_ENDPOINT=$(eval "echo \$${ENV}_MEMBER_SERVICE_ENDPOINT")
IDENTITY_SERVICE_ENDPOINT=$(eval "echo \$${ENV}_IDENTITY_SERVICE_ENDPOINT")
BUS_API_URL=$(eval "echo \$${ENV}_BUS_API_URL")
BUS_API_TOKEN=$(eval "echo \$${ENV}_BUS_API_TOKEN")
SYSTEM_USER_CLIENT_ID=$(eval "echo \$${ENV}_SYSTEM_USER_CLIENT_ID")
SYSTEM_USER_CLIENT_SECRET=$(eval "echo \$${ENV}_SYSTEM_USER_CLIENT_SECRET")
CAPTURE_LOGS=$(eval "echo \$${ENV}_CAPTURE_LOGS")
Expand All @@ -201,7 +216,14 @@ make_task_def(){
echo "NODE_ENV"
echo $NODE_ENV

task_def=$(printf "$task_template" $family $ACCOUNT_ID $AWS_ECS_CONTAINER_NAME $ACCOUNT_ID $AWS_REGION $AWS_REPOSITORY $CIRCLE_SHA1 $NODE_ENV $LOG_LEVEL $CAPTURE_LOGS $LOGENTRIES_TOKEN $API_VERSION $AWS_REGION $AWS_ACCESS_KEY_ID $AWS_SECRET_ACCESS_KEY $AUTH_DOMAIN $AUTH_SECRET $VALID_ISSUERS $DB_MASTER_URL $MEMBER_SERVICE_ENDPOINT $IDENTITY_SERVICE_ENDPOINT $BUS_API_URL $BUS_API_TOKEN $SYSTEM_USER_CLIENT_ID $SYSTEM_USER_CLIENT_SECRET $PROJECTS_ES_URL $PROJECTS_ES_INDEX_NAME $RABBITMQ_URL $DIRECT_PROJECT_SERVICE_ENDPOINT $FILE_SERVICE_ENDPOINT $CONNECT_PROJECTS_URL $SEGMENT_ANALYTICS_KEY $PORT $PORT $AWS_ECS_CLUSTER $AWS_REGION $NODE_ENV)
AUTH0_URL=$(eval "echo \$${ENV}_AUTH0_URL")
AUTH0_AUDIENCE=$(eval "echo \$${ENV}_AUTH0_AUDIENCE")
AUTH0_CLIENT_ID=$(eval "echo \$${ENV}_AUTH0_CLIENT_ID")
AUTH0_CLIENT_SECRET=$(eval "echo \$${ENV}_AUTH0_CLIENT_SECRET")
TOKEN_CACHE_TIME=$(eval "echo \$${ENV}_TOKEN_CACHE_TIME")


task_def=$(printf "$task_template" $family $ACCOUNT_ID $AWS_ECS_CONTAINER_NAME $ACCOUNT_ID $AWS_REGION $AWS_REPOSITORY $CIRCLE_SHA1 $NODE_ENV $LOG_LEVEL $CAPTURE_LOGS $LOGENTRIES_TOKEN $API_VERSION $AWS_REGION $AWS_ACCESS_KEY_ID $AWS_SECRET_ACCESS_KEY $AUTH_DOMAIN $AUTH_SECRET $VALID_ISSUERS $DB_MASTER_URL $MEMBER_SERVICE_ENDPOINT $IDENTITY_SERVICE_ENDPOINT $BUS_API_URL $SYSTEM_USER_CLIENT_ID $SYSTEM_USER_CLIENT_SECRET $PROJECTS_ES_URL $PROJECTS_ES_INDEX_NAME $RABBITMQ_URL $DIRECT_PROJECT_SERVICE_ENDPOINT $FILE_SERVICE_ENDPOINT $CONNECT_PROJECTS_URL $SEGMENT_ANALYTICS_KEY "$AUTH0_URL" "$AUTH0_AUDIENCE" $AUTH0_CLIENT_ID "$AUTH0_CLIENT_SECRET" $TOKEN_CACHE_TIME $PORT $PORT $AWS_ECS_CLUSTER $AWS_REGION $NODE_ENV)
}

push_ecr_image(){
Expand Down Expand Up @@ -240,4 +262,4 @@ check_service_status() {
configure_aws_cli
push_ecr_image
deploy_cluster
check_service_status
check_service_status
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@
"pg": "^4.5.5",
"pg-native": "^1.10.0",
"sequelize": "^3.23.0",
"tc-core-library-js": "appirio-tech/tc-core-library-js.git#v2.2",
"tc-core-library-js": "appirio-tech/tc-core-library-js.git#v2.3",
"traverse": "^0.6.6",
"urlencode": "^1.1.0"
},
Expand Down
4 changes: 4 additions & 0 deletions src/constants.js
Original file line number Diff line number Diff line change
Expand Up @@ -77,3 +77,7 @@ export const BUS_API_EVENT = {
export const REGEX = {
URL: /^(http(s?):\/\/)?(www\.)?[a-zA-Z0-9\.\-\_]+(\.[a-zA-Z]{2,15})+(\:[0-9]{2,5})?(\/[a-zA-Z0-9\_\-\s\.\/\?\%\#\&\=;]*)?$/, // eslint-disable-line
};

export const TOKEN_SCOPES = {
CONNECT_PROJECT_ADMIN: 'all:connect_project',
};
96 changes: 52 additions & 44 deletions src/services/busApi.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,33 +2,38 @@ import config from 'config';

const Promise = require('bluebird');
const axios = require('axios');
const tcCoreLibAuth = require('tc-core-library-js').auth;

const m2m = tcCoreLibAuth.m2m(config);

let client = null;

/**
* Get Http client to bus api
* @return {Object} Http Client to bus api
*/
function getClient() {
async function getClient() {
if (client) return client;
const apiBusUrl = config.get('busApiUrl');
const apiBusToken = config.get('busApiToken');
try {
const token = await m2m.getMachineToken(config.AUTH0_CLIENT_ID, config.AUTH0_CLIENT_SECRET);
client = axios.create({ baseURL: apiBusUrl });

client = axios.create({ baseURL: apiBusUrl });
// Alter defaults after instance has been created
client.defaults.headers.common.Authorization = `Bearer ${token}`;

// Alter defaults after instance has been created
client.defaults.headers.common.Authorization = `Bearer ${apiBusToken}`;
// Add a response interceptor
client.interceptors.response.use(function (res) { // eslint-disable-line
return res;
}, function (error) { // eslint-disable-line
// Ingore response errors
return Promise.resolve();
});

// Add a response interceptor
client.interceptors.response.use(function (res) { // eslint-disable-line
return res;
}, function (error) { // eslint-disable-line
// Ingore response errors
return Promise.resolve();
});

return client;
return client;
} catch (err) {
return Promise.reject(`Bus api calling - Error in genearting m2m token : ${err.message}`);
}
}

/**
Expand All @@ -42,39 +47,42 @@ function getClient() {
function createEvent(type, message, logger) {
const body = JSON.stringify(message);
logger.debug(`Sending message: ${JSON.stringify(message)}`);
return getClient().post('/bus/events', {
type,
message: body,
})
.then((resp) => {
logger.debug('Sent event to bus-api');
logger.debug(`Sent event to bus-api [data]: ${resp.data}`);
logger.debug(`Sent event to bus-api [status]: ${resp.status}`);
})
.catch((error) => {
logger.debug('Error sending event to bus-api');
if (error.response) {
// The request was made and the server responded with a status code
// that falls out of the range of 2xx
logger.debug(error.response.data);
logger.debug(error.response.status);
logger.debug(error.response.headers);
} else if (error.request) {
// The request was made but no response was received
// `error.request` is an instance of XMLHttpRequest in the browser and an instance of
// http.ClientRequest in node.js
logger.debug(error.request);
} else {
// Something happened in setting up the request that triggered an Error
logger.debug(error.message);
}
logger.debug(error.config);

Promise.resolve(); // eslint-disable-line
return getClient().then((busClient) => {
logger.debug('calling bus-api');
busClient.post('/bus/events', {
type,
message: body,
})
.then((resp) => {
logger.debug('Sent event to bus-api');
logger.debug(`Sent event to bus-api [data]: ${resp.data}`);
logger.debug(`Sent event to bus-api [status]: ${resp.status}`);
})
.catch((error) => {
logger.debug('Error sending event to bus-api');
if (error.response) {
// The request was made and the server responded with a status code
// that falls out of the range of 2xx
logger.debug(error.response.data);
logger.debug(error.response.status);
logger.debug(error.response.headers);
} else if (error.request) {
// The request was made but no response was received
// `error.request` is an instance of XMLHttpRequest in the browser and an instance of
// http.ClientRequest in node.js
logger.debug(error.request);
} else {
// Something happened in setting up the request that triggered an Error
logger.debug(error.message);
}
logger.debug(error.config);
Promise.resolve(); // eslint-disable-line
});
}).catch((errMessage) => {
logger.debug(errMessage);
});
}


module.exports = {
createEvent,
};
20 changes: 19 additions & 1 deletion src/util.js
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ import urlencode from 'urlencode';
import elasticsearch from 'elasticsearch';
import Promise from 'bluebird';
import AWS from 'aws-sdk';
import { ADMIN_ROLES } from './constants';
import { ADMIN_ROLES, TOKEN_SCOPES } from './constants';

const exec = require('child_process').exec;
const models = require('./models').default;
Expand Down Expand Up @@ -70,6 +70,12 @@ _.assignIn(util, {
* @return {boolean} true/false
*/
hasRole: (req, role) => {
const isMachineToken = _.get(req, 'authUser.isMachine', false);
const tokenScopes = _.get(req, 'authUser.scopes', []);
if (isMachineToken) {
if (_.indexOf(tokenScopes, TOKEN_SCOPES.CONNECT_PROJECT_ADMIN) >= 0) return true;
return false;
}
let roles = _.get(req, 'authUser.roles', []);
roles = roles.map(s => s.toLowerCase());
return _.indexOf(roles, role.toLowerCase()) >= 0;
Expand All @@ -81,6 +87,12 @@ _.assignIn(util, {
* @return {boolean} true/false
*/
hasRoles: (req, roles) => {
const isMachineToken = _.get(req, 'authUser.isMachine', false);
const tokenScopes = _.get(req, 'authUser.scopes', []);
if (isMachineToken) {
if (_.indexOf(tokenScopes, TOKEN_SCOPES.CONNECT_PROJECT_ADMIN) >= 0) return true;
return false;
}
let authRoles = _.get(req, 'authUser.roles', []);
authRoles = authRoles.map(s => s.toLowerCase());
return _.intersection(authRoles, roles.map(r => r.toLowerCase())).length > 0;
Expand All @@ -101,6 +113,12 @@ _.assignIn(util, {
* @return {boolean} true/false
*/
hasAdminRole: (req) => {
const isMachineToken = _.get(req, 'authUser.isMachine', false);
const tokenScopes = _.get(req, 'authUser.scopes', []);
if (isMachineToken) {
if (_.indexOf(tokenScopes, TOKEN_SCOPES.CONNECT_PROJECT_ADMIN) >= 0) return true;
return false;
}
let roles = _.get(req, 'authUser.roles', []);
roles = roles.map(s => s.toLowerCase());
return _.intersection(roles, ADMIN_ROLES.map(r => r.toLowerCase())).length > 0;
Expand Down