Skip to content

Instantly share code, notes, and snippets.

@hesahesa

hesahesa/app.js Secret

Last active April 24, 2016 09:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hesahesa/8d54852e9ef0546b96765f056653aa24 to your computer and use it in GitHub Desktop.
Save hesahesa/8d54852e9ef0546b96765f056653aa24 to your computer and use it in GitHub Desktop.
Intel Edison Cloud Backend using OpenShift
/**
* Created by hesahesa.
*/
var express = require('express');
var path = require('path');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var exphbs = require('express-handlebars');
var routes = require('./routes/index');
var app = express();
app.engine('.hbs', exphbs({extname: '.hbs'}));
app.set('view engine', '.hbs');
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('/', routes);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
// error handlers
//================
// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.send('error'+ err.message );
});
}
// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.send('error'+ err.message );
});
// force HTTPS openshift
//app.use(function(err, req, res, next) {
// if (req.headers['x-forwarded-proto'] == 'http') {
// res.redirect('https://' + req.headers.host + req.path);
// } else {
// return next();
// }
//});
module.exports = app;
/**
* Created by hesahesa
*/
var express = require('express');
var multer = require('multer');
var MongoClient = require('mongodb'),MongoClient;
var assert = require('assert');
var randomstring = require('randomstring');
var csurf = require('csurf');
var path = require('path');
var ObjectId = require('mongodb').ObjectID;
var upload = multer();
var router = express.Router();
var csrfProtection = csurf({ cookie: true });
var S = require('string');
var MONGO_URL = "YOUR_MONGO_CONNECTION_STRING_HERE";
// intel edison endpoint
router.post('/edison/payment/counter', function(req, res, next) {
var paymentToken = req.body.paymenttoken;
var ammount = req.body.ammount;
// insert to mongo db
var dataObject = {
'paymentToken' : paymentToken,
'ammount' : ammount,
'createdAt' : new Date()
};
var insertDocument = function(db, callback) {
db.collection('countertrx').insertOne( dataObject, function(err, result) {
assert.equal(err, null);
console.log("Inserted a document into the counter trx collection.");
callback(result);
});
};
MongoClient.connect(MONGO_URL, function(err, db) {
assert.equal(null, err);
insertDocument(db, function() {
db.close();
});
});
// return result, assuming success for hackathon purpose, owyeah
res.send('ok');
});
router.post('/edison/payment/iot', function(req, res, next) {
var paymentToken = req.body.paymenttoken;
var userToken = req.body.usertoken;
var ammount = req.body.ammount;
// case of failure, for testing purpose
if(S(userToken).startsWith('fail')) {
res.send('fail');
}
// insert to mongo db
var dataObject = {
'paymentToken' : paymentToken,
'userToken' : userToken,
'ammount' : ammount,
'createdAt' : new Date()
};
var insertDocument = function(db, callback) {
db.collection('iottrx').insertOne( dataObject, function(err, result) {
assert.equal(err, null);
console.log("Inserted a document into the iot trx collection.");
callback(result);
});
};
MongoClient.connect(MONGO_URL, function(err, db) {
assert.equal(null, err);
insertDocument(db, function() {
db.close();
});
});
// in reality, should charge for payment from user in here
// return result, assuming success for hackathon purpose, owyeah
res.send('ok');
});
router.get('/edison/payment/all', function(req, res, next) {
var findDocuments = function(db, callback) {
// Get the documents collection
var collection = db.collection('iottrx');
// Find some documents
collection.find({}).toArray(function(err, docs) {
res.send(docs);
callback(docs);
});
}
MongoClient.connect(MONGO_URL, function(err, db) {
assert.equal(null, err);
findDocuments(db, function() {
db.close();
});
});
});
router.get('/edison/payment/ui', function(req, res, next) {
res.sendfile(path.join(__dirname, '../static/mailbox.html'));
});
module.exports = router;
<!doctype html>
<!--
Material Design Lite
Copyright 2015 Google Inc. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
https://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License
-->
<html lang="en" ng-app="mailboxApp">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="description" content="Nonce.ID Temporary and Shareable Email">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Alstublieft Transaction Log</title>
<!-- Add to homescreen for Chrome on Android -->
<meta name="mobile-web-app-capable" content="yes">
<link rel="icon" sizes="192x192" href="../../images/android-desktop.png">
<!-- Add to homescreen for Safari on iOS -->
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-status-bar-style" content="black">
<meta name="apple-mobile-web-app-title" content="Material Design Lite">
<link rel="apple-touch-icon-precomposed" href="../../images/ios-desktop.png">
<!-- Tile icon for Win8 (144x144 + tile color) -->
<meta name="msapplication-TileImage" content="../../images/touch/ms-touch-icon-144x144-precomposed.png">
<meta name="msapplication-TileColor" content="#3372DF">
<link rel="shortcut icon" href="../../images/favicon.png">
<!-- SEO: If your mobile URL is different from the desktop URL, add a canonical link to the desktop page https://developers.google.com/webmasters/smartphone-sites/feature-phones -->
<!--
<link rel="canonical" href="http://www.example.com/">
-->
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Roboto:regular,bold,italic,thin,light,bolditalic,black,medium&amp;lang=en">
<link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons">
<link rel="stylesheet" href="https://code.getmdl.io/1.1.1/material.deep_purple-pink.min.css">
<link rel="stylesheet" href="../../styles.css">
<style>
#view-source {
position: fixed;
display: block;
right: 0;
bottom: 0;
margin-right: 40px;
margin-bottom: 40px;
z-index: 900;
}
</style>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.0/angular.min.js"></script>
</head>
<body class="mdl-demo mdl-color--grey-100 mdl-color-text--grey-700 mdl-base" ng-controller="MailboxCtrl">
<div class="mdl-layout mdl-js-layout mdl-layout--fixed-header">
<main class="mdl-layout__content">
<div class="mdl-layout__tab-panel is-active" id="overview">
<section class="section--center mdl-grid mdl-grid--no-spacing mdl-shadow--2dp">
<div class="mdl-card mdl-cell mdl-cell--12-col">
<div class="mdl-card__supporting-text mdl-grid mdl-grid--no-spacing">
<h4 class="mdl-cell mdl-cell--12-col">Transactions log </h4>
<table class="mdl-data-table mdl-cell--12-col mdl-js-data-table mdl-shadow--2dp">
<colgroup>
<col span="1" style="width: 40%;">
<col span="1" style="width: 40%;">
<col span="1" style="width: 20%;">
</colgroup>
<thead>
<tr>
<th class="mdl-data-table__cell--non-numeric">Payment Token</th>
<th class="mdl-data-table__cell--non-numeric">User Token</th>
<th class="mdl-data-table__cell--non-numeric">Ammount</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="trx in trxs">
<td class="mdl-data-table__cell--non-numeric" style="white-space: nowrap; text-overflow:ellipsis; overflow: hidden; max-width:1px;">{{trx.paymentToken}}</td>
<td class="mdl-data-table__cell--non-numeric" style="white-space: nowrap; text-overflow:ellipsis; overflow: hidden; max-width:1px;">{{trx.userToken}}</td>
<td class="mdl-data-table__cell--non-numeric" style="white-space: nowrap; text-overflow:ellipsis; overflow: hidden; max-width:1px;">{{trx.ammount}}</td>
</tr>
</tbody>
</table>
</div>
</div>
</section>
<section class="section--center mdl-grid mdl-grid--no-spacing mdl-shadow--2dp">
<div class="mdl-card mdl-cell mdl-cell--12-col">
<div class="mdl-card__supporting-text mdl-grid mdl-grid--no-spacing">
<img src="../../images/revenue_chart.png" class="mdl-cell mdl-cell--12-col mdl-typography--text-center" />
</div>
</div>
</section>
</div>
</main>
</div>
<!-- snackbar -->
<div id="demo-snackbar-example" class="mdl-js-snackbar mdl-snackbar">
<div class="mdl-snackbar__text"></div>
<button class="mdl-snackbar__action" type="button"></button>
</div>
<script src="https://code.getmdl.io/1.1.1/material.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script>window.jQuery || document.write('<script src="js/jquery-1.10.2.min.js"><\/script>')</script>
<script>
'use strict';
var mailboxApp = angular.module('mailboxApp', []);
mailboxApp.controller('MailboxCtrl', function ($scope, $http, $interval) {
$http.get('../payment/all').success(function(data) {
$scope.trxs = data;
console.log($scope.trx);
});
});
</script>
</body>
</html>
#!/bin/env node
var AppContainer = function () {
// Scope.
var self = this;
/* ================================================================ */
/* Helper functions. */
/* ================================================================ */
/**
* Set up server IP address and port # using env variables/defaults.
*/
self.setupVariables = function () {
// Set the environment variables we need.
self.ipaddress = process.env.OPENSHIFT_NODEJS_IP;
self.port = process.env.OPENSHIFT_NODEJS_PORT || 8080;
if (typeof self.ipaddress === "undefined") {
// Log errors on OpenShift but continue w/ 127.0.0.1 - this
// allows us to run/test the app locally.
console.warn('No OPENSHIFT_NODEJS_IP var, using 127.0.0.1');
self.ipaddress = "127.0.0.1";
}
};
/**
* terminator === the termination handler
* Terminate server on receipt of the specified signal.
* @param {string} sig Signal to terminate on.
*/
self.terminator = function (sig) {
if (typeof sig === "string") {
console.log('%s: Received %s - terminating sample app ...',
Date(Date.now()), sig);
process.exit(1);
}
console.log('%s: Node server stopped.', Date(Date.now()));
};
/**
* Setup termination handlers (for exit and a list of signals).
*/
self.setupTerminationHandlers = function () {
// Process on exit and signals.
process.on('exit', function () {
self.terminator();
});
// Removed 'SIGPIPE' from the list - bugz 852598.
['SIGHUP', 'SIGINT', 'SIGQUIT', 'SIGILL', 'SIGTRAP', 'SIGABRT',
'SIGBUS', 'SIGFPE', 'SIGUSR1', 'SIGSEGV', 'SIGUSR2', 'SIGTERM'
].forEach(function (element, index, array) {
process.on(element, function () {
self.terminator(element);
});
});
};
/**
* Initializes the sample application.
*/
self.initialize = function () {
self.setupVariables();
self.setupTerminationHandlers();
};
self.setupServer = function () {
/**
* Module dependencies.
*/
var app = require('./app');
var http = require('http');
/**
* Get port from environment and store in Express.
*/
var port = normalizePort(self.port);
/**
* Create HTTP server.
*/
var server = http.createServer(app);
/**
* Listen on provided port, on all network interfaces.
*/
server.listen(self.port, self.ipaddress, function () {
console.log('%s: Node server started on %s:%d ...',
Date(Date.now()), self.ipaddress, self.port);
});
server.on('error', onError);
server.on('listening', onListening);
/**
* Normalize a port into a number, string, or false.
*/
function normalizePort(val) {
var port = parseInt(val, 10);
if (isNaN(port)) {
// named pipe
return val;
}
if (port >= 0) {
// port number
return port;
}
return false;
}
/**
* Event listener for HTTP server "error" event.
*/
function onError(error) {
if (error.syscall !== 'listen') {
throw error;
}
var bind = typeof port === 'string'
? 'Pipe ' + port
: 'Port ' + port;
// 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;
}
}
/**
* Event listener for HTTP server "listening" event.
*/
function onListening() {
var addr = server.address();
console.log('Server on port : ' + addr.port);
}
};
};
/**
* main(): Main code.
*/
var zapp = new AppContainer();
zapp.initialize();
zapp.setupServer();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment