Skip to content

User routes #12

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 12 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
3 changes: 3 additions & 0 deletions lab-davidw/.eslintignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
**/node_modules/*
**/vendor/*
**/*.min.js
25 changes: 25 additions & 0 deletions lab-davidw/.eslintrc
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
{
"rules": {
"quotes": ["error", "single", { "allowTemplateLiterals": true }],
"comma-dangle": ["error", "always-multiline"],
"no-console": "off",
"indent": [ "error", 2 ],
"semi": ["error", "always"]
},
"env": {
"es6": true,
"node": true,
"mocha": true,
"jasmine": true
},
"globals": {
"__API_URI__": false,
"__DEBUG__": false
},
"ecmaFeatures": {
"modules": true,
"experimentalObjectRestSpread": true,
"impliedStrict": true
},
"extends": "eslint:recommended"
}
101 changes: 101 additions & 0 deletions lab-davidw/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,101 @@
# ignore db directorys
db

# Created by https://www.gitignore.io/api/linux,node,osx,vim

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


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

# Runtime data
pids
*.pid
*.seed

# 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 REPL history
.node_repl_history


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


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

# environment
.env
138 changes: 138 additions & 0 deletions lab-davidw/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,138 @@
# lab 17 bearer auth
----
## Goal
Add a gallery model, with a POST, PUT, GET, and DELETE routes to interact with it, and some tests.


## Setup

- **make sure you have Node.js and MongoDB installed.**
```$ apt-get node```
```$ npm install mongoose```

- **install the app**
```$ npm install ```

- **start the server**
```$ npm run start```

- **start the database**
```$ mongod --dbpath ./db```
- **start the mongo interface**
```$ mongo```
```$ use cfgram-dev```


## Usage
###### User management
You can sign up and sign in with the following end points:
note: this is based on using 'HTTPie'
- Sign up:
- http POST
- http POST :3000/api/signup username=<UniqueUsername> password=<password> email=<UniqueEmail>
- Sign in:
- http GET
- http :3000/api/signin -a<username>:<password>

###### Gallery management
You can sign up and sign in with the following end points:
note: this is based on using 'HTTPie'
- Create Gallery:
- http POST
- http POST :3000/api/gallery username=<UniqueUsername> password=<password> email=<UniqueEmail>
- Get Gallery array:
- http GET
- http GET :3000/api/galllery/<galleryId> 'Authorization:Bearer <your token string here>'
- Update Gallery:
- http PUT :3000/api/gallery/<galleryId> 'Authorization:Bearer <your token string here>'

- Delete Gallery:
-http DELETE :3000/api/gallery/<galleryId> 'Authorization:Bearer <your token string here>'

- Test!
- npm run test
(mocha)

## Expected

##### EXAMPLE RESPONSES:

###### User Management:
- POST:
```
HTTP/1.1 200 OK
Access-Control-Allow-Origin: *
Connection: keep-alive
Content-Length: 207
Content-Type: application/json; charset=utf-8
Date: <date> GMT
ETag: W/"<etag>"
X-Powered-By: Express

"<you will receive a unique token string here>"
```

- GET:
```
HTTP/1.1 200 OK
Access-Control-Allow-Origin: *
Connection: keep-alive
Content-Length: 207
Content-Type: application/json; charset=utf-8
Date: <date> GMT
ETag: W/"<etag>"
X-Powered-By: Express

"<you will receive a unique token string here>"
```

###### Gallery Management:
- POST:
```
HTTP/1.1 200 OK
Access-Control-Allow-Origin: *
Connection: keep-alive
Content-Length: 207
Content-Type: application/json; charset=utf-8
Date: <date> GMT
ETag: W/"<etag>"
X-Powered-By: Express
{
"__v": <num>,
"name": "<name string>",
"desc": "<desc string>",
"userId": "<userId>",
"_id": "<galleryId",
"created": "<timestamp>"
}
```

- GET:
```
HTTP/1.1 200 OK
Access-Control-Allow-Origin: *
Connection: keep-alive
Content-Length: 207
Content-Type: application/json; charset=utf-8
Date: <date> GMT
ETag: W/"<etag>"
X-Powered-By: Express

[<you will receive an array of objects contained in the Gallery>]
```

- DELETE
```
HTTP/1.1 204 OK
Access-Control-Allow-Origin: *
Connection: keep-alive
Content-Length: 207
Content-Type: application/json; charset=utf-8
Date: <date> GMT
ETag: W/"<etag>"
X-Powered-By: Express
```

### Attributions
I worked closely with Abigail White, Ali Grampa, David Teddy and, Steven Johnson.
JR Iriarte really helped me get through making my POST route work.
36 changes: 36 additions & 0 deletions lab-davidw/controllers/auth-controller.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
'use strict';

const Promise = require('bluebird');
const createError = require('http-errors');
const User = require('../models/user');
const debug = require('debug')('cfgram:gallery-controller');

module.exports = exports = {};

exports.createUser = function(req) {
debug('#createUser');
if(!req) return Promise.reject(createError(400, 'Bad request'));

let tempPassword = req.body.password;
req.body.password = null;
delete req.body.password;

let newUser = User(req.body);

return newUser.generatePasswordHash(tempPassword)
.then(user => user.save())
.then(user => user.generateToken())
.then(token => token)
.catch(err => createError(401, err.message));
};

exports.fetchUser = function(reqAuth) {
debug('#fetchUser');
if(!reqAuth) return Promise.reject(createError(404, 'Not found'));

return User.findOne({username: reqAuth.username})
.then(user => user.comparePasswordHash(reqAuth.password))
.then(user => user.generateToken())
.then(data => data)
.catch(err => createError(401, err.message));
};
53 changes: 53 additions & 0 deletions lab-davidw/controllers/gallery-controller.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
'use strict';

const Promise = require('bluebird');
const createError = require('http-errors');
const Gallery = require('../models/gallery');
const debug = require('debug')('cfgram:gallery-controller');

module.exports = exports = {};

exports.createGallery = function(req) {
debug('#createGallery');
if(!req) return Promise.reject(createError(400, 'Bad request'));

req.body.userId = req.user._id;
return new Gallery(req.body).save()
.then(gallery => gallery)
.catch(err => createError(401, err.message));
};

exports.fetchGallery = function(req) {
debug('#fetchGallery');
if(!req.user) return Promise.reject(createError(400, 'Bad request'));

return Gallery.find(req.user, { _id : req.params.id})
.then(gallery => gallery)
.catch(err => createError(404, err.message));

};

exports.deleteGallery = function(req) {
debug('deleteGallery');
if(!req.user._id) return Promise.reject(createError(400, 'bad request'));
if(!req.params.id) return Promise.reject(createError(400, 'bad request'));

return Gallery.findOneAndRemove({ _id: req.params.id, userId: req.user._id.toString()})
.then(data => {
if (data === null) createError(404, 'Gallery not found');
})
.catch(err => createError(err.status, err.message));
};

exports.updateGallery = function(req) {
debug('#updateGallery');
console.log({ _id: req.params.id, userId: req.user._id.toString()});
if(!req.params.id) return Promise.reject(createError(400, 'Id required'));

return Gallery.findOneAndUpdate({ _id: req.params.id, userId: req.user._id}, req.body, {new: true})
.then(data => {
if (data === null) return createError(404, 'Cannot find that Gallery to update');
return data;
})
.catch(err => createError(err.status, err.message));
};
22 changes: 22 additions & 0 deletions lab-davidw/lib/basic-auth-middleware.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
'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');

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

let base64Str = authHeaders.split('Basic ')[1];
if(!base64Str) return next(createError(401, 'Username and Password required'));

let [username, password] = new Buffer(base64Str, 'base64').toString().split(':');
req.auth = {username, password};

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

next();
};
Loading