Skip to content

Commit

Permalink
Log client's last login date. Start to create configs for Docker depl…
Browse files Browse the repository at this point in the history
…oyment.
  • Loading branch information
holdonowgo committed Jul 4, 2017
1 parent 2ce909d commit b63afba
Show file tree
Hide file tree
Showing 14 changed files with 4,046 additions and 118 deletions.
2 changes: 2 additions & 0 deletions .dockerignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
node_modules
npm-debug.log
15 changes: 15 additions & 0 deletions Dockerfile
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
FROM node:7.5.0-alpine

RUN mkdir /app
WORKDIR /app

ADD package.json .
RUN npm install -q

#ADD . . # josh
COPY . /app # tutorial

EXPOSE 8080

RUN npm start # spin up temp container run then spin down. in this case db service wont work
CMD ["npm", "start"] # when have this image when we run a container off this execute after there is a build of this image. makes sure dependencies are fu
10 changes: 10 additions & 0 deletions DockerfileDB
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
FROM postgres:9.6.3-alpine

RUN mkdir /db/data
WORKDIR /db/data

# run create.sql on init
ADD create.sql /docker-entrypoint-initdb.d
ADD create.sql.sql /db/data

RUN "knex migrate:latest"
4 changes: 2 additions & 2 deletions api/controllers/clients.js
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ module.exports = {
getUsersSearchResponse: getUsersSearchResponse
}

const bcrypt = require('bcrypt-as-promised');
const bcrypt = require('bcrypt-nodejs-as-promised');
const humps = require('humps');
const ev = require('express-validation');
// const validations = require("../validations/users");
Expand Down Expand Up @@ -351,7 +351,7 @@ function addRestriction(req, res) {
res.status(404).json('Not Found');
} else {
let ingredientObj = ingredient.serialize();

return res.json(
{
description: ingredientObj.description,
Expand Down
2 changes: 1 addition & 1 deletion api/controllers/ingredients.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ const IngredientTag = require('../models/ingredient_tag.js').IngredientTag;
const IngredientTags = require('../models/ingredient_tag.js').IngredientTags;
const AlternativeIngredient = require('../models/ingredients_ingredients.js').AlternativeIngredient;
const AlternativeIngredients = require('../models/ingredients_ingredients.js').AlternativeIngredients;
const bcrypt = require('bcrypt-as-promised');
const bcrypt = require('bcrypt-nodejs-as-promised');
const jwt = require('jsonwebtoken');
const fetch = require('node-fetch');
const url = require('url');
Expand Down
2 changes: 1 addition & 1 deletion api/controllers/recipes.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
'use strict';
const knex = require('../../knex');
const bookshelf = require('../../bookshelf');
const bcrypt = require('bcrypt-as-promised');
const bcrypt = require('bcrypt-nodejs-as-promised');
const jwt = require('jsonwebtoken');
const Recipe = require('../models/recipe.js').Recipe;
const Recipes = require('../models/recipe.js').Recipes;
Expand Down
194 changes: 93 additions & 101 deletions api/controllers/token.js
Original file line number Diff line number Diff line change
@@ -1,126 +1,118 @@
'use strict';
const knex = require('../../knex');
const bookshelf = require('../../bookshelf');
const bcrypt = require('bcrypt-as-promised');
const bcrypt = require('bcrypt-nodejs-as-promised');
const jwt = require('jsonwebtoken');
const Client = require('../models/client.js').Client;
const Clients = require('../models/client.js').Clients;

const clientSecret = process.env.CLIENT_SECRET;

module.exports = {
postToken,
postTokenOAuth
}

// function postToken(req, res) {
// if (!req.cookies.token) {
// return res.status(200).json(false);
// }
// jwt.verify(req.cookies.token, process.env.JWT_KEY, (err, payload) => {
// if (err) {
// //unauthorized
// return res.status(200).json(false);
// }
// //the payload is the claim that we sent the client. In this case {clientId}
// //if it is present, the client is authorized. Do what you need to with clientId
// if (payload.userId) {
// return res.status(200).json(true);
// } else {
// return res.status(200).json(false);
// }
// });
// }

const finishLogin = (client, res) => {
const claim = {
userId: client.id
};
new Client({id: client.id}).save({
last_login_at: knex.raw('now()')
}, {patch: true}).then((model) => {
const claim = {
userId: client.id
};

const token = jwt.sign(claim, process.env.JWT_KEY, {
expiresIn: '7 days'
});
const token = jwt.sign(claim, process.env.JWT_KEY, {
expiresIn: '7 days'
});

client.token = token;
client.token = token;

delete client.first_name;
delete client.last_name;
delete client.hashed_password;
delete client.created_at;
delete client.updated_at;
delete client.first_name;
delete client.last_name;
delete client.hashed_password;
delete client.created_at;
delete client.updated_at;

res.set('Token', token);
res.set('Content-Type', 'application/json');
res.status(200).json(client);
res.set('Token', token);
res.set('Content-Type', 'application/json');
res.status(200).json(client);
});
}

function postTokenOAuth(req, res) {
const idToken = req.swagger.params.credentials.value.idToken;
const client_secret = 'e9XGt9Dwcgn-vJRs04UXsqWpbbzwWYS8NeFEZl5ADjnxXyEqOQ9-UzkuPaCckY--';
jwt.verify(idToken, client_secret, (err, payload) => {
if (err) {
res.set('Content-Type', 'application/json');
res.status(401).send('Unauthorized');
} else {
const full_name = payload.name || "John Doe";
const [first_name, ...last_name_parts] = full_name.split(" ");
let last_name = last_name_parts.join(" ");
// console.log("decoded", decoded.email);
knex('clients')
.where('email', payload.email)
.first()
.then((client) => {
if (client === undefined) {
// no account yet, make an account
let client = {
first_name: first_name,
last_name: last_name,
email: payload.email,
hashed_password: ""
};
return knex('clients').insert(client, '*').returning('*')
.then((insertedRows) => {
return insertedRows[0];
jwt.verify(idToken, clientSecret, (err, payload) => {
if (err) {
res.set('Content-Type', 'application/json');
res.status(401).send('Unauthorized');
} else {
const full_name = payload.name || "John Doe";
const [first_name, ...last_name_parts] = full_name.split(" ");
let last_name = last_name_parts.join(" ");
// console.log("decoded", decoded.email);
knex('clients')
.where('email', payload.email)
.first()
.then((client) => {
if (client === undefined) {
// no account yet, make an account
let client = {
first_name: first_name,
last_name: last_name,
email: payload.email,
hashed_password: ""
};
return knex('clients').insert(client, '*').returning('*')
.then((insertedRows) => {
return insertedRows[0];
});
}
return client;
})
.then((client) => {
return finishLogin(client, res);
})
.catch((err) => {
res.status(400).json({
message: "Can't authenticate via OAuth."
});
}
return client;
}).then((client) => {
return finishLogin(client, res);
})
}
})
}
});
}
// const decoded = jwt.decode(idToken);


function postToken(req, res) {
knex('clients')
.where('email', req.swagger.params.credentials.value.email)
.first()
.then((client) => {
return bcrypt.compare(
req.swagger.params.credentials.value.password,
client.hashed_password
);
})
.then((passwordMatched) => {
if (!passwordMatched) {
res.status(400).json({
message: 'Bad email or password'
});
return;
}
return knex('clients')
.where('email', req.swagger.params.credentials.value.email)
.first();
})
.then((client) => {
return finishLogin(client, res);
})
.catch((err) => {
res.status(400).json({
message: "Can't make token"
});
})
.catch(bcrypt.MISMATCH_ERROR, () => {
res.status(400).json({
message: 'Bad email or password'
});
});
knex('clients')
.where('email', req.swagger.params.credentials.value.email)
.first()
.then((client) => {
return bcrypt.compare(
req.swagger.params.credentials.value.password,
client.hashed_password
);
})
.then((passwordMatched) => {
if (!passwordMatched) {
res.status(400).json({
message: 'Bad email or password'
});
return;
}
return knex('clients')
.where('email', req.swagger.params.credentials.value.email)
.first();
})
.then((client) => {
return finishLogin(client, res);
})
.catch((err) => {
res.status(500).json({
message: "Can't make token"
});
})
.catch(bcrypt.MISMATCH_ERROR, () => {
res.status(400).json({
message: 'Bad email or password'
});
});
}
2 changes: 1 addition & 1 deletion api/helpers/auth.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
const bcrypt = require('bcrypt-as-promised');
const bcrypt = require('bcrypt-nodejs-as-promised');
const jwt = require('jsonwebtoken');

if (process.env.NODE_ENV !== 'production') {
Expand Down
2 changes: 2 additions & 0 deletions create.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
CREATE DATABASE piecemeal_dev;
CREATE DATABASE piecemeal_test;
41 changes: 41 additions & 0 deletions docker-compose.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
version: "2"

services:

my-counter-service:
# image: counter
build: .
depends_on:
- db-service
volumes:
# - pathOnHost:PathInContainer
- ./:/app

db-service:
# image: postgres:9.6.3-alpine
build: ./DockerfileDB
# this should become the location and name of the db image you create with docker build
environment:
- PG_DATABASE=whatever

users-db:
container_name: users-db
build: ./services/users/src/db
ports:
- '5433:5432'
environment:
- POSTGRES_USER=admin
- POSTGRES_PASSWORD=admin
healthcheck:
test: exit 0

locations-db:
container_name: locations-db
build: ./services/locations/src/db
ports:
- '5434:5432'
environment:
- POSTGRES_USER=admin
- POSTGRES_PASSWORD=admin
healthcheck:
test: exit 0
1 change: 1 addition & 0 deletions migrations/20170319175614_clients.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ exports.up = function(knex, Promise) {
table.specificType('hashed_password', 'char(60)').notNullable();
table.timestamp('created_at').notNullable().defaultTo(knex.raw('now()'));
table.timestamp('updated_at').notNullable().defaultTo(knex.raw('now()'));
table.timestamp('last_login_at');
});
};

Expand Down
Loading

0 comments on commit b63afba

Please sign in to comment.