Skip to content

Lab isak scaffold created, working on tests, put and delete #3

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 5 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
The table of contents is too big for display.
Diff view
Diff view
  •  
  •  
  •  
The diff you're trying to view is too large. We only load the first 3000 changed files.
3 changes: 3 additions & 0 deletions .env
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
APP_SECRET='SEEEEKRET'

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Gotta make sure to delete and gitignore this file.

MONGODB_URI='mongodb://localhost/cfgram-dev'
PORT=3000
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
`.env`
`db`
Empty file added controllers/llama-controller.js
Empty file.
46 changes: 46 additions & 0 deletions controllers/user-controller.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
'use strict';

const User = require('../models/user');
const debug = require('debug')('cfgram:auth-contoller');
const basicAuth = require('../lib/basic-auth-middleware');

module.exports = exports = {};

exports.addNewUser = function(body){
debug('#addNewUser');

let tempPassword = body.password;
body.password = null;
delete body.password;

// console.log('the body ', body);
let newUser = new User(body);
return newUser.generatePasswordHash(tempPassword)
.then(user => user.save())
.then(user => user.generateToken())
.then(token => Promise(token))
.catch(err => Promise(err.status).send(err));
};

exports.getUser = function(auth){
debug('#getUser');

return User.findOne({username: auth.username})
.then(user => user.comparePasswordHash(auth.password))
.then(user => user.generateToken())
.then(token => Promise(token))
.catch(err => Promise(err.status).send(err));
};


// exports.putUser = function(body, auth){
// debug('#putUser');
//
// return User.findOne({username: auth.username})
// .then(user => user.comparePasswordHash(auth.password))
// .then(user => user.generateToken())
// .then(token => Promise(token))
// .catch(err => Promise(err.status).send(err));


// };
2 changes: 2 additions & 0 deletions db/WiredTiger
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
WiredTiger
WiredTiger 2.9.2: (December 23, 2016)
1 change: 1 addition & 0 deletions db/WiredTiger.lock
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
WiredTiger lock file
6 changes: 6 additions & 0 deletions db/WiredTiger.turtle
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
WiredTiger version string
WiredTiger 2.9.2: (December 23, 2016)
WiredTiger version
major=2,minor=9,patch=2
file:WiredTiger.wt
access_pattern_hint=none,allocation_size=4KB,app_metadata=,block_allocation=best,block_compressor=,cache_resident=false,checkpoint=(WiredTigerCheckpoint.13=(addr="018b81e48314359d8e81e4fc12ecb18f81e4e80b7584808080e2efc0e22fc0",order=13,time=1494443316,size=24576,write_gen=26)),checkpoint_lsn=(4,5888),checksum=uncompressed,collator=,columns=,dictionary=0,encryption=(keyid=,name=),format=btree,huffman_key=,huffman_value=,id=0,ignore_in_memory_cache_size=false,internal_item_max=0,internal_key_max=0,internal_key_truncate=true,internal_page_max=4KB,key_format=S,key_gap=10,leaf_item_max=0,leaf_key_max=0,leaf_page_max=32KB,leaf_value_max=0,log=(enabled=true),memory_page_max=5MB,os_cache_dirty_max=0,os_cache_max=0,prefix_compression=false,prefix_compression_min=4,split_deepen_min_child=0,split_deepen_per_child=0,split_pct=90,value_format=S,version=(major=1,minor=1)
Binary file added db/WiredTiger.wt
Binary file not shown.
Binary file added db/WiredTigerLAS.wt
Binary file not shown.
Binary file added db/_mdb_catalog.wt
Binary file not shown.
Binary file added db/collection-0-3879806582052326196.wt
Binary file not shown.
Binary file added db/collection-0-7136290055178207603.wt
Binary file not shown.
Binary file added db/collection-2-3879806582052326196.wt
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file added db/diagnostic.data/metrics.interim
Binary file not shown.
Binary file added db/index-1-3879806582052326196.wt
Binary file not shown.
Binary file added db/index-1-7136290055178207603.wt
Binary file not shown.
Binary file added db/index-2-7136290055178207603.wt
Binary file not shown.
Binary file added db/index-3-3879806582052326196.wt
Binary file not shown.
Binary file added db/index-3-7136290055178207603.wt
Binary file not shown.
Binary file added db/index-4-3879806582052326196.wt
Binary file not shown.
Binary file added db/index-4-7136290055178207603.wt
Binary file not shown.
Binary file added db/journal/WiredTigerLog.0000000004
Binary file not shown.
Binary file added db/journal/WiredTigerPreplog.0000000001
Binary file not shown.
Binary file added db/journal/WiredTigerPreplog.0000000002
Binary file not shown.
1 change: 1 addition & 0 deletions db/mongod.lock
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
9488
Binary file added db/sizeStorer.wt
Binary file not shown.
Binary file added db/storage.bson
Binary file not shown.
22 changes: 22 additions & 0 deletions lib/basic-auth-middleware.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
'use strict'

const debug = require('debug')('cfgram:basic-auth-middleware')
const createError = require('http-errors')

module.exports = function(req, res, next) {
debug('#basic-auth-middleware')

let authHeaders = req.headers.authorization
if(!authHeaders) return next(createError(401, 'Authorization headers required'))

let base64Str = authHeaders.split('Basic ')[1]
if(!base64Str) return next(createError(401, 'Username and Password required'))

let [username, password] = new Buffer(base64Str, 'base64').toString().split(':')
req.auth = {username, password}

if(!req.auth.username) return next(createError(401, 'Username required'))
if(!req.auth.password) return next(createError(401, 'Password required'))

next()
}
28 changes: 28 additions & 0 deletions lib/bearer-auth-middleware.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
'use strict';

const jwt = require('jsonwebtoken');
const createError = require('http-errors');
const debug = require('debug')('cfgram:bearer-auth-middleware');

const User = require('../models/user');

module.exports = function(req, res, next) {
debug('bearer-auth-middleware');

let authHeaders = req.headers.authorization;
if(!authHeaders) return next(createError(401, 'Authorization headers required'));

let token = authHeaders.split('Bearer ')[1];
if (!token) return next(createError(401, 'Token required'));

jwt.verify(token, process.env.APP_SECRET, (err, decoded) => {
if(err) return next(err);

User.find({findHash: decoded.token})
.then(user => {
req.user = user[0];
next();
})
.catch(err => next(createError(401, err.message)));
});
};
28 changes: 28 additions & 0 deletions lib/error-middleware.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
'use strict'

const debug = require('debug')('cfgram:error-middleware')
const createError = require('http-errors')

module.exports = function(err, req, res, next) {
debug('#error-middleware')

console.log('message', err.message)
console.log('name', err.name)

if(err.status) {
res.status(err.status).send(err.name)
next()
return
}

if(err.name === 'ValidationError') {
err = createError(400, err.message)
res.status(err.status).send(err.name)
next()
return
}

err = createError(500, err.message)
res.status(err.status).send(err.name)
next()
}
13 changes: 13 additions & 0 deletions models/llama.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
'use strict';

const mongoose = require('mongoose');
const Schema = mongoose.Schema;

const llamaSchema = Schema({
name: {type: String, required: true},
breed: {type: String, required: true},
created: {type: Date, default: Date.now, required: true},
userId: {type: Schema.Types.ObjectId, required: true},
});

module.exports = mongoose.model('llama', llamaSchema);
78 changes: 78 additions & 0 deletions models/user.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
'use strict';

const bcrypt = require('bcrypt');
const crypto = require('crypto');
const jwt = require('jsonwebtoken');
const Promise = require('bluebird');
const mongoose = require('mongoose');
const createError = require('http-errors');
const debug = require('debug')('cfgram:user-model');

const Schema = mongoose.Schema;

const userSchema = Schema({
username: {type: String, required: true, unique: true},
email: {type: String, required: true, unique: true},
password: {type: String, required: true},
findhash: {type: String, unique: true},
});

userSchema.methods.generatePasswordHash = function(password) {
debug('#generatePasswordHash');

return new Promise((resolve, reject) => {
bcrypt.hash(password, 10, (err, hash) => {
if(err) return reject(createError(401, 'Password hashing failed'));
this.password = hash;
resolve(this);
});
});
};

userSchema.methods.comparePasswordHash = function(password) {
debug('#comparePasswordHash');

return new Promise((resolve, reject) => {
bcrypt.compare(password, this.password, (err, valid) => {
if(err) return reject(createError(401, 'Password validation failed'));
if(!valid) return reject(createError(401, 'Wrong password'));

resolve(this);
});
});
};

userSchema.methods.generateFindHash = function() {
debug('#generateFindHash');

return new Promise((resolve, reject) => {
let tries = 0;
let _generateFindHash = () => {
this.findHash = crypto.randomBytes(32).toString('hex');
this.save()
.then(() => resolve(this.findHash))
.catch(err => {
if(tries > 3) return reject(createError(401, 'Generate findhash failed'));
tries++;
_generateFindHash();
});
};

_generateFindHash();
});
};

userSchema.methods.generateToken = function() {
debug('#generateToken');
return new Promise((resolve, reject) => {
console.log(process.env.APP_SECRET);
this.generateFindHash()
.then(findHash => resolve(jwt.sign({token: findHash}, process.env.APP_SECRET)))
.catch(err => {
console.log(err);
reject(createError(401, 'Generate token failed'));
});
});
};

module.exports = mongoose.model('user', userSchema);
15 changes: 15 additions & 0 deletions node_modules/.bin/_mocha

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

7 changes: 7 additions & 0 deletions node_modules/.bin/_mocha.cmd

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

15 changes: 15 additions & 0 deletions node_modules/.bin/coveralls

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

7 changes: 7 additions & 0 deletions node_modules/.bin/coveralls.cmd

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

15 changes: 15 additions & 0 deletions node_modules/.bin/escodegen

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

7 changes: 7 additions & 0 deletions node_modules/.bin/escodegen.cmd

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

15 changes: 15 additions & 0 deletions node_modules/.bin/esgenerate

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

7 changes: 7 additions & 0 deletions node_modules/.bin/esgenerate.cmd

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

15 changes: 15 additions & 0 deletions node_modules/.bin/esparse

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

7 changes: 7 additions & 0 deletions node_modules/.bin/esparse.cmd

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

15 changes: 15 additions & 0 deletions node_modules/.bin/esvalidate

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

7 changes: 7 additions & 0 deletions node_modules/.bin/esvalidate.cmd

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading