diff --git a/.coveralls.yml b/.coveralls.yml new file mode 100644 index 0000000..bc7e1df --- /dev/null +++ b/.coveralls.yml @@ -0,0 +1,2 @@ +service_name: travis-ci +repo_token: swd8oweVDiONheCgxzP0lxarI45ODDJxd diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..5702678 --- /dev/null +++ b/.gitignore @@ -0,0 +1,65 @@ + +# 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 + + +# End of https://www.gitignore.io/api/node diff --git a/.travis.yml b/.travis.yml new file mode 100644 index 0000000..3d980f3 --- /dev/null +++ b/.travis.yml @@ -0,0 +1,19 @@ +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 + -npm run lint diff --git a/lib/basic-auth-middleware.js b/lib/basic-auth-middleware.js new file mode 100644 index 0000000..0dbd522 --- /dev/null +++ b/lib/basic-auth-middleware.js @@ -0,0 +1,37 @@ +'use strict'; + +const createError = require('http-errors'); +const debug = require('debug')('cfgram:basic-auth-middleware'); + +module.exports = function(req, res, next) { + debug('basic auth'); + + // console.log('LOOK HERE NOAH, BEFORE:', req.headers.authorization); + var authHeader = req.headers.authorization; + // console.log('LOOK HERE NOAH, AFTER:', 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')); + } + + var utf8str = new Buffer(base64str, 'base64').toString(); + var authArr = utf8str.split(':'); + + req.auth = { + username: authArr[0], + password: authArr[1] + }; + + if(!req.auth.username){ + return next(createError(401, 'username required')); + } + if(!req.auth.password){ + return next(createError(401, 'password required')); + } + + next(); +}; diff --git a/lib/bearer-auth-middleware.js b/lib/bearer-auth-middleware.js new file mode 100644 index 0000000..491f7ba --- /dev/null +++ b/lib/bearer-auth-middleware.js @@ -0,0 +1,38 @@ +'use strict'; + +const jwt = require('jsonwebtoken'); +const createError = require('http-errors'); +const debug = require('debug')('cfgram:bearer-auth-middleware'); + +const User = require('../model/user.js'); + +module.exports = function(req, res, next) { + debug('bearer-auth'); + // console.log('req headers auth:', req.headers.authorization); + // console.log('Request:', req); + var authHeader = req.headers.authorization; + // console.log('req headers:', req.headers); + if(!authHeader) { + return next(createError(401, 'authorization header required')); + } + + var token = authHeader.split('Bearer ')[1]; + if(!token) { + return next(createError(401, 'token required')); + } + // console.log('Auth Header:', authHeader); + // console.log('token', token); + jwt.verify(token, process.env.APP_SECRET, (err, decoded) => { + if (err) return next(err); + // console.log('DECODED:', decoded); + + User.findOne({ findHash: decoded.token}) + .then( user => { + req.user = user; + next(); + }) + .catch(err => { + next(createError(401, err.message)); + }); + }); +}; diff --git a/lib/error-middleware.js b/lib/error-middleware.js new file mode 100644 index 0000000..3c0f42b --- /dev/null +++ b/lib/error-middleware.js @@ -0,0 +1,29 @@ +'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.name === 'ValidationError') { + err = createError(400, err.message); + res.status(err.status).send(err.name); + next(); + return; + } + + if (err.status) { + res.status(err.status).send(err.name); + next(); + return; + } + + + err = createError(500, err.message); + res.status(err.status).send(err.name); + next(); +}; diff --git a/model/gallery.js b/model/gallery.js new file mode 100644 index 0000000..22d6f75 --- /dev/null +++ b/model/gallery.js @@ -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); diff --git a/model/pic.js b/model/pic.js new file mode 100644 index 0000000..6ae6ecd --- /dev/null +++ b/model/pic.js @@ -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}, + imageURI: {type: String, required: true, unique: true}, + objectKey: {type: String, required: true, unique: true}, + created: {type: Date, default: Date.now}, +}); + +module.exports = mongoose.model('pic', picSchema); diff --git a/model/user.js b/model/user.js new file mode 100644 index 0000000..dd4c376 --- /dev/null +++ b/model/user.js @@ -0,0 +1,76 @@ +'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); diff --git a/package.json b/package.json new file mode 100644 index 0000000..6ee1714 --- /dev/null +++ b/package.json @@ -0,0 +1,49 @@ +{ + "name": "16-basic_auth", + "version": "1.0.0", + "description": "![cf](https://i.imgur.com/7v5ASc8.png) Lab 16 - Basic Auth\r ======", + "main": "server.js", + "directories": { + "test": "test" + }, + "scripts": { + "test": "DEBUG='cfgram*' mocha", + "coveralls": "istanbul cover ./node_modules/mocha/bin/_mocha --report lcovonly -- -R spec && cat ./coverage/lcov.info | ./node_modules/coveralls/bin/coveralls.js && rm -rf ./coverage", + "start": "DEBUG='cfgram*' node server.js" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/noahgribbin/16-basic_auth.git" + }, + "keywords": [], + "author": "", + "license": "ISC", + "bugs": { + "url": "https://github.com/noahgribbin/16-basic_auth/issues" + }, + "homepage": "https://github.com/noahgribbin/16-basic_auth#readme", + "dependencies": { + "aws-sdk": "^2.24.0", + "bcrypt": "^1.0.2", + "bluebird": "^3.5.0", + "body-parser": "^1.17.1", + "cors": "^2.8.1", + "debug": "^2.6.1", + "del": "^2.2.2", + "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", + "multer": "^1.3.0" + }, + "devDependencies": { + "aws-sdk-mock": "^1.6.1", + "chai": "^3.5.0", + "coveralls": "^2.12.0", + "istanbul": "^0.4.5", + "mocha": "^3.2.0", + "superagent": "^3.5.0" + } +} diff --git a/route/auth-router.js b/route/auth-router.js new file mode 100644 index 0000000..424119b --- /dev/null +++ b/route/auth-router.js @@ -0,0 +1,36 @@ +'use strict'; + +const jsonParser = require('body-parser').json(); +const debug = require('debug')('cfgram:auth-router'); +const Router = require('express').Router; +const basicAuth = require('../lib/basic-auth-middleware.js'); +const createError = require('http-errors'); + +const User = require('../model/user.js'); + +const authRouter = module.exports = Router(); + +authRouter.post('/api/signup', jsonParser, function(req, res, next) { + debug('POST /api/signup'); + + let password = req.body.password; + delete req.body.password; + + let user = new User(req.body); + + user.generatePasswordHash(password) + .then( user => user.save()) + .then( user => user.generateToken()) + .then( token => res.send(token)) + .catch(err => next(createError(400, err.message))); +}); + +authRouter.get('/api/signin', basicAuth, function(req, res, next) { + debug('GET /api/signin'); + + User.findOne({ username: req.auth.username }) + .then( user => user.comparePasswordHash(req.auth.password)) + .then( user => user.generateToken()) + .then( token => res.send(token)) + .catch(next); +}); diff --git a/route/gallery-router.js b/route/gallery-router.js new file mode 100644 index 0000000..4770fca --- /dev/null +++ b/route/gallery-router.js @@ -0,0 +1,54 @@ +'use strict'; + +const Router = require('express').Router; +const jsonParser = require('body-parser').json(); +const createError = require('http-errors'); +const debug = require('debug')('cfgram:gallery-router'); + +const Gallery = require('../model/gallery.js'); +const bearerAuth = require('../lib/bearer-auth-middleware.js'); + +const galleryRouter = module.exports = Router(); + +galleryRouter.post('/api/gallery', bearerAuth, jsonParser, function(req, res, next) { + debug('POST /api/gallery'); + + //the gallery will not valdate without the req.body BECAUSE the REQUIRED id was just attached to it + req.body.userID = req.user._id; + new Gallery(req.body).save() + .then( gallery => res.json(gallery)) + .catch(next); +}); + +galleryRouter.get('/api/gallery/:id', bearerAuth, function(req, res, next) { + debug('GET /api/galler/:id'); + + Gallery.findById(req.params.id) + .then( gallery => { + if (gallery.userID.toString() !== req.user._id.toString()) { + return next(createError(401, 'invalid user')); + } + res.json(gallery); + }) + .catch(next); +}); + +galleryRouter.put('/api/gallery/:id', bearerAuth, jsonParser, function(req, res, next) { + debug('PUT /api/galler/:id'); + Gallery.findByIdAndUpdate(req.params.id, res.body, {new:true}) + .then( gallery => { + if (gallery.userID.toString() !== req.user._id.toString()) { + return next(createError(401, 'invalid user')); + } + res.json(gallery); + }) + .catch(next); +}); + +galleryRouter.delete('/api/gallery/:id', function(req, res, next) { + debug('DELETE /api/galler/:id'); + + Gallery.findByIdAndRemove(req.params.id) + .then( () => res.status(204).send()) + .catch( err => next(createError(404, err.message))); +}); diff --git a/route/pic-router.js b/route/pic-router.js new file mode 100644 index 0000000..5a7d3c9 --- /dev/null +++ b/route/pic-router.js @@ -0,0 +1,70 @@ +'use strict'; + +const fs = require('fs'); +const path = require('path'); +const del = require('del'); +const AWS = require('aws-sdk'); +const multer = require('multer'); +const Router = require('express').Router; +const createError = require('http-errors'); +const debug = require('debug')('cfgram:pic-router'); + +const Pic = require('../model/pic.js'); +const Gallery = require('../model/gallery.js'); +const bearerAuth = require('../lib/bearer-auth-middleware.js'); + +AWS.config.setPromisesDependency(require('bluebird')); + +const s3 = new AWS.S3(); +const dataDir = `${__dirname}/../data`; +const upload = multer({dest: dataDir}); + +const picRouter = module.exports = Router(); + +function s3uploadProm(params) { + debug('s3uploadProm'); + + return new Promise((resolve, reject) => { + s3.upload(params, (err, s3data) => { + resolve(s3data); + }); + }); +} + +picRouter.post('/api/gallery/:galleryID/pic', bearerAuth, upload.single('image'), function(req, res, next) { + debug('POST: /api/gallery/:galleryID/pic'); + + if(!req.file) { + return next(createError(400, 'file not found')); + } + + if(!req.file.path) { + return next(createError(500, 'file not saved')); + } + + let ext = path.extname(req.file.originalname); + + let params = { + ACL: 'public-read', + Bucket: process.env.AWS_BUCKET, + Key: `${req.file.filename}${ext}`, + Body: fs.createReadStream(req.file.path) + }; + + Gallery.findById(req.params.galleryID) + .then( () => s3uploadProm(params)) + .then( s3data => { + del([`${dataDir}/*`]); + let picData = { + name: req.body.name, + desc: req.body.desc, + objectKey: s3data.Key, + imageURI: s3data.Location, + userID: req.user._id, + galleryID: req.params.galleryID + }; + return new Pic(picData).save(); + }) + .then(pic => res.json(pic)) + .catch( err => next(err)); +}); diff --git a/server.js b/server.js new file mode 100644 index 0000000..67e698b --- /dev/null +++ b/server.js @@ -0,0 +1,35 @@ +'use strict'; + +const express = require('express'); +const cors = require('cors'); +const dotenv = require('dotenv'); +const morgan = require('morgan'); +const mongoose = require('mongoose'); +const Promise = require('bluebird'); +const debug = require('debug')('cfgram:server'); + +const authRouter = require('./route/auth-router.js'); +const galleryRouter = require('./route/gallery-router.js'); +const picRouter = require('./route/pic-router.js'); +const errors = require('./lib/error-middleware.js'); + +dotenv.load(); + +const PORT = process.env.PORT || 3000; +const app = express(); + +mongoose.connect(process.env.MONGODB_URI); + +app.use(cors()); +app.use(morgan('dev')); + +app.use(authRouter); +app.use(galleryRouter); +app.use(picRouter); +app.use(errors); + +const server = module.exports = app.listen(PORT, () => { + debug(`server up: ${PORT}`); +}); + +server.isRunning = true; diff --git a/test/auth-router-test.js b/test/auth-router-test.js new file mode 100644 index 0000000..f663c80 --- /dev/null +++ b/test/auth-router-test.js @@ -0,0 +1,111 @@ +'use strict'; + +const expect = require('chai').expect; +const request = require('superagent'); +const mongoose = require('mongoose'); +const Promise = require('bluebird'); +const User = require('../model/user.js'); + +require('../server.js'); + +const url = `http://localhost:${process.env.PORT}`; + +const exampleUser = { + username: 'exampleuser', + password: '1234', + email: 'exampleuser@test.com' +}; + +describe('Auth Routes', function() { + describe('POST: /api/signup', function() { + describe('with a valid body', function() { + after( done => { + User.remove({}) + .then( () => done()) + .catch(done); + }); + before( done => { + User.remove({}) + .then( () => done()) + .catch(done); + }); + it('should return a token', done => { + request.post(`${url}/api/signup`) + .send(exampleUser) + .end((err, res) => { + if (err) return done(err); + // console.log('OVER HEREEEEEEE:', res); + expect(res.status).to.equal(200); + expect(res.text).to.be.a('string') ; + done(); + }); + }); + }); + describe('with an invalid body', function() { + it('should return 400', done => { + request.post(`${url}/api/signup`) + .send({ + username: 'exampleuseraaa', + password: '1234' + }) + .end((err, res) => { + // if(err) return done(err); + expect(res.status).to.equal(400); + done(); + }); + }); + }); + }); + + describe('GET: /api/signin', function() { + describe('with a valid body', function() { + before( done => { + let user = new User(exampleUser); + user.generatePasswordHash(exampleUser.password) + .then( user => user.save()) + .then( user => { + this.tempUser = user; + done(); + }) + .catch(done); + }); + + after( done => { + User.remove({}) + .then( () => done()) + .catch(done); + }); + + it('should return a token', done => { + request.get(`${url}/api/signin`) + .auth('exampleuser', '1234') + // + .end((err, res) => { + if (err) return done(err); + expect(res.status).to.equal(200); + done(); + }); + }); + }); + describe('with an invalid body', function() { + before( done => { + let user = new User(exampleUser); + user.generatePasswordHash(exampleUser.password) + .then( user => user.save()) + .then( user => { + this.tempUser = user; + done(); + }) + .catch(done); + }); + it('should return 401, authentication error', done => { + request.get(`${url}/api/signin`) + .auth('exampleusertest') + .end((err, res) => { + expect(res.status).to.equal(401); + done(); + }); + }); + }); + }); +}); diff --git a/test/data/tester.png b/test/data/tester.png new file mode 100644 index 0000000..04c99f2 Binary files /dev/null and b/test/data/tester.png differ diff --git a/test/gallery-router-test.js b/test/gallery-router-test.js new file mode 100644 index 0000000..c26ebf6 --- /dev/null +++ b/test/gallery-router-test.js @@ -0,0 +1,237 @@ +'use strict'; + +const expect = require('chai').expect; +const request = require('superagent'); +const mongoose = require('mongoose'); +const Promise = require('bluebird'); +const User = require('../model/user.js'); +const Gallery = require('../model/gallery.js'); + +const url = `http://localhost:${process.env.PORT}`; + + +const exampleUser = { + username: 'exampleuser', + password: '1234', + email: 'exampleuser@test.com' +}; +const updatedUser = { + username: 'updateduser', + password: '1234', + email: 'exampleuser@test.com' +}; +const invalidUser = { + username: 1, + password: '1234', + email: 'exampleuser@test.com' +}; +const exampleGallery = { + name: 'test gallery', + desc: 'test gallery description' +}; + +describe('Gallery Routes', function() { + afterEach(done => { + Promise.all([ + User.remove({}), + Gallery.remove({}) + ]) + .then( () => done()) + .catch(done); + }); + + describe('POST: /api/gallery', () => { + beforeEach( done => { + User.remove({}) + .then( () => done()) + .catch(done); + }); + beforeEach( done => { + new User(exampleUser) + .generatePasswordHash(exampleUser.password) + .then( user => user.save()) + .then( user => { + this.tempUser = user; + console.log('intermediate value?:', user); + return user.generateToken(); + }) + .then( token => { + this.tempToken = token; + done(); + }) + .catch(done); + }); + afterEach( done => { + User.remove({}) + .then( () => done()) + .catch(done); + }); + it('should return a gallery', done => { + request.post(`${url}/api/gallery`) + .send(exampleGallery) + .set({ + Authorization: `Bearer ${this.tempToken}` + }) + .end((err, res) => { + if (err) return done(err); + let date = new Date(res.body.created).toString(); + expect(res.body.name).to.equal(exampleGallery.name); + expect(res.body.desc).to.equal(exampleGallery.desc); + expect(res.body.userID).to.equal(this.tempUser._id.toString()); + expect(date).to.not.equal('invalid date'); + expect(res.status).to.equal(200); + done(); + }); + }); + it('should return 401, no token', done => { + request.post(`${url}/api/gallery`) + .send(exampleGallery) + .set({ + Authorization: 'Bearer ' + }) + .end((err, res) => { + expect(res.status).to.equal(401); + done(); + }); + }); + it('should return 400, invalid body', done => { + request.post(`${url}/api/gallery`) + .send({}) + .set({ + Authorization: `Bearer ${this.tempToken}` + }) + .end((err, res) => { + expect(res.status).to.equal(400); + done(); + }); + }); + }); + describe('GET: /api/gallery/:id', function() { + beforeEach( done => { + new User(exampleUser) + .generatePasswordHash(exampleUser.password) + .then( user => user.save()) + .then( user => { + this.tempUser = user; + return user.generateToken(); + }) + .then( token => { + this.tempToken = token; + done(); + }) + .catch(done); + }); + + beforeEach( done => { + exampleGallery.userID = this.tempUser._id.toString(); + new Gallery(exampleGallery).save() + .then( gallery => { + this.tempGallery = gallery; + done(); + }) + .catch(done); + }); + + afterEach( () => { + delete exampleGallery.userID; + }); + + it('should return a gallery', done => { + request.get(`${url}/api/gallery/${this.tempGallery._id}`) + .set({ + Authorization: `Bearer ${this.tempToken}` + }) + .end((err, res) => { + if (err) return done(err); + let date = new Date(res.body.created).toString(); + expect(res.body.name).to.equal(exampleGallery.name); + expect(res.body.desc).to.equal(exampleGallery.desc); + expect(res.body.userID).to.equal(this.tempUser._id.toString()); + expect(res.status).to.equal(200); + expect(date).to.not.equal('invalid date'); + done(); + }); + }); + it('should return 401, no token', done => { + request.get(`${url}/api/gallery/${this.tempGallery._id}`) + .set({ + Authorization: 'Bearer ' + }) + .end((err, res) => { + expect(res.status).to.equal(401); + done(); + }); + }); + it('should return 404', done => { + request.get(`${url}/apu/test`) + .set({ + Authorization: `Bearer ${this.tempToken}` + }) + .end((err, res) => { + expect(res.status).to.equal(404); + done(); + }); + }); + }); + describe('PUT: /api/gallery/:id', () => { + beforeEach(done => { + new User(exampleUser) + .generatePasswordHash(exampleUser.password) + .then( user => user.save()) + .then( user => { + this.tempUser = user; + return user.generateToken(); + }) + .then(token => { + this.tempToken = token; + done(); + }) + .catch(done); + }); + beforeEach( done => { + exampleGallery.userID = this.tempUser._id.toString(); + new Gallery(exampleGallery).save() + .then( gallery => { + this.tempGallery = gallery; + done(); + }) + .catch(done); + }); + it('should update a gallery', done => { + request.put(`${url}/api/gallery/${this.tempGallery._id}`) + .set({ + Authorization: `Bearer ${this.tempToken}` + }) + .send(updatedUser) + .end((err, res) => { + if (err) return done(err); + let date = new Date(res.body.created).toString(); + expect(res.status).to.equal(200); + expect(date).to.not.equal('invalid date'); + done(); + }); + }); + it('should return 401, no token', done => { + request.put(`${url}/api/gallery/${this.tempGallery._id}`) + .set({ + Authorization: 'Bearer ' + }) + .send(updatedUser) + .end((err, res) => { + expect(res.status).to.equal(401); + done(); + }); + }); + it('should return 400, invalid body', done => { + request.put(`${url}/api/gallery/${this.tempGallery._id}`) + .set({ + Authorization: `Bearer ${this.tempToken}` + }) + .send(invalidUser) + .end((err, res) => { + expect(res.status).to.equal(400); + done(); + }); + }); + }); +}); diff --git a/test/lib/server-toggle.js b/test/lib/server-toggle.js new file mode 100644 index 0000000..25ff01a --- /dev/null +++ b/test/lib/server-toggle.js @@ -0,0 +1,29 @@ +'use strict'; + +const debug = require('debug')('cfgram:server-toggle'); + +module.exports = exports = {}; + +exports.serverOn = function(server, done) { + if(!server.isRunning) { + server.listen(process.env.PORT, () => { + server.isRunning = true; + debug('server up!'); + done(); + }); + return; + } + done(); +}; + +exports.serverOff = function(server, done) { + if(server.isRunning) { + server.close( err => { + server.isRunning = false; + debug('server off!'); + done(); + }); + return; + } + done(); +}; diff --git a/test/pic-router-test.js b/test/pic-router-test.js new file mode 100644 index 0000000..aa7ad29 --- /dev/null +++ b/test/pic-router-test.js @@ -0,0 +1,101 @@ +'use strict'; + +const expect = require('chai').expect; +const request = require('superagent'); +const debug = require('debug')('cfgram:pic-router-test'); + +const Pic = require('../model/pic.js'); +const User = require('../model/user.js'); +const Gallery = require('../model/gallery.js'); + +const serverToggle = require('./lib/server-toggle.js'); +const server = require('../server.js'); + +const url = `http://localhost:${process.env.PORT}`; + +const exampleUser = { + username: 'exampleser', + password: '1234', + email: 'exampleuser@test.com' +}; + +const exampleGallery = { + name: 'test gallery', + desc: 'test gallery description' +}; + +const examplePic = { + name: 'example pic', + desc: 'example pic desc', + image: `${__dirname}/data/tester.png` +}; + +describe('Pic Routes', function() { + before(done => { + serverToggle.serverOn(server, done); + }); + after( done => { + serverToggle.serverOff(server, done); + }); + afterEach( done => { + Promise.all([ + Pic.remove({}), + User.remove({}), + Gallery.remove({}) + ]) + .then( () => done()) + .catch(done); + }); + + describe('POST: /api/gallery/galleryID/pic', function() { + describe('with a valid body', function() { + + before( done => { + new User(exampleUser) + .generatePasswordHash(exampleUser.password) + .then( user => user.save()) + .then( user => { + this.tempUser = user; + return user.generateToken(); + }) + .then( token => { + this.tempToken = token; + done(); + }) + .catch(done); + }); + + before( done => { + exampleGallery.userID = this.tempUser._id.toString(); + new Gallery(exampleGallery).save() + .then( gallery => { + this.tempGallery = gallery; + done(); + }) + .catch(done); + }); + + after( done => { + delete exampleGallery.userID; + done(); + }); + + it('should return a pic', done => { + request.post(`${url}/api/gallery/${this.tempGallery._id}/pic`) + .set({ + Authorization: `Bearer ${this.tempToken}` + }) + .field('name', examplePic.name) + .field('desc', examplePic.desc) + .attach('image', examplePic.image) + .end((err, res) => { + if(err) return done(err); + expect(res.body.name).to.equal(examplePic.name); + expect(res.body.desc).to.equal(examplePic.desc); + expect(res.body.galleryID).to.equal(this.tempGallery._id.toString()); + done(); + }); + }); + }); + }); +});