Skip to content

Patrick-Lab-17 #11

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
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Empty file added .env
Empty file.
3 changes: 3 additions & 0 deletions lab-patrick/.eslintignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
**/node_modules/*
**/vendor/*
**/*.min.js
25 changes: 25 additions & 0 deletions lab-patrick/.eslintrc
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
{
"rules": {
"quotes": ["error", "single", { "allowTemplateLiterals": true }],
"comma-dangle": ["error", "always-multiline"],
"no-console": "off",
"indent": [ "error", 2 ],
"semi": ["error", "always"]
},
"env": {
"es6": true,
"node": true,
"mocha": true,
"jasmine": true
},
"globals": {
"__API_URI__": false,
"__DEBUG__": false
},
"ecmaFeatures": {
"modules": true,
"experimentalObjectRestSpread": true,
"impliedStrict": true
},
"extends": "eslint:recommended"
}
70 changes: 70 additions & 0 deletions lab-patrick/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@

db/

.env

# Created by https://www.gitignore.io/api/osx,linux,node,vim

### OSX ###
.DS_Store
.AppleDouble
.LSOverride

### Linux ###
*~

# temporary files which can be created if a process still has a handle open of a deleted file
.fuse_hidden*

# KDE directory preferences
.directory

# Linux trash folder which might appear on any partition or disk
.Trash-*


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

# Runtime data
pids
*.pid
*.seed

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

# Coverage directory used by tools like istanbul
coverage

# node-waf configuration
.lock-wscript

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

# Dependency directories
node_modules
jspm_packages

# Optional npm cache directory
.npm

# Optional REPL history
.node_repl_history

### Vim ###
# swap
[._]*.s[a-w][a-z]
[._]s[a-w][a-z]
# session
Session.vim
# temporary
.netrwhist
*~

# auto-generated tag files
tags
21 changes: 21 additions & 0 deletions lab-patrick/.travis.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
language: node_js
node_js:
- '4.4.3'
services:
- mongodb
addons:
apt:
sources:
- ubuntu-toolchain-r-test
packages:
- gcc-4.8
- g++-4.8
env:
- CXX=g++-4.8
- MONGODB_URI=mongodb://localhost/test
- PORT=3000
- APP_SECRET='lulwat top secret'
sudo: required
before_script: npm i -g eslint mocha
script:
- ./script/test-submissions.sh
36 changes: 36 additions & 0 deletions lab-patrick/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
# Lab-17
# Patrick Sheridan

## Overview
The point of this lab was to create a mongo database where a user could sign up and sign in, create, update, get, and delete a photeo gallery

## To Use
With a mongod running, enter the following commands into a new terminal.

### User signup/POST
```
http POST :3000/api/signup username=<username> email=<email> password=<password>
```
### User signin/GET
```
http GET :3000/api/signin -a <username>:<password>
```

### Galley POST
```
http POST :3000/api/gallery name=<picture name> desc=<description> 'Authorization:Bearer'
```
Bearer token can be found in the USER GET/POST response

### Gallery GET
```
http GET :3000/api/gallery/:galleryId 'Authorization:Bearer'
```
### Gallery PUT/Update
```
http PUT :3000/api/gallery/<galleryID> name=<new picture name> desc=<new description> 'Authorization:Bearer'
```
### Gallery DELETE
```
http DELETE :3000/api/gallery/<galleryID> 'Authorization:Bearer'
```
31 changes: 31 additions & 0 deletions lab-patrick/controller/gallery-controller.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
'use strict';

const Gallery = require('../models/gallery');

module.exports = exports ={};

exports.createItem = function(body, user){
body.userId = user._id;
return new Gallery(body).save()
.then(gallery => gallery)
.catch(err => body.status(err.status).send(err.message));

};

exports.fetchItem = function(id, res){
return Gallery.findById(id)
.then(gallery => gallery)
.catch(err => res.status(err.status).send(err.message));
};

exports.updateItem = function(req, res, id){
return Gallery.findByIdAndUpdate(id, req.body, {new:true})
.then(gallery => gallery)
.catch(err => res.status(err.status).send(err.message));
};

exports.deleteItem = function(req, res, id){
Gallery.findByIdAndRemove(id)
.then(() => res.status(204).send())
.catch(err => res.status(err.status).send(err.message));
};
33 changes: 33 additions & 0 deletions lab-patrick/controller/user-controller.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
'use strict';

const Promise = require('bluebird');
const createError = require('http-errors');
const User = require('../models/user');

module.exports = exports ={};

exports.createItem = function(req, res){

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

let newUser = new User(req.body);

return newUser.generatePasswordHash(tempPassword)
.then(user => user.save())
.then(user => user.generateToken())
.catch(err => res.status(err.status).send(err.message));
};

exports.fetchItem = function(res, reqAuth){

if(!reqAuth) return Promise.reject(createError(404, 'Authorization required'));

return User.findOne({username: reqAuth.username})
.then(user => user.comparePasswordHash(reqAuth.password))
.then(user => user.generateToken())
.catch(err => res.status(err.status).send(err.message));

};
22 changes: 22 additions & 0 deletions lab-patrick/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 lab-patrick/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 lab-patrick/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 lab-patrick/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, reuqired: true},
});

module.exports = mongoose.model('gallery', gallerySchema);
74 changes: 74 additions & 0 deletions lab-patrick/models/user.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
'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 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) {

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) {

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() {

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(err) throw err;
if(tries > 3) return reject(createError(401, 'Generate findhash failed'));
tries++;
_generateFindHash();
});
};

_generateFindHash();
});
};

userSchema.methods.generateToken = function() {
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);
Loading