Skip to content
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

lab-17-remil #30

Open
wants to merge 16 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: 2 additions & 0 deletions lab-remil/.env
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
APP_SECRET='ayo'
MONGODB_URI='mongodb://localhost/ayogramdb'
22 changes: 22 additions & 0 deletions lab-remil/.eslintrc
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
{
"rules": {
"no-console": "off",
"indent": [ "error", 2 ],
"quotes": [ "error", "single" ],
"semi": ["error", "always"],
"linebreak-style": [ "error", "unix" ],
"comma-dangle": ["error", "always-multiline"]
},
"env": {
"es6": true,
"node": true,
"mocha": true,
"jasmine": true
},
"ecmaFeatures": {
"modules": true,
"experimentalObjectRestSpread": true,
"impliedStrict": true
},
"extends": "eslint:recommended"
}
121 changes: 121 additions & 0 deletions lab-remil/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,121 @@
# Created by https://www.gitignore.io/api/node,vim,osx,macos,linux

### My Custom Jams ###
*.env
.appnote

*node_modules

### Node ###
# Logs
logs
*.log
npm-debug.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

# 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 eslint cache
.eslintcache

# Optional REPL history
.node_repl_history

# Output of 'npm pack'
*.tgz

# Yarn Integrity file
.yarn-integrity



### Vim ###
# swap
[._]*.s[a-v][a-z]
[._]*.sw[a-p]
[._]s[a-v][a-z]
[._]sw[a-p]
# session
Session.vim
# temporary
.netrwhist
*~
# auto-generated tag files
tags


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

# Icon must end with two \r
Icon
# Thumbnails
._*
# Files that might appear in the root of a volume
.DocumentRevisions-V100
.fseventsd
.Spotlight-V100
.TemporaryItems
.Trashes
.VolumeIcon.icns
.com.apple.timemachine.donotpresent
# Directories potentially created on remote AFP share
.AppleDB
.AppleDesktop
Network Trash Folder
Temporary Items
.apdisk


### macOS ###
# Icon must end with two \r
# Thumbnails
# Files that might appear in the root of a volume
# Directories potentially created on remote AFP share


### 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-*

# .nfs files are created when an open file is removed but is still being accessed
.nfs*

# End of https://www.gitignore.io/api/node,vim,osx,macos,linux
23 changes: 23 additions & 0 deletions lab-remil/gulpfile.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
'use strict';

const gulp = require('gulp');
const eslint = require('gulp-eslint');
const mocha = require('gulp-mocha');

gulp.task('test', function gulpTest(){
gulp.src('./test/*-test.js', {read: false})
.pipe(mocha({reporter: 'spec'}));
});

gulp.task('lint', function gulpLint(){
return gulp.src(['**/*.js', '!node_modules/**'])
.pipe(eslint())
.pipe(eslint.format())
.pipe(eslint.failAfterError());
});

gulp.task('dev', function gulpDev(){
gulp.watch(['**/*.js', '!node_modules/**'], ['lint', 'test']);
});

gulp.task('default', ['dev']);
24 changes: 24 additions & 0 deletions lab-remil/lib/basic-auth-middleware.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
'use strict';

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

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

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

let base64str = authHeader.split('Basic ')[1];
if (!base64str) return next(createError(401, 'username and password required'));

let utf8str = new Buffer(base64str, 'base64').toString();
let authArray = utf8str.split(':');

req.auth = {
username: authArray[0],
password: authArray[1],
};

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

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

const User = require('../model/user.js');

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

let authHeader = req.headers.authorization;

if (!authHeader) return next(createError(401, 'authorization header required'));

let token = authHeader.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));
});
});
};
35 changes: 35 additions & 0 deletions lab-remil/lib/error-middleware.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
'use strict';

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

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

console.error('Error name:', err.name);
console.error('Error message:', err.message);

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

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

if (err.name === 'CastError') {
err = createError(404, err.message);
res.status(err.status).send(err.message);
next();
return;
}

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

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

const gallerySchema = Schema({
name: { type: String, required: true },
desc: { type: String, required: true },
created: { type: Date, required: true, default: Date.now },
userID: { type: Schema.Types.ObjectId, required: true },
});

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

const debug = require('debug')('ayogram:user');
const createError = require('http-errors');
const bcrypt = require('bcrypt');
const crypto = require('crypto');
const jwt = require('jsonwebtoken');

const Promise = require('bluebird');
const mongoose = require('mongoose');
mongoose.Promise = Promise;
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 bcrypt.hash(password, 10)
.then( hash => {
this.password = hash;
return this;
});
};

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

return bcrypt.compare(password, this.password)
.then( valid => {
if (!valid) return Promise.reject(createError(401, 'wrong password'));
return 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( err => {
if (tries > 3) return reject(err);
tries++;
_generateFindHash.call(this);
});
}
});
};

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

return new Promise((resolve, reject) => {
this.generateFindHash()
.then ( findHash => resolve(jwt.sign({ token: findHash }, process.env.APP_SECRET)))
.catch( err => reject(err));
});
};

module.exports = mongoose.model('User', userSchema);
34 changes: 34 additions & 0 deletions lab-remil/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
{
"name": "lab-remil",
"version": "1.0.0",
"description": "",
"main": "gulpfile.js",
"directories": {
"test": "test"
},
"scripts": {
"test": "DEBUG='ayogram*' mocha",
"start": "DEBUG='ayogram*' node server.js"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"bcrypt": "^1.0.2",
"bluebird": "^3.5.0",
"body-parser": "^1.17.1",
"cors": "^2.8.1",
"dotenv": "^4.0.0",
"express": "^4.15.2",
"http-errors": "^1.6.1",
"jsonwebtoken": "^7.3.0",
"mongoose": "^4.8.6",
"morgan": "^1.8.1"
},
"devDependencies": {
"chai": "^3.5.0",
"gulp": "^3.9.1",
"mocha": "^3.2.0",
"superagent": "^3.5.0"
}
}
Loading