Skip to content

nothing works. #14

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 8 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
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .eslintrc
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
"comma-dangle": ["error", "always-multiline"],
"no-console": "off",
"indent": [ "error", 2 ],
"semi": ["error", "always"]
"semi": [0]
},
"env": {
"es6": true,
Expand Down
67 changes: 67 additions & 0 deletions caleb-lab/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@

# Created by https://www.gitignore.io/api/node

### Node ###
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*

# Runtime data
pids
*.pid
*.seed
*.pid.lock

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

# Coverage directory used by tools like istanbul
coverage

# nyc test coverage
.nyc_output

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

# Bower dependency directory (https://bower.io/)
bower_components

# node-waf configuration
.lock-wscript

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

# Dependency directories
node_modules/
jspm_packages/

# Typescript v1 declaration files
typings/

# Optional npm cache directory
.npm

# Optional eslint cache
.eslintcache

# Optional REPL history
.node_repl_history

# Output of 'npm pack'
*.tgz

# Yarn Integrity file
.yarn-integrity

# dotenv environment variables file
.env

# database hidden
db/

# End of https://www.gitignore.io/api/node
7 changes: 7 additions & 0 deletions caleb-lab/README.MD
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
# Goal:
* Create Multiple users
* Create galleries that are joined to a user with a matching id
* Generate a unique token for each user
* Use the proper username and password combination to sign in a user
* Verify each gallery interaction with a token to make sure that only a user with the proper token can access a gallery
* Use a user's unique token to approve each action taken by a user
41 changes: 41 additions & 0 deletions caleb-lab/controllers/gallery-controller.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
'use strict'

const debug = require('debug')('cfgram:gallery-controller.js')
const Gallery = require('../models/gallery.js')
const createError = require('http-errors')

module.exports = exports = {}

exports.createGallery = function(gallery){
debug('#createGallery')
if(!gallery) return Promise.reject(createError(400, '!!no gallery!!'))
console.log(gallery)
return new Gallery(gallery).save()
}

exports.fetchGallery = function(id){
debug('#fetchGallery')
if(!id) return Promise.reject(createError(400, '!!no id!!'))
return Gallery.findById(id)
.then(gallery => Promise.resolve(gallery))
.catch(() => Promise.reject(createError(404, 'gallery not found')))
}

exports.updateGallery = function(id, gallery){
debug('#updateGallery')
if(!id) return Promise.reject(createError(400, '!!no id!!'))
if(!gallery) return Promise.reject(createError(400, '!!no gallery!!'))
return Gallery.findByIdAndUpdate(id, gallery, {new: true})
.then(gallery => Promise.resolve(gallery))
.catch(() => Promise.reject(createError(404, 'gallery not found')))
}

exports.deleteGallery = function(id){
debug('#deleteGallery')
if(!id) return Promise.reject(createError(400, '!!no id, id required'))
Gallery.findById(id)
.then(gallery => console.log(`Gallery DELETED: \n`, gallery))
.catch(err => Promise.reject(err))

return Gallery.findByIdAndRemove(id)
}
33 changes: 33 additions & 0 deletions caleb-lab/controllers/user-controller.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
'use strict'

const User = require('../models/user.js')
const debug = require('debug')('cfgram:user-controller')
const createError = require('http-errors')

module.exports = exports = {}

exports.createUser = function(body){
debug('#createUser')
if(!body) return Promise.reject(createError(400, '!!No user!!'))
// if(!password) return Promise.reject(createError(400, '!!no password!!'))

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

let newUser = new User(body)
return newUser.generatePasswordHash(tempPassword)
.then(user => user.save())
.then(user => user.generateToken())
.then(token => Promise.resolve(token))
.catch(err => Promise.reject(err))
}

exports.fetchUser = function(auth){
debug('#fetchUser')
return User.findOne({username: auth.username})
.then(user => user.comparePasswordHash(auth.password))
.then(user => user.generateToken())
.then(token => Promise.resolve(token))
.catch(err => Promise.reject(err))
}
17 changes: 17 additions & 0 deletions caleb-lab/lib/basic-auth-middleware.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
'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 base64String = authHeaders.split('Basic ')[1]
if(!base64String) return next(createError(401, 'username and password required'))
let [username, password] = new Buffer(base64String, '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()
}
25 changes: 25 additions & 0 deletions caleb-lab/lib/bearer-auth-middleware.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
'use strict'

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

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

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.findOne({findHash: decoded.token})
.then(user => {
req.user = user
next()
})
.catch(err => next(createError(401, err.message)))
})
}
24 changes: 24 additions & 0 deletions caleb-lab/lib/error-middleware.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
'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 caleb-lab/models/gallery.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 gallerySchema = Schema({
name: {type: String, required: true},
desc: {type: String, required: true},
created: {type: Date, default: Date.now, required: true},
userId: {type: Schema.Types.ObjectId, required: true},
})

module.exports = mongoose.model('gallery', gallerySchema)
77 changes: 77 additions & 0 deletions caleb-lab/models/user.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
'use strict'

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

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 validataion failed'))
if(!valid) return reject(createError(401, 'wrong password, you n\'wah '))

resolve(this)
})
})
}

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

return new Promise((resolve, reject) => {
let tries = 0

_generateFindHash.call(this)

function _generateFindHash(){
this.findHash = crypto.randomBytes(32).toString('hex')
this.save()
.then(() => resolve(this.findHash))
.catch(() => {//potentially need err as a single param here. doubtful, since wwe don't use it.
if(tries > 3) return reject(createError(401, 'Generate findhash failed.'))
tries++
_generateFindHash()
})
}
})
}

userSchema.methods.generateToken = function(){
debug('#generateToken')

return new Promise((resolve, reject) => {
console.log(process.env.MONGODB_URI);
this.generateFindHash()
.then(findHash => resolve(jwt.sign({token: findHash}, process.env.APP_SECRET)))
.catch(() => reject(createError(401, 'Generate Token Failed')))
})
}

module.exports = mongoose.model('user', userSchema)
40 changes: 40 additions & 0 deletions caleb-lab/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
{
"name": "17-wat",
"version": "1.0.0",
"description": "",
"main": "server.js",
"directories": {
"test": "test"
},
"scripts": {
"test": "mocha",
"start": "node server.js",
"debug": "DEBUG=cfgram* nodemon server.js",
"watch": "nodemon server.js"
},
"author": "wat-man",
"license": "MIT",
"dependencies": {
"bcrypt": "^1.0.2",
"bluebird": "^3.5.0",
"body-parser": "^1.17.1",
"chai": "^3.5.0",
"chai-http": "^3.0.0",
"cors": "^2.8.3",
"crypto": "0.0.3",
"debug": "^2.6.6",
"decrypt": "0.0.1",
"dotenv": "^4.0.0",
"express": "^4.15.2",
"http-errors": "^1.6.1",
"jsonwebtoken": "^7.4.0",
"mocha": "^3.3.0",
"mongoose": "^4.9.8"
},
"devDependencies": {
"coveralls": "^2.13.1",
"mocha": "^3.3.0",
"mocha-lcov-reporter": "^1.3.0",
"superagent": "^3.5.2"
}
}
26 changes: 26 additions & 0 deletions caleb-lab/routes/auth-routes.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
'use strict';

const debug = require('debug')('cfgram:auth-routes');
const basicAuth = require('../lib/basic-auth-middleware.js');
const userCtrl = require('../controllers/user-controller.js');

module.exports = function(router){
router.post('/signup', (req, res) => {
debug('POST /signup');

return userCtrl.createUser(req.body)
.then(token => {
console.log('userCtrl createUser', token);
res.json(token)
})
.catch(err => res.status(err.status).send(err));
});

router.get('/signin', basicAuth, (req, res) => {
debug('GET /signin');
return userCtrl.fetchUser(req.auth)
.then(token => res.json(token))
.catch(err => res.status(400).send(err));
});
return router;
};
Loading