Skip to content

Commit

Permalink
Merge branch 'JWT_Authentication'
Browse files Browse the repository at this point in the history
  • Loading branch information
unknown committed Dec 11, 2017
2 parents a4ec9e4 + 86d5280 commit 9c3d47f
Show file tree
Hide file tree
Showing 100 changed files with 3,744 additions and 1,884 deletions.
104 changes: 38 additions & 66 deletions app.js
Original file line number Diff line number Diff line change
@@ -1,19 +1,21 @@
require('dotenv').config({path: 'config/application.env'});
var express = require('express');
var app = express();
var server = require('http').createServer(app);
var io = require('socket.io')(server);
app.io = io;
server.listen(process.env.PORT || '3000');
var port = process.env.PORT || 3000;
server.listen(port);
var path = require('path');
var favicon = require('serve-favicon');
var morgan = require('morgan');
var bodyParser = require('body-parser');
require('dotenv').config({path: 'config/local.env'});

// Mongo
var mongoose = require('mongoose');
mongoose.Promise = global.Promise;

require('./models/Authorization');
require('./models/Player');
require('./models/Team');
require('./models/Challenge');
Expand All @@ -22,31 +24,39 @@ require('./models/Alert');

var db_uri = process.env.MONGODB_URI;
if (!db_uri) {
console.log('Defaulting to local mongo db instance.');
console.log('Defaulting to local instance.');
db_uri = 'mongodb://127.0.0.1/sparcPongDb';
process.env.LADDER_URL = 'http://127.0.0.1:' + port;
}
mongoose.connect(db_uri);

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');

app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(morgan(process.env.MORGAN_FORMAT || 'tiny'));
app.use(favicon(path.join(__dirname, 'public/images', 'favicon.ico')));
if (process.env.MORGAN_FORMAT !== 'none') {
app.use(morgan(process.env.MORGAN_FORMAT || 'tiny'));
}
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(express.static(path.join(__dirname, 'public')));

// Include scripts
app.use('/bower', express.static(path.join(__dirname, 'bower_components')));
app.use('/node_modules', express.static(path.join(__dirname, 'node_modules')));

// JWT Security
var auth = require('./middleware/jwtMiddleware');
app.use(['/api/team/*', '/api/challenge/*', '/api/playerAlerts/*', '/api/envBridge/*'], auth.jwtAuthProtected);

app.use('/', require('./routes/basic'));
app.use('/api/player', require('./routes/player'));
app.use('/api/team', require('./routes/team'));
app.use('/api/challenge/player', require('./routes/challenges/playerChallenge'));
app.use('/api/challenge/team', require('./routes/challenges/teamChallenge'));
app.use('/api/playerAlerts', require('./routes/alert'));
app.use('/api/envBridge', require('./routes/envBridge'));
app.use('/', require('./routes/EjsViewController'));
app.use('/auth', require('./routes/AuthorizationController'));
app.use('/api/player', require('./routes/PlayerController'));
app.use('/api/team', require('./routes/TeamController'));
app.use('/api/challenge/player', require('./routes/challenges/PlayerChallengeController'));
app.use('/api/challenge/team', require('./routes/challenges/TeamChallengeController'));
app.use('/api/playerAlerts', require('./routes/AlertController'));
app.use('/api/envBridge', require('./routes/EnvironmentBridgeController'));


// catch 404 and forward to error handler
Expand All @@ -58,74 +68,36 @@ app.use(function(req, res, next) {

// error handler
app.use(function(err, req, res, next) {
console.error(err);
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: err
});
res.json(err.message);
});


// Active Sockets
var activeSockets = {};
var USER_KEY = 'userId';

// Helper functions
function activeClients() {
var size = 0, key;
for (key in activeSockets) {
if (activeSockets.hasOwnProperty(key)) size++;
}
return size;
}
function onlineUsers() {
var ids = [], key;
for (key in activeSockets) {
if (activeSockets.hasOwnProperty(key) && activeSockets[key][USER_KEY] != null) {
ids.push(activeSockets[key][USER_KEY]);
}
}
var uniqueIds = [];
for ( i = 0; i < ids.length; i++ ) {
var current = ids[i];
if (uniqueIds.indexOf(current) < 0) uniqueIds.push(current);
}
return uniqueIds;
}
var SocketBank = require('./singletons/SocketBank');

// Socket Events
io.on('connection', function(socket) {
console.log('New client socket connection...');
activeSockets[socket.id] = {};
activeSockets[socket.id]['socket'] = socket;
activeSockets[socket.id][USER_KEY] = null;

SocketBank.addSocket(socket);

// Notify all clients of presence
io.sockets.emit('client:enter', activeClients());
io.sockets.emit('client:enter', SocketBank.getClientCount());

// Give initial list of online users
socket.emit('client:online', onlineUsers());
socket.emit('client:online', SocketBank.getOnlineClientIds());

socket.on('disconnect', function() {
console.log('Disconnected socket connection...');
var userId = activeSockets[socket.id][USER_KEY];
delete activeSockets[socket.id];
if (userId) {
io.sockets.emit('client:online', onlineUsers());
}
io.sockets.emit('client:leave', activeClients());
SocketBank.removeSocket(socket);
io.sockets.emit('client:online', SocketBank.getOnlineClientIds());
io.sockets.emit('client:leave', SocketBank.getClientCount());
});

socket.on('login', function(userId) {
console.log('Login from userId: '+ userId);
activeSockets[socket.id][USER_KEY] = userId;
io.sockets.emit('client:online', onlineUsers());
});


socket.on('logout', function(userId) {
console.log('Logout from userId: '+ userId);
activeSockets[socket.id][USER_KEY] = null;
io.sockets.emit('client:online', onlineUsers());
SocketBank.logoffUser(userId);
io.sockets.emit('client:online', SocketBank.getOnlineClientIds());
});
});

Expand Down
90 changes: 0 additions & 90 deletions bin/www

This file was deleted.

13 changes: 0 additions & 13 deletions bower.json

This file was deleted.

72 changes: 72 additions & 0 deletions config/readme.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
Adding Properties
=================

Add a file called `application.env` under the config directory.
This file should contain properties formatted like this:

```
KEY=VALUE
```


Possible Properties
===================
Listed below are the available properties.


Username Properties
-------------------

| Property Name | Default | Description |
| ------------- | ------- | ----------- |
| USERNAME_LENGTH_MIN | 2 | Minimum length of characters allowed for players and teams |
| USERNAME_LENGTH_MAX | 15 | Maximum length of characters allowed for players and teams |


Authentication Properties
-------------------------

| Property Name | Default | Description |
| ------------- | ------- | ----------- |
| JWT_SECRET_KEY | *none* | Used to encode and decode JWT tokens |
| JWT_AUTH_HEADER_PREFIX | JWT | HTTP authorization header prefix before the JWT |
| JWT_ALGORITHM | HS256 | Algorithm used to encode and decode a JWT |
| JWT_EXPIRATION_DAYS | 5 | Days before a JWT is considered expired |
| JWT_REJECT_IAT_BEFORE | 1483246800000 | A JWT before this time (in milliseconds) is considered invalid |
| PASSWORD_RESET_WINDOW_MINUTES | 20 | Minutes after a password reset key is issued until it expires |
| PASSWORD_RESET_REPEAT_HOURS | 1 | Hours after a password reset is enabled before it can be reset again |
| PASSWORD_MIN_LENGTH | 6 | Minimum allowed length of a user password |


Email Properties
----------------

| Property Name | Default | Description |
| ------------- | ------- | ----------- |
| EMAIL_ADDRESS | *none* | Gmail address used to email users |
| EMAIL_TITLE | Sparc Pong | Friendly email titled used to email users |
| AUTH_CLIENT_ID | *none* | Oauth2 client id for gmail account |
| AUTH_CLIENT_SECRET | *none* | Oauth2 secret for gmail account |
| AUTH_CLIENT_REFRESH | *none* | Oauth2 refresh token for gmail account |


Challenge Properties
--------------------

| Property Name | Default | Description |
| ------------- | ------- | ----------- |
| CHALLENGE_ANYTIME | false | Challenges can be issued on any day including weekends |
| CHALLENGE_BACK_DELAY_HOURS | 12 | Hours before a challenger may re-challenge the same opponent |
| ALLOWED_CHALLENGE_DAYS | 4 | Business days until a singles challenge expires |
| ALLOWED_CHALLENGE_DAYS_TEAM | 5 | Business days until a doubles challenge expires |


Application Properties
----------------------

| Property Name | Default | Description |
| ------------- | ------- | ----------- |
| PORT | 3000 | Port the node server runs on |
| MONGODB_URI | mongodb://127.0.0.1/sparcPongDb | Mongo connection uri |
| MORGAN_FORMAT | tiny | Morgan logging predefined type |
| LADDER_URL | *none* | Root url where the ladder is hosted. Defaults to localhost when MONGODB_URL is not defined. |
Loading

0 comments on commit 9c3d47f

Please sign in to comment.