Skip to content

Lab16 darcy #47

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 9 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 @@
PORT='3000'
MONGODB_URI='mongodb://localhost/cfgramtester'
APP_SECRET='WOOTWOOT!'
18 changes: 18 additions & 0 deletions .travis.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
language: node_js
node_js:
- 'stable'
services:
- mongodb
addons:
apt:
sources:
- ubuntu-toolchain-r-test
packages:
- gcc-4.8
- g++-4.8
env:
- CXX=g++-4.8
sudo: required
before_script: npm i
script:
- npm run test
75 changes: 21 additions & 54 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,59 +1,26 @@
![cf](https://i.imgur.com/7v5ASc8.png) Lab 16 - Basic Auth
======

## To Submit this Assignment
* fork this repository
* write all of your code in a directory named `lab-` + `<your name>` **e.g.** `lab-brian`
* push to your repository
* submit a pull request to this repository
* submit a link to your PR in canvas
* write a question and observation on canvas

## Include
* `package.json`
* `.eslintrc`
* `gulpfile.js`
* `.gitignore`
* `.env`
* `README.md`

## Description
* Create the following directories to organize your code:
* **lib**
* **model**
* **route**
* **test**
* Create an HTTP server using `express`
* Using `mongoose`, create a **User** model with the following properties and options:
* `username` - *required and unique*
* `email` - *required and unique*
* `password` - *required - this must be hashed and can not stored as plain text*
* `findHash` - *unique*
* Use the **npm** `debug` module to log function calls that are used within your application
* Use the **express** `Router` to create a custom router for allowing users to **sign up** and **sign in**
* Use the **npm** `dotenv` module to house the following environment variables:
* `PORT`
* `MONGODB_URI`
* `APP_SECRET` *(used for signing and verify tokens)*
* Basic API Authentication with route tests

## Server Endpoints
### `/api/signup`
* `POST` request
* the client should pass the username and password in the body of the request
* the server should respond with a token (generated using `jwt` and `findHash`
* the server should respond with **400 Bad Request** to a failed request

### `/api/signin`
* `GET` request
* the client should pass the username and password to the server using a `Basic:` authorization header
* the server should respond with a token for authenticated users
* the server should respond with **401 Unauthorized** for non-authenticated users

## Tests
* Create a test that will ensure that your API returns a status code of **404** for any routes that have not been registered
* `/api/signup`
* `POST` - test **400**, if no request body has been provided or the body is invalid
* `POST` - test **200**, if the request body has been provided and is valid
* `/api/signin`
* `GET` - test **401**, if the user could not be authenticated
* `GET` - test **200**, responds with token for a request with a valid basic authorization header
## To Get this API working
* fork this repository
* install npm
* In your terminal open a 2nd tab
* In the first tab run the command:
```sh
mongod
```
* In the other tab run the command:
```sh
node server.js
```
* Go to browser and enter in:
[http://localhost:3000]
* this should open up the API
* to issue commands- chain them after the end of the address:
```
3000/GET
```

117 changes: 117 additions & 0 deletions gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,117 @@
# 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

# 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 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(){
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']);
19 changes: 19 additions & 0 deletions lib/basic-auth-middleware.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
'use strict';

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

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

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

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

};
27 changes: 27 additions & 0 deletions lib/error-middleware.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
'use strict';

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

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;
};

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

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

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(err);
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(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');
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);
1 change: 1 addition & 0 deletions node_modules/.bin/_mocha

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

1 change: 1 addition & 0 deletions node_modules/.bin/mime

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

1 change: 1 addition & 0 deletions node_modules/.bin/mkdirp

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

1 change: 1 addition & 0 deletions node_modules/.bin/mocha

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

1 change: 1 addition & 0 deletions node_modules/.bin/node-pre-gyp

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

1 change: 1 addition & 0 deletions node_modules/.bin/nopt

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

1 change: 1 addition & 0 deletions node_modules/.bin/rc

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

1 change: 1 addition & 0 deletions node_modules/.bin/rimraf

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

1 change: 1 addition & 0 deletions node_modules/.bin/semver

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

1 change: 1 addition & 0 deletions node_modules/.bin/sshpk-conv

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

Loading