Skip to content

Hotfix/user level reports #535

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 9 commits into from
Apr 9, 2020
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
4 changes: 4 additions & 0 deletions src/routes/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -310,6 +310,10 @@ router.route('/v5/projects/metadata/planConfig/:key/versions/:version(\\d+)')
.patch(require('./planConfig/version/update'))
.delete(require('./planConfig/version/delete'));

// user level reports
router.route('/v5/projects/reports/embed')
.get(require('./userReports/getEmbedReport'));

// work streams
router.route('/v5/projects/:projectId(\\d+)/workstreams')
.get(require('./workStreams/list'))
Expand Down
5 changes: 3 additions & 2 deletions src/routes/projectReports/getEmbedReport.js
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,8 @@ module.exports = [
let REPORTS = null;
let allowedUsers = null;
try {
allowedUsers = JSON.parse(_.get(config, 'lookerConfig.ALLOWED_USERS', '[]'));
allowedUsers = config.get('lookerConfig.ALLOWED_USERS');
allowedUsers = allowedUsers ? JSON.parse(allowedUsers) : [];
req.log.trace(allowedUsers, 'allowedUsers');
REPORTS = JSON.parse(config.get('lookerConfig.EMBED_REPORTS_MAPPING'));
} catch (error) {
Expand Down Expand Up @@ -105,7 +106,7 @@ module.exports = [
const embedUrl = REPORTS[reportName];
req.log.trace(`Generating embed URL for ${reportName} report, using ${embedUrl} as embed URL.`);
if (embedUrl) {
result = await lookerSerivce.generateEmbedUrl(req.authUser, project, member, embedUrl);
result = await lookerSerivce.generateEmbedUrlForProject(req.authUser, project, member, embedUrl);
} else {
return res.status(404).send('Report not found');
}
Expand Down
97 changes: 76 additions & 21 deletions src/routes/projectReports/getEmbedReport.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -164,7 +164,7 @@ describe('GET embed report', () => {

it('should return 404 when report name not mock and not in EMBED_REPORTS_MAPPING', (done) => {
const cfg = sinon.stub(config, 'get');
cfg.withArgs('lookerConfig.USE_MOCK').returns(false);
cfg.withArgs('lookerConfig.USE_MOCK').returns('false');
request(server)
.get(`/v5/projects/${project1.id}/reports/embed?reportName=random`)
.set({
Expand All @@ -176,10 +176,27 @@ describe('GET embed report', () => {
});
});

it('should return 403 when report name not mock and not in EMBED_REPORTS_MAPPING', (done) => {
const cfg = sinon.stub(config, 'get');
cfg.withArgs('lookerConfig.USE_MOCK').returns('false');
// allows only admin user
cfg.withArgs('lookerConfig.ALLOWED_USERS').returns(`[${testUtil.userIds.admin}]`);
cfg.withArgs('lookerConfig.EMBED_REPORTS_MAPPING').returns('{"mock": "/embed/looks/2"}');
request(server)
.get(`/v5/projects/${project1.id}/reports/embed?reportName=random`)
.set({
Authorization: `Bearer ${testUtil.jwts.member}`,
})
.expect(403, (err) => {
cfg.restore();
done(err);
});
});

it('should return 500 when get admin user error', (done) => {
const cfg = sinon.stub(config, 'get');
const gem = sinon.stub(lookerSerivce, 'generateEmbedUrl', () => 'generatedUrl');
cfg.withArgs('lookerConfig.USE_MOCK').returns(false);
const gem = sinon.stub(lookerSerivce, 'generateEmbedUrlForProject', () => 'generatedUrl');
cfg.withArgs('lookerConfig.USE_MOCK').returns('false');
cfg.withArgs('lookerConfig.EMBED_REPORTS_MAPPING').returns('{"mock-concrete-customer": "/embed/looks/2"}');
request(server)
.get(`/v5/projects/${project1.id}/reports/embed?reportName=mock`)
Expand All @@ -195,8 +212,8 @@ describe('GET embed report', () => {

it('should return 404 when the project template or product template is not found', (done) => {
const cfg = sinon.stub(config, 'get');
const gem = sinon.stub(lookerSerivce, 'generateEmbedUrl', () => 'generatedUrl');
cfg.withArgs('lookerConfig.USE_MOCK').returns(false);
const gem = sinon.stub(lookerSerivce, 'generateEmbedUrlForProject', () => 'generatedUrl');
cfg.withArgs('lookerConfig.USE_MOCK').returns('false');
cfg.withArgs('lookerConfig.EMBED_REPORTS_MAPPING').returns('{"mock-concrete-customer": "/embed/looks/2"}');
request(server)
.get(`/v5/projects/${project0.id}/reports/embed?reportName=mock`)
Expand All @@ -210,10 +227,48 @@ describe('GET embed report', () => {
});
});

it('should return mock url', (done) => {
const cfg = sinon.stub(config, 'get');
const gem = sinon.stub(lookerSerivce, 'generateEmbedUrlForProject', () => 'generatedUrl');
const getUser = sinon.stub(util, 'getTopcoderUser', () => ({
firstName: 'fn',
lastName: 'ln',
userId: testUtil.userIds.member,
}));
cfg.withArgs('lookerConfig.USE_MOCK').returns('true');
cfg.withArgs('lookerConfig.EMBED_REPORTS_MAPPING')
.returns('{"mock": "/customer/embed/looks/2"}');
request(server)
.get(`/v5/projects/${project1.id}/reports/embed?reportName=mock`)
.set({
Authorization: `Bearer ${testUtil.jwts.member}`,
})
.expect('Content-Type', /json/)
.expect(200)
.end((err, res) => {
getUser.restore();
gem.restore();
cfg.restore();
if (err) {
done(err);
} else {
const resJson = res.body;
should.exist(resJson);
resJson.should.equal('generatedUrl');
const [user, project, member, embedUrl] = gem.lastCall.args;
user.userId.should.equal(testUtil.userIds.member);
project.should.deep.equal({ id: project1.id });
member.userId.should.equal(testUtil.userIds.member);
embedUrl.should.equal('/customer/embed/looks/2');
done();
}
});
});

it('should return customer url', (done) => {
const cfg = sinon.stub(config, 'get');
const gem = sinon.stub(lookerSerivce, 'generateEmbedUrl', () => 'generatedUrl');
cfg.withArgs('lookerConfig.USE_MOCK').returns(false);
const gem = sinon.stub(lookerSerivce, 'generateEmbedUrlForProject', () => 'generatedUrl');
cfg.withArgs('lookerConfig.USE_MOCK').returns('false');
cfg.withArgs('lookerConfig.EMBED_REPORTS_MAPPING')
.returns('{"mock-concrete-customer": "/customer/embed/looks/2"}');
request(server)
Expand All @@ -233,9 +288,9 @@ describe('GET embed report', () => {
should.exist(resJson);
resJson.should.equal('generatedUrl');
const [user, project, member, embedUrl] = gem.lastCall.args;
user.userId.should.equal(40051331);
user.userId.should.equal(testUtil.userIds.member);
project.should.deep.equal({ id: project1.id });
member.userId.should.equal(40051331);
member.userId.should.equal(testUtil.userIds.member);
member.role.should.equal('customer');
embedUrl.should.equal('/customer/embed/looks/2');
done();
Expand All @@ -245,13 +300,13 @@ describe('GET embed report', () => {

it('should return admin url', (done) => {
const cfg = sinon.stub(config, 'get');
const gem = sinon.stub(lookerSerivce, 'generateEmbedUrl', () => 'generatedUrl');
const gem = sinon.stub(lookerSerivce, 'generateEmbedUrlForProject', () => 'generatedUrl');
const getAdmin = sinon.stub(util, 'getTopcoderUser', () => ({
firstName: 'fn',
lastName: 'ln',
userId: 40051333,
}));
cfg.withArgs('lookerConfig.USE_MOCK').returns(false);
cfg.withArgs('lookerConfig.USE_MOCK').returns('false');
cfg.withArgs('lookerConfig.EMBED_REPORTS_MAPPING').returns('{"mock-concrete-topcoder": "/admin/embed/looks/2"}');
request(server)
.get(`/v5/projects/${project1.id}/reports/embed?reportName=mock`)
Expand All @@ -271,9 +326,9 @@ describe('GET embed report', () => {
should.exist(resJson);
resJson.should.equal('generatedUrl');
const [user, project, member, embedUrl] = gem.lastCall.args;
user.userId.should.equal(40051333);
user.userId.should.equal(testUtil.userIds.admin);
project.should.deep.equal({ id: project1.id });
member.userId.should.equal(40051333);
member.userId.should.equal(testUtil.userIds.admin);
member.firstName.should.equal('fn');
member.lastName.should.equal('ln');
member.role.should.equal('');
Expand All @@ -285,8 +340,8 @@ describe('GET embed report', () => {

it('should return copilot url', (done) => {
const cfg = sinon.stub(config, 'get');
const gem = sinon.stub(lookerSerivce, 'generateEmbedUrl', () => 'generatedUrl');
cfg.withArgs('lookerConfig.USE_MOCK').returns(false);
const gem = sinon.stub(lookerSerivce, 'generateEmbedUrlForProject', () => 'generatedUrl');
cfg.withArgs('lookerConfig.USE_MOCK').returns('false');
cfg.withArgs('lookerConfig.EMBED_REPORTS_MAPPING').returns('{"mock-concrete-copilot": "/copilot/embed/looks/2"}');
request(server)
.get(`/v5/projects/${project1.id}/reports/embed?reportName=mock`)
Expand All @@ -305,9 +360,9 @@ describe('GET embed report', () => {
should.exist(resJson);
resJson.should.equal('generatedUrl');
const [user, project, member, embedUrl] = gem.lastCall.args;
user.userId.should.equal(40051332);
user.userId.should.equal(testUtil.userIds.copilot);
project.should.deep.equal({ id: project1.id });
member.userId.should.equal(40051332);
member.userId.should.equal(testUtil.userIds.copilot);
member.role.should.equal('copilot');
embedUrl.should.equal('/copilot/embed/looks/2');
done();
Expand All @@ -317,13 +372,13 @@ describe('GET embed report', () => {

it('should return admin url for project with product template', (done) => {
const cfg = sinon.stub(config, 'get');
const gem = sinon.stub(lookerSerivce, 'generateEmbedUrl', () => 'generatedUrl');
const gem = sinon.stub(lookerSerivce, 'generateEmbedUrlForProject', () => 'generatedUrl');
const getAdmin = sinon.stub(util, 'getTopcoderUser', () => ({
firstName: 'fn',
lastName: 'ln',
userId: 40051333,
}));
cfg.withArgs('lookerConfig.USE_MOCK').returns(false);
cfg.withArgs('lookerConfig.USE_MOCK').returns('false');
cfg.withArgs('lookerConfig.EMBED_REPORTS_MAPPING')
.returns('{"mock-prodCut-topcoder": "/admin/embed/looks/3"}');
request(server)
Expand All @@ -344,9 +399,9 @@ describe('GET embed report', () => {
should.exist(resJson);
resJson.should.equal('generatedUrl');
const [user, project, member, embedUrl] = gem.lastCall.args;
user.userId.should.equal(40051333);
user.userId.should.equal(testUtil.userIds.admin);
project.should.deep.equal({ id: project3.id });
member.userId.should.equal(40051333);
member.userId.should.equal(testUtil.userIds.admin);
member.firstName.should.equal('fn');
member.lastName.should.equal('ln');
member.role.should.equal('');
Expand Down
76 changes: 76 additions & 0 deletions src/routes/userReports/getEmbedReport.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
/* eslint-disable no-unused-vars */
import config from 'config';
import _ from 'lodash';
import { middleware as tcMiddleware } from 'tc-core-library-js';
import util from '../../util';
import { USER_ROLE, ADMIN_ROLES, MANAGER_ROLES } from '../../constants';
import lookerSerivce from '../../services/lookerService';

const permissions = tcMiddleware.permissions;


module.exports = [
async (req, res, next) => {
const mockReport = config.get('lookerConfig.USE_MOCK') === 'true';
let reportName = mockReport ? 'mock' : req.query.reportName;
const authUser = req.authUser;
let REPORTS = null;
let allowedUsers = null;
try {
allowedUsers = config.get('lookerConfig.ALLOWED_USERS');
allowedUsers = allowedUsers ? JSON.parse(allowedUsers) : [];
req.log.trace(allowedUsers, 'allowedUsers');
REPORTS = JSON.parse(config.get('lookerConfig.EMBED_REPORTS_MAPPING'));
} catch (error) {
req.log.error(error);
req.log.debug('Invalid reports mapping. Should be a valid JSON.');
}
if (!mockReport && !REPORTS) {
return res.status(404).send('Report not found');
}

try {
const isAdmin = util.hasRoles(req, ADMIN_ROLES);
const userDisallowed = allowedUsers.length > 0 && !allowedUsers.includes(authUser.userId);
if (userDisallowed) {
req.log.error(`User whitelisting prevented accessing report ${reportName} to ${authUser.userId}`);
return res.status(403).send('User is not allowed to access the report');
}
const token = await util.getM2MToken();
const callerUser = await util.getTopcoderUser(authUser.userId, token, req.log);
req.log.trace(callerUser, 'callerUser');
const member = {
firstName: callerUser.firstName,
lastName: callerUser.lastName,
userId: authUser.userId,
role: '',
};
let roleKey = '';
if (!mockReport) {
if (util.hasRoles(req, [USER_ROLE.COPILOT])) {
roleKey = 'copilot';
} else if (isAdmin || util.hasRoles(req, MANAGER_ROLES)) {
roleKey = 'topcoder';
} else {
roleKey = 'customer';
}
reportName = `${reportName}-${roleKey}`;
}
// pick the report based on its name
let result = {};
const embedUrl = REPORTS[reportName];
req.log.trace(`Generating embed URL for ${reportName} report, using ${embedUrl} as embed URL.`);
if (embedUrl) {
result = await lookerSerivce.generateEmbedUrlForUser(req.authUser, member, embedUrl);
} else {
return res.status(404).send('Report not found');
}

req.log.trace(result);
return res.status(200).json(result);
} catch (err) {
req.log.error(err);
return res.status(500).send(err.toString());
}
},
];
Loading