Skip to content

Lab 18 -Yana #39

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 20 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
20 commits
Select commit Hold shift + click to select a range
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
7 changes: 7 additions & 0 deletions lab-yana/.env
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
PORT='3003'
MONGODB_URI='mongodb://localhost/cfgram'
APP_SECRET='mysupersekritthingy'
APP_SECRET='uhwhut'
AWS_BUCKET='cfgrambackend42'
AWS_ACCESS_KEY_ID='AKIAIUKO3XB6OQZSFZQA'
AWS_SECRET_ACCESS_KEY='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'
21 changes: 21 additions & 0 deletions lab-yana/.eslintrc
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
{
"rules": {
"no-console": "off",
"indent": [ "error", 2 ],
"quotes": [ "error", "single" ],
"semi": ["error", "always"],
"linebreak-style": [ "error", "unix" ]
},
"env": {
"es6": true,
"node": true,
"mocha": true,
"jasmine": true
},
"ecmaFeatures": {
"modules": true,
"experimentalObjectRestSpread": true,
"impliedStrict": true
},
"extends": "eslint:recommended"
}
119 changes: 119 additions & 0 deletions lab-yana/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,119 @@
# Created by https://www.gitignore.io/api/node,vim,osx,macos,linux
*node_modules

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

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

# file containing SUPER SEKRIT VARIABLES
.env

# 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
3 changes: 3 additions & 0 deletions lab-yana/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
This is a server that allows you to sign in or sign up, using basic authorization and authentication using a token generated by the middleware jsonwebtoken as well as hashing using the native node module crypto as well as the imported module bcrypt. The server now allows you to create galleries with a name and description.

_created by_ Yana Radenska
Binary file added lab-yana/data/d36c6fc77352cf478b70c0db17b86142
Binary file not shown.
20 changes: 20 additions & 0 deletions lab-yana/gulpfile.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
'use strict';

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

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

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

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

gulp.task('default', ['dev']);
27 changes: 27 additions & 0 deletions lab-yana/lib/basic-auth-middleware.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
'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');

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

var base64string = authHeader.split('Basic ')[1]; //takes the username and password part of the auth header
if (!base64string) return next(createError(401, 'username and password required'));

var utf8string = new Buffer(base64string, 'base64').toString(); //turns our string into a readable by humans string
var authArray = utf8string.split(':'); //puts the username in index 0 of array and the password in index 1

req.auth = { //create new property auth of request object
username: authArray[0],
password: authArray[1]
};

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

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

const debug = require('debug')('cfgram: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-auth-middleware');

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

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

jwt.verify(token, process.env.APP_SECRET, function(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-yana/lib/error-middleware.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
'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.error(`msg: ${err.message}`);
console.error(`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;
}

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

err = createError(500, err.message);
res.status(err.status).send(err.message);
next();

};
13 changes: 13 additions & 0 deletions lab-yana/model/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, required: true, default: Date.now },
userID: { type: Schema.Types.ObjectId, required: true }
});

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

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

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

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

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

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) => { //take the plain text password the user chose and turn it into a hash
if (err) return reject(err);
this.password = hash; //store the hashed password
resolve(this);
});
});
};

userSchema.methods.comparePasswordHash = function(password) {
debug('comparePasswordHash');
return new Promise((resolve, reject) => {
bcrypt.compare(password, this.password, (err, valid) => { //compare a user entered password with their hashed password
if (err) return reject(err);
if (!valid) return reject(createError(401, 'wrong password'));
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'); //assign to findHash a randomly generated hash for two step authentication
this.save() //make sure to save it in db
.then( () => resolve(this.findHash))
.catch(err => {
if (tries > 3) return reject(err);
tries++;
_generateFindHash.call(this); //try to generate the FindHash again until it has been tried 3 times
});
}
});
};

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);
Loading