Skip to content

Commit

Permalink
Merge branch 'master' into contribution-#26
Browse files Browse the repository at this point in the history
  • Loading branch information
jordanh committed Mar 22, 2016
2 parents ea48a92 + 8c43886 commit 29b34fb
Show file tree
Hide file tree
Showing 63 changed files with 581 additions and 1,496 deletions.
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,7 @@ _Remember: if RethinkDB is running locally, you can reach its dashboard at
2) Start Action in development mode:

```bash
$ npm run migrate
$ npm run dev
```

Expand Down
8 changes: 7 additions & 1 deletion api/api.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import sessionRethinkDB from 'session-rethinkdb';
import bodyParser from 'body-parser';
import PrettyError from 'pretty-error';
import http from 'http';
import jwt from 'express-jwt';
import SocketIo from 'socket.io';
import socketSession from 'socket.io-express-session';
import falcorExpress from 'falcor-express';
Expand All @@ -17,6 +18,11 @@ import { mapUrl } from './utils/url';

const pretty = new PrettyError();

const authenticate = jwt({
secret: new Buffer(config.auth0.secret, 'base64'),
audience: config.auth0.audience
});

/*
* Initialize app and HTTP server:
*/
Expand Down Expand Up @@ -50,7 +56,7 @@ app.use(session);
app.use(bodyParser.json());

// Initialze falcor routes:
app.use('/model.json', bodyParser.urlencoded({extended: false}),
app.use('/model.json', authenticate, bodyParser.urlencoded({extended: false}),
falcorExpress.dataSourceRoute( (req, res, next) =>
new FalcorRouter(req, res, next)
));
Expand Down
2 changes: 2 additions & 0 deletions api/falcor/index.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
import meetings from './meetings';
import users from './users';
import FalcorRouter from 'falcor-router';

const allRoutes = [
...meetings,
...users,
];

class ExpressFalcorRouter extends FalcorRouter.createClass(allRoutes) {
Expand Down
2 changes: 1 addition & 1 deletion api/falcor/meetings.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { createRoutes } from 'falcor-saddle';

import Meeting from '../models/meeting';
import { Meeting } from '../models/index';


export default [
Expand Down
29 changes: 29 additions & 0 deletions api/falcor/users.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
import { createGetByIdRoute } from 'falcor-saddle';

import { CachedUser } from '../models/index';

export default [
createGetByIdRoute(
'users',
['createdAt', 'updatedAt', 'userId', 'email',
'emailVerified', 'picture', 'name', 'nickname',
'identities', 'loginsCount', 'blockedFor'],
async (id) => CachedUser.getUserByUserId(id),
(model, id) => model[id],
'userId'
),
{
route: 'users.updateCacheWithToken',
call: async (callPath, args) => {
const [ idToken ] = args;
const aUser = await CachedUser.updateWithToken(idToken);

return [
{
path: ['users.updateCacheWithToken'],
value: aUser.userId
},
];
}
}
];
75 changes: 75 additions & 0 deletions api/models/cached_users.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
import Database from './database';
import { AuthenticationClient } from 'auth0';
import config from '../../config/config';

const type = Database.type;
const auth0 = new AuthenticationClient({
domain: config.auth0.domain,
clientId: config.auth0.audience,
});

export const CachedUser = Database.createModel('CachedUser', {
// locally set:
id: type.string(),
cachedAt: type.date(),
cacheExpiresAt: type.date().default(Database.r.now()),
// from auth0:
createdAt: type.date(),
updatedAt: type.date(),
userId: type.string(),
email: type.string().email(),
emailVerified: type.boolean().default(false),
picture: type.string(),
name: type.string(),
nickname: type.string(),
identities: type.array().default([]),
loginsCount: type.number(),
blockedFor: type.array().default([])
});

CachedUser.ensureIndex('userId');

function getUserByUserId(userId) {
return new Promise( (resolve, reject) => {
CachedUser.getAll(userId, { index: 'userId'}).limit(1)
.then((result) => {
// TODO: handle cache expiration here
resolve(result[0]);
})
.catch((error) => {
reject(error);
});
});
}

CachedUser.defineStatic('getUserByUserId', getUserByUserId);

async function updateWithToken(idToken) {
const userInfo = await auth0.tokens.getInfo(idToken);
let aUser = await CachedUser.getUserByUserId(userInfo.user_id);

const fieldData = {
createdAt: userInfo.created_at,
updatedAt: userInfo.updated_at,
userId: userInfo.user_id,
email: userInfo.email,
emailVerified: userInfo.email_verified,
picture: userInfo.picture,
name: userInfo.name,
nickname: userInfo.nickname,
identities: userInfo.identities,
loginsCount: userInfo.logins_count,
blockedFor: userInfo.blocked_for
};

if (!aUser) {
aUser = new CachedUser(fieldData);
} else {
await aUser.merge(fieldData);
}
await aUser.save();

return aUser;
}

CachedUser.defineStatic('updateWithToken', updateWithToken);
3 changes: 2 additions & 1 deletion api/models/index.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@

export Database from './database';
export Meeting from './meeting';
export { Meeting } from './meeting';
export { CachedUser } from './cached_users';
4 changes: 1 addition & 3 deletions api/models/meeting.js
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ function subscribe(io, room, params, modelPath) {
try {
subscriptions.add(modelPath, params, cursor);
subscriptions.addRoomTo(modelPath, params, room);
} catch (e) { }
} catch (e) { console.log(e); } // eslint-disable-line
cursor.on('change', (doc) => {
const rooms = subscriptions.getRoomsFor(modelPath, params);
publish(io, rooms, modelPath, doc, doc.updatedBy);
Expand Down Expand Up @@ -58,5 +58,3 @@ function unsubscribe(room, params, modelPath) {
}

Meeting.defineStatic('unsubscribe', unsubscribe);

export default Meeting;
9 changes: 9 additions & 0 deletions api/models/migrations/20160229105717-initialize.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
exports.up = (r, connection) => { // eslint-disable-line id-length
r.tableCreate('Meeting').run(connection);
return r.tableCreate('Session').run(connection);
};

exports.down = (r, connection) => { // eslint-disable-line id-length
r.tableDrop('Session').run(connection);
return r.tableDrop('Meeting').run(connection);
};
7 changes: 7 additions & 0 deletions api/models/migrations/20160316123107-create-user-cache.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
exports.up = function (r, connection) {
return r.tableCreate('CachedUser').run(connection);
};

exports.down = function (r, connection) {
return r.tableDrop('CachedUser').run(connection);
};
56 changes: 56 additions & 0 deletions bin/migrate.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
#!/bin/bash

DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
MIGRATE="${DIR}/../node_modules/.bin/rethink-migrate"

development ()
{
source ${DIR}/../config/env/development.sh
}

production ()
{
source ${DIR}/../config/env/production.sh
}

case $NODE_ENV in
development)
echo "node development environment found"
development
;;
production)
echo "node production environment found"
production
;;
*)
echo "defaulting to node development environment"
development
;;
esac

case $1 in
down)
echo "will migrate down one"
MIGRATE_ARGS="down"
;;
down-all)
echo "will migrate down all"
MIGRATE_ARGS="down -a"
;;
up)
echo "will migrate up one"
MIGRATE_ARGS="up"
;;
up-all)
echo "will migrate up all"
MIGRATE_ARGS="up -a"
;; # no fallthough in bash < 4.0
*)
echo "will migrate up all"
MIGRATE_ARGS="up -a"
;;
esac

${MIGRATE} ${MIGRATE_ARGS} -a --host $RETHINK_DB_HOST --port $RETHINK_DB_PORT \
--db $RETHINK_DB_NAME -r ${DIR}/../api/models/

Loading

0 comments on commit 29b34fb

Please sign in to comment.