Skip to content
This repository has been archived by the owner on Jan 15, 2021. It is now read-only.

Connected client to api gateway; auth and checkout service working E2E #49

Merged
merged 3 commits into from
May 17, 2017
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
13 changes: 13 additions & 0 deletions .vscode/launch.json
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,13 @@
"Launch Chrome",
"Launch Sticker App"
]
},
{
"name": "Client-Server Gateway",
"configurations": [
"Launch Chrome",
"Launch Sticker App Gateway"
]
}
],
"configurations": [
Expand Down Expand Up @@ -43,6 +50,12 @@
"request": "launch",
"name": "Launch Sticker App",
"program": "${workspaceRoot}/server/index.js"
},
{
"type": "node",
"request": "launch",
"name": "Launch Sticker App Gateway",
"program": "${workspaceRoot}/apigateway/app.js"
}
]
}
9 changes: 9 additions & 0 deletions apigateway/Dockerfile
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
FROM node:latest
LABEL Name=stickerapp-apigateway Version=0.1.0
COPY package.json /tmp/package.json
RUN cd /tmp && npm install
RUN mkdir -p /usr/src/app && mv /tmp/node_modules /usr/src
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm curious: what's the advantage here over installing dependencies directly to /usr/src?

Copy link
Collaborator Author

@nicolehaugen nicolehaugen May 15, 2017

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I inadvertently included the docker files - I still have to finish this part of the check in before I have it reviewed. Also, I think Mike actually created this docker file and included it with his PR. Anyway, I will remove this file from this PR - you should add your comment to his.

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I just copied the Dockerfile Chris used for the web client. I agree that it seems like an unusual pattern; I'm not sure what the reasoning is.

WORKDIR /usr/src/app
COPY . /usr/src/app
EXPOSE 3000
CMD npm start
53 changes: 35 additions & 18 deletions apigateway/app.js
Original file line number Diff line number Diff line change
@@ -1,17 +1,29 @@
'use strict';

var express = require('express');
var session = require('express-session');
var path = require('path');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var passport = require('passport');
var authService = require('./services/auth');
var serverConnection = require('./config/database-config').serverConnection;

var index = require('./routes/index');
var users = require('./routes/users');
var profile = require('./routes/profile');
var app = express();
const logger = require('morgan');
const cookieParser = require('cookie-parser');
const passport = require('passport');

const authService = require('./services/auth');
const serverConnection = require('./config/database-config').serverConnection;

const users = require('./routes/users');
const browse = require('./routes/browse');
const cart = require('./routes/cart');
const feedback = require('./routes/feedback');
const create = require('./routes/create');
const checkout = require('./routes/checkout');

const app = express();

const PROJECT_ROOT = path.join(__dirname, '..');
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This path is incorrect for the given Docker configuration, and awkward in general. I think required files should be below the application in the tree.

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good catch - I'm going to put a TODO comment above this line. I'd like to get all of the changes Mike made for docker in and then adjust this accordingly.

app.set('etag', false);
app.set('views', path.join(PROJECT_ROOT, 'apigateway', 'templates'));
app.set('view engine', 'pug');
app.use(express.static(path.join(PROJECT_ROOT, 'client', 'dist')));

require('./strategy/aad-b2c')();
require('./strategy/passport')();
Expand All @@ -23,21 +35,26 @@ app.use(session({
}));

app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

app.use(passport.initialize());
app.use(passport.session());

app.use('/', index);
app.use('/users', users);
app.use('/profile', profile);

// setup the auth's datastore where authenticated user\profile data is stored
authService.setupAuthDataStore();

app.use('/feedback', feedback);
app.use('/users', users);
app.use('/browse', browse);
app.use('/cart', cart);
app.use('/create', create);
app.use('/checkout', checkout);

app.get('/', function stickerRootRedirection(req, res) {
console.log('app.js: redirecting to browse');
res.redirect('/browse');
});

const server = app.listen(serverConnection.port, () => {
console.log(`Sticker server running on port ${server.address().port}`);
});
Expand Down
5 changes: 0 additions & 5 deletions apigateway/config/database-config.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,3 @@

//TODO: Need to get the connection URL from env variable to support when deployed
//e.g. process.env.DB_URL or something equivalent

//TODO: Add info in instructions that the MySQL db needs to be created by the user first
exports.dbSettings = {
URI: process.env.DB_URL || 'mysql://root:Admin_007@localhost/StickerDemoApp'
};
Expand Down
6 changes: 6 additions & 0 deletions apigateway/config/services-config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
module.exports = {

//Default URL for the checkout service which provides Feedback and Order CRUD operations
checkoutServiceUrl: 'http://localhost:5000'
};

26 changes: 26 additions & 0 deletions apigateway/npm-debug.log
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
0 info it worked if it ends with ok
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Stowaway file.

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yep missed this - removing now.

1 verbose cli [ 'C:\\Program Files (x86)\\nodejs\\node.exe',
1 verbose cli 'C:\\Program Files (x86)\\nodejs\\node_modules\\npm\\bin\\npm-cli.js',
1 verbose cli 'run',
1 verbose cli 'build' ]
2 info using [email protected]
3 info using [email protected]
4 verbose stack Error: missing script: build
4 verbose stack at run (C:\Program Files (x86)\nodejs\node_modules\npm\lib\run-script.js:151:19)
4 verbose stack at C:\Program Files (x86)\nodejs\node_modules\npm\lib\run-script.js:61:5
4 verbose stack at C:\Program Files (x86)\nodejs\node_modules\npm\node_modules\read-package-json\read-json.js:356:5
4 verbose stack at checkBinReferences_ (C:\Program Files (x86)\nodejs\node_modules\npm\node_modules\read-package-json\read-json.js:320:45)
4 verbose stack at final (C:\Program Files (x86)\nodejs\node_modules\npm\node_modules\read-package-json\read-json.js:354:3)
4 verbose stack at then (C:\Program Files (x86)\nodejs\node_modules\npm\node_modules\read-package-json\read-json.js:124:5)
4 verbose stack at ReadFileContext.<anonymous> (C:\Program Files (x86)\nodejs\node_modules\npm\node_modules\read-package-json\read-json.js:295:20)
4 verbose stack at ReadFileContext.callback (C:\Program Files (x86)\nodejs\node_modules\npm\node_modules\graceful-fs\graceful-fs.js:78:16)
4 verbose stack at FSReqWrap.readFileAfterOpen [as oncomplete] (fs.js:366:13)
5 verbose cwd C:\Repos\StickerApp_Integrate_Final\StickerApp\apigateway
6 error Windows_NT 10.0.15063
7 error argv "C:\\Program Files (x86)\\nodejs\\node.exe" "C:\\Program Files (x86)\\nodejs\\node_modules\\npm\\bin\\npm-cli.js" "run" "build"
8 error node v6.10.2
9 error npm v3.10.10
10 error missing script: build
11 error If you need help, you may report this error at:
11 error <https://github.com/npm/npm/issues>
12 verbose exit [ 1, true ]
11 changes: 10 additions & 1 deletion apigateway/package.json
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
{
{
"name": "apigateway",
"version": "0.0.0",
"private": true,
Expand All @@ -10,11 +10,20 @@
"cookie-parser": "~1.4.3",
"debug": "~2.6.0",
"express": "~4.14.1",
"express-http-proxy": "^1.0.1",
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't see debug or express-http-proxy used anywhere.

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

No they're not used...removed them.

"express-session": "^1.15.2",
"guid": "0.0.12",
"morgan": "~1.7.0",
"mysql": "^2.13.0",
"passport": "^0.3.2",
"passport-azure-ad": "^3.0.6",
"pug": "^2.0.0-rc.1",
"request": "^2.81.0",
"sequelize": "^3.30.4"
},
"devDependencies": {
"gulp": "^3.9.1",
"gulp-eslint": "^3.0.1",
"lodash": "^4.17.4"
}
}
38 changes: 38 additions & 0 deletions apigateway/routes/browse.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
'use strict';

const express = require('express');
const bodyParser = require('body-parser');
const router = express.Router();

const dataAccess = require('../temp/db/data-access');

router.use(bodyParser.json());

router.get('/', function stickerRouteBrowse(req, res) {
const renderData = { pageTitle: 'Browse', entry: 'browse' };

console.log('Render values: ', renderData);

res.render('index', renderData);
});

router.get('/api/items', function stickerRouteApiBrowse(req, res) {
// Do things with req.query.tags
let tags;
if (req.query.tags) {
tags = req.query.tags.split(',');
}

dataAccess.getStickers(tags, (items) => {
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is this something that will move into its own microservice eventually? I feel like doing data access for stickers from the API gateway muddies our microservice architecture and should be handled by a separate service.

Copy link
Collaborator

@chlowell chlowell May 16, 2017

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes, on my dev branch I've rewritten this to get data from the sticker service.

console.info('%d stickers found', items.length);
if (tags) {
console.log('Tags used in filter: ', tags);
}

res.send({
items
});
});
});

module.exports = router;
65 changes: 65 additions & 0 deletions apigateway/routes/cart.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
'use strict';

//TODO: This functionality is temporary until integated with the new cart microservice; note that this currently calls into the "dummy" data access layer
const express = require('express');
const bodyParser = require('body-parser');
const dataAccess = require('../temp/db/data-access');

const router = express.Router();
router.use(bodyParser.json());

router.get('/', function stickerRouteCart(req, res) {
res.render('index', { pageTitle: 'Cart', entry: 'cart' });
});

function sendItems(token, res) {
dataAccess.getCart(token, (items) => {
dataAccess.getStickers(null, (stickers) => {
res.send({
items: items.map((id) => stickers.filter((sticker) => sticker.id.toString() === id)[0])
});
});
});
}

router.get('/api/items', (req, res) => {
if (!req.query.token) {
res.status(401).send('Unauthorized');
return;
}
sendItems(req.query.token, res);
});

router.put('/api/items/:item_id', (req, res) => {
if (!req.body.token) {
res.status(401).send('Unauthorized');
return;
}

console.log('Item targetted %s', req.params.item_id);

dataAccess.addToCart(req.body.token, req.params.item_id, () => {
dataAccess.getSticker(req.params.item_id, (item) => {
if (!item) {
dataAccess.addStickers([ req.body.item ], () => sendItems(req.body.token, res));
} else {
sendItems(req.body.token, res);
}
});
});
});

router.delete('/api/items/:item_id', (req, res) => {
if (!req.body.token) {
res.status(401).send('Unauthorized');
return;
}

console.log('Item targetted', req.params.item_id);

dataAccess.removeFromCart(req.body.token, req.params.item_id, () => {
sendItems(req.body.token, res);
});
});

module.exports = router;
54 changes: 54 additions & 0 deletions apigateway/routes/checkout.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@

'use strict';

//TODO: This is temporary using the "dummy" data access layer in order to interact with the cart; this will be removed when integrated with new cart microservice
const dataAccess = require('../temp/db/data-access');

const express = require('express');
const request = require('request');
const guid = require('guid');

//This route calls into the ASP.NET Core checkout microservice
const checkoutServiceUrl = require('../config/services-config').checkoutServiceUrl; //TODO: add env url lookup
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

As mentioned in the TODO, we should prefer a URL from the environment since that will allow docker-compose files to organize services, as needed.

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes agree - I am going to address this once Charles gets all the docker stuff checked in.


const router = express.Router();
const bodyParser = require('body-parser');
router.use(bodyParser.urlencoded({ extended: true }));

//Ensures that the user is authenticated prior to calling into this route
const authService = require('../services/auth');
router.use(authService.isUserLoggedIn);
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This middleware could be moved into app.js, before the routes requiring authentication.

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Sure, I had it there originally, and then moved it since not all the services require it...but I do agree that it would be clearer to have it in the app.js...so I'll move that back now. :)


router.post('/', function stickerRouteCheckout(req, res) {

var orderJson = {
'Id': guid.raw(),
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

These properties needn't be strings.

'FullName' : req.body['checkout-name'],
'Email' : req.body['checkout-email'],
'Items' : req.body['checkout-items']
};

request({
url: checkoutServiceUrl + '/api/order/',
method: 'POST',
json: true,
body: orderJson,
headers: {
//Pass the current authenticated user's id to the checkout microservice
'stickerUserId': req.user.id
}},
function finishAddOrder(error){
if (error) {
console.log('Adding Order failed: ' + error);
} else {
console.log('Order added');
}

//TODO: Need to update this when the new cart microservice is integrated; for now, calls into the "dummy" data access layer
dataAccess.clearCart(req.body.token, () => {
res.render('index', { pageTitle: 'Checkout', entry: 'checkout' });
});
});
});

module.exports = router;
Loading