Skip to content
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 .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
node_modules
.env
55 changes: 0 additions & 55 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,55 +0,0 @@
![CF](https://camo.githubusercontent.com/70edab54bba80edb7493cad3135e9606781cbb6b/687474703a2f2f692e696d6775722e636f6d2f377635415363382e706e67) 18: Image Uploads w/ AWS S3
===

## Submission Instructions
* fork this repository & create a new branch for your work
* write all of your code in a directory named `lab-` + `<your name>` **e.g.** `lab-susan`
* 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

## Learning Objectives
* students will be able to upload static assets to AWS S3
* students will be able to retrieve a cdn url that contains the previously uploaded static asset
* students will be able to work with secret and public access keys

## Requirements
#### Configuration
* `package.json`
* `.eslintrc`
* `.gitignore`
* `README.md`

#### Description
* create an AWS account
* create an AWS Access Key and Secret
* add the Access Key and Secret to your `.env` file
* create a new model that represents a file type that you want to store on AWS S3
* ex: `.mp3`, `.mp4`, `.png`, etc
* create a test that uploads one of these files to your route
* use the `aws-sdk` to assist with uploading
* use `multer` to parse the file upload request

#### Server Endpoint
* `POST` - `/api/resource/:resourceID/new-resource`

#### Tests
* `POST` - **200** - test that the upload worked and a resource object is returned

#### Bonus
* `DELETE` route - `/api/resource/:resourceID/new-resource/:new-resourceID`
* Test: `DELETE` - **204** - test to ensure the object was deleted from s3

#### Bonus: 3pts
* try using the `deleteObject` method provided by the `aws-sdk` to delete an object *(file)* from S3
* you will need to pass in a `params` object that contains the associated Bucket and AWS object key in order to delete the object from s3
* ex:
``` javascript
var params = {
Bucket: 's3-bucket-name',
Key: 'object-filename'
}
s3.deleteObject(params)
```
* don't forget to remove the resource from the DB
Binary file added data/cubone.jpg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
36 changes: 36 additions & 0 deletions lib/basic-auth-middleware.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
'use strict';

const createError = require('http-errors');
const debug = require('debug')('pokegram: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'));
}

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

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

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

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

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

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

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

console.error('message:', 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);
next();
}
13 changes: 13 additions & 0 deletions 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},
description: {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 model/pokemon.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 pokemonSchema = Schema({
name: { type: String, required: true },
year: { type: String, required: true },
userID: { type: Schema.Types.ObjectId, required: true },
pokemonID: { type: Schema.Types.ObjectId, required: true },
audioURI: { type: String, required: true, unique: true },
objectKey: { type: String, required: true, unique: true },
created: { type: Date, default: Date.now }
});

module.exports = mongoose.model('pokemon', pokemonSchema);
74 changes: 74 additions & 0 deletions model/user.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
'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')('pokegram: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, 'invalid 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);
42 changes: 42 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
{
"name": "17-bearer-auth",
"version": "1.0.0",
"description": "![CF](https://camo.githubusercontent.com/70edab54bba80edb7493cad3135e9606781cbb6b/687474703a2f2f692e696d6775722e636f6d2f377635415363382e706e67) 17: Bearer Auth ===",
"main": "server.js",
"directories": {
"test": "test"
},
"dependencies": {
"bcrypt": "^1.0.2",
"bluebird": "^3.5.0",
"body-parser": "^1.17.2",
"cors": "^2.8.4",
"debug": "^2.6.8",
"dotenv": "^4.0.0",
"express": "^4.15.4",
"http-errors": "^1.6.2",
"jsonwebtoken": "^7.4.2",
"mongoose": "^4.11.6",
"morgan": "^1.8.2",
},
"devDependencies": {
"chai": "^4.1.1",
"mocha": "^3.5.0",
"superagent": "^3.5.2"
},
"scripts": {
"test": "DEBUG='pokemon*' mocha",
"start": "DEBUG='pokemon*' node server.js"
},
"repository": {
"type": "git",
"url": "git+https://github.com/Loaye/17-bearer-auth.git"
},
"keywords": [],
"author": "",
"license": "ISC",
"bugs": {
"url": "https://github.com/Loaye/17-bearer-auth/issues"
},
"homepage": "https://github.com/Loaye/17-bearer-auth#readme"
}
34 changes: 34 additions & 0 deletions route/auth-router.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
'use strict';

const jsonParser = require('body-parser').json();
const debug = require('debug')('pokegram:auth-router');
const Router = require('express').Router;
const basicAuth = require('../lib/basic-auth-middleware.js');
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(next);
});

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