Skip to content

Commit

Permalink
Initial commit of Hapiness
Browse files Browse the repository at this point in the history
  • Loading branch information
arpit-systango committed Jan 6, 2017
0 parents commit 7f699fe
Show file tree
Hide file tree
Showing 143 changed files with 11,442 additions and 0 deletions.
3 changes: 3 additions & 0 deletions .babelrc
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
{
"presets" : ["es2015", "react"]
}
8 changes: 8 additions & 0 deletions .env
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
#DEBUGGER=true
NODE_ENV=development
#NODE_ENV=production
WEB_PORT=8000
API_PORT=8001
COOKIE_SECRET=MyCookieSecret_ThisShould_be_32_character_long
YAR_COOKIE_SECRET=MyYarCookieSecret_ThisShould_be_32_character_long
JWT_SECRET=MySecretKey_ThisShould_be_32_character_long
28 changes: 28 additions & 0 deletions .eslintrc
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
env:
browser: true
commonjs: true
es6: true
node: true
extends: 'eslint:recommended'
parserOptions:
ecmaFeatures:
experimentalObjectRestSpread: true
jsx: true
sourceType: module
plugins:
- react
rules:
linebreak-style:
- error
- unix
quotes:
- error
- single
semi:
- error
- always
curly: error
eqeqeq: error
no-empty: warn
no-console: off
no-unused-vars: off
43 changes: 43 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
# Logs
logs
*.log
npm-debug.log*

# Runtime data
pids
*.pid
*.seed

# Directory for instrumented libs generated by jscoverage/JSCover
lib-cov

# Coverage directory used by tools like istanbul
coverage

# Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files)
.grunt

# node-waf configuration
.lock-wscript

# Compiled binary addons (http://nodejs.org/api/addons.html)
build/Release

# Dependency directory
node_modules
node_modules/

# Optional npm cache directory
.npm

# Optional REPL history
.node_repl_history


# Sublime Project Files
*.sublime-project
*.sublime-workspace

# Project specific ignore
./log/hapiness.log
.build
21 changes: 21 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2017 Systango-Admin

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
103 changes: 103 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,103 @@
## Hapiness
Production ready Hapi boilerplate application with dual servers inbuilt.

## Credits
Thanks to ravisuhag/jolly for their wonderful boilerplate app which became the base of Hapiness.

## Description
'Hapiness' boilerplate application serves as a great starting point for all the Hapi.js developers who were looking for a platform for their production servers. This app instantiates two servers on startup:

1) localhost:8000 - Server for web application
2) localhost:8001 - Server for mobile/Rest APIs

Both the servers have their independent authentication mechanisms, the web application server uses the cookie based authentication and the api server uses the JWT authentication for the rest api access. The deployment and application management is done via 'Gulp' and there are different configurations/tasks for starting the app in the development vs the prodcution environment. This application assumes the availibility of 'MongoDB' installation on the localhost where the server will run.

For production, we have used 'PM2' as the process manager which spawns 4 servers for the application and takes care of the rest of application life cycle management. All the environment variables are managed using 'dotenv' node package for development, the same will need to be configured at the host server in the production environment.

If you are using 'Chrome' for unit testing the application, you can Hapi-ly use the 'node-inspector' chrome plugin pre-configured with this app for debugging purposes.

## TO-DO
One of the items we have identified for future is cotainerizing the app using 'Docker'.

## Technology

- **Hapi** - Server side framework
- **Handlebar** - HTML templating engine
- **Mongoose** - Mongo database ORM
- **SASS** - CSS preprocessor
- **Gulp** - Javascript tasks automation
- **WebPack** - Asset pipeline
- **Dotenv** - Environment variable emulator
- **Good** - Logger mechanism
- **JWT** - Authentication mechanism for APIs
- **Config** - Configuration Handler
- **PM2** - Production process manager for Node.js apps


## Application Structure

```
|
| -- app
| |-- controllers // Controllers are organised by module names
| | |-- <module_name> // Each controller defines config and handler for that route.
| |
| |-- helpers // Helper functions used across application
| |-- models // All mongoose models are defined here
| |-- routes // All app routes are defined here
| | |-- <route_plugin> // Route module is a hapi plugin and can be toggled from config/manifest.js
| |
| `-- templates // All server-rendered handlebar templates, partials and helpers
| |-- <module_name> // Templates are organised by module names.
|
|-- assets // Contains all static resources
| |-- fonts // Fonts used in application
| |-- images // Images used in application
| |-- misc // Misc resources used in application
| |-- scripts // Client javscripts files which are then packed by webpack
| |-- styles // All SASS stylesheets
| | |-- <module_name> // Styles are organised by module names.
|
|-- config // Contains all app configurations
| |-- assets.js // Assets configuration file
| |-- config.js // Application configuration file which stores all passwords etc. (gitignore).
| |-- manifest.js // App manifest file listing all plugins and load order.
| |-- meta.js // App metadata file.
|
|-- lib // Core application lib/plugins
|-- tasks // Contains all gulp tasks
|
|-- gulpfile.js // Gulp entry file
|-- index.js // Application starting point
|-- package.js // Package configuration file
|-- server.js // Main server file
|-- .env // dotenv configuration file for environment variable management
|-- .gitignore // standrd git ignore file
|-- .babelrc // Babel config
|-- .eslintrc // WebPack config
```

## Code

We're using semi-colons and comma-last. No rhyme or reason; and some of the hapi [code convention guidelines](http://hapijs.com/styleguide). All client-side js code is also in commonJS pattern packs using webpack. Check out `.eslintrc` for additional code conventions used.

## Running the server locally

- Install `node`, `npm`
- Run these commands

```sh
# Install deps
$ npm install

# Run the node server
$ gulp

```
The servers should be running at [localhost:8000](https://localhost:8000) and [localhost:8001](https://localhost:8001).

```
## Contributers
Systango-Technologies
40 changes: 40 additions & 0 deletions app/controllers/auth/jwtlogin.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
'use strict';
var Boom = require('boom');
var proxy = require('../../utils/proxy');
var JWT = require('jsonwebtoken');
const Joi = require('joi');
const Config = require('../../../config/config');

exports.postCredentials = {
description: 'jwt login',
validate: {
payload: {
email: Joi.string().min(3).max(20).email().required(),
password: Joi.string().min(6).max(20).required(),
id: Joi.string().required()
},
failAction: function(request, reply, source, error) {
// Username, passowrd minimum validation failed
console.log('Username, Invalid username or password');
return reply.redirect('/');
}
},
handler: function(request, reply) {
console.log('post jwt-login reached');
proxy.externalAppLogin(request,reply,function(err,is_authenticated,msg){
if(err){
reply(Boom.unauthorized(msg));
}
if(is_authenticated){
let secret = Config.get('/jwtAuthOptions/key');
let obj = {
id:request.payload.id,
'username': request.payload.email
}; // object info you want to sign
let jwtToken = JWT.sign(obj, secret, { expiresIn: '1 day' });
reply({text: msg}).header('Authorization', jwtToken);
}
});
},
tags: ['api'] //swagger documentation
};
72 changes: 72 additions & 0 deletions app/controllers/auth/login.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
'use strict';

const Mongoose = require('mongoose');
const Joi = require('joi');
const User = Mongoose.model('User');

exports.showForm = {
description: 'Returns the login page',
auth: {
mode: 'try',
strategy: 'standard'
},
handler: function(request, reply) {

if (request.auth.isAuthenticated) {
return reply.redirect('/dashboard');
}
reply.view('auth/login');

},
tags: ['api'] //swagger documentation
};

exports.postForm = {
description: 'Post to the login page',
auth: {
mode: 'try',
strategy: 'standard'
},
plugins: {
crumb: {
key: 'crumb',
source: 'payload',
}
},
validate: {
payload: {
email: Joi.string().min(3).max(20).email().required(),
password: Joi.string().min(6).max(20).required()
},
failAction: function(request, reply, source, error) {
console.log('Username, passowrd minimum validation failed');
// Username, passowrd minimum validation failed
request.yar.flash('error', 'Invalid username or password');
return reply.redirect('/');
}
},
handler: function(request, reply) {
console.log('post login reached');
if (request.auth.isAuthenticated) {
return reply.redirect('/dashboard');
}

User.findByCredentials(request.payload.email, request.payload.password, function(err, user, msg) {
if (err) {
// Boom bad implementation
request.yar.flash('error', 'An internal server error occurred');
return reply.redirect('/');
}
if (user) {
request.cookieAuth.set(user);
return reply.redirect('/dashboard');
} else {
// User not fond in database
request.yar.flash('error', 'Invalid username or password');
return reply.redirect('/');
}
});

},
tags: ['api'] //swagger documentation
};
21 changes: 21 additions & 0 deletions app/controllers/auth/logout.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
'use strict';

module.exports = {
auth: {
strategy: 'standard'
},
plugins: {
crumb: {
key: 'crumb',
source: 'payload',
restful: true
}
},
handler: function(request, reply) {

request.cookieAuth.clear();
request.yar.flash('success', 'Logged out successfully');
return reply.redirect('/login');

}
};
Loading

0 comments on commit 7f699fe

Please sign in to comment.