├── .gitignore ├── .travis.yml ├── Dockerfile ├── LICENSE ├── README.md ├── package.json └── src ├── api ├── auth.js ├── index.js ├── register.js └── user.js ├── config.js ├── db.js ├── index.js ├── lib ├── res-message.js └── util.js ├── middleware ├── passport.js └── require-auth.js └── models └── user.js /.gitignore: -------------------------------------------------------------------------------- 1 | /dist 2 | /logs 3 | /npm-debug.log 4 | /node_modules 5 | .DS_Store 6 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: node_js 2 | node_js: 3 | - "6" 4 | script: 5 | - 'npm run test:coverage' 6 | after_script: 7 | - 'cat ./coverage/lcov.info | ./node_modules/.bin/coveralls' -------------------------------------------------------------------------------- /Dockerfile: -------------------------------------------------------------------------------- 1 | FROM alpine:3.4 2 | 3 | # File Author / Maintainer 4 | LABEL authors="Emerson Laurentino " 5 | 6 | # Update & install required packages 7 | RUN apk add --update nodejs bash git 8 | 9 | # Install app dependencies 10 | COPY package.json /www/package.json 11 | RUN cd /www; npm install 12 | 13 | # Copy app source 14 | COPY . /www 15 | 16 | # Set work directory to /www 17 | WORKDIR /www 18 | 19 | # set your port 20 | ENV PORT 8080 21 | 22 | # expose the port to outside world 23 | EXPOSE 8080 24 | 25 | # start command as per package.json 26 | CMD ["npm", "start"] 27 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2017 Emerson Laurentino 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | A basic project for an ES6 RESTful Express server with JWT, Passport and Mongoose. 2 | ================================== 3 | [![Build Status](https://travis-ci.org/emersonlaurentino/express-es6-jwt-mongoose.svg?branch=master)](https://travis-ci.org/emersonlaurentino/express-es6-jwt-mongoose) 4 | 5 | Get started 6 | --------------- 7 | ```sh 8 | # clone it 9 | git clone git@github.com:emersonlaurentino/express-es6-jwt-mongoose.git 10 | cd express-es6-jwt-mongoose 11 | 12 | # Make it your own 13 | rm -rf .git && git init 14 | 15 | # install dependences 16 | npm i 17 | 18 | # Start development live-reload server 19 | PORT=4000 npm run dev 20 | 21 | # Start production server: 22 | PORT=4000 npm start 23 | ``` 24 | 25 | Install mongo 26 | --------------- 27 | ```sh 28 | docker run --name mongo-example -v /docker/mongo-example/datadir:/data/db -p 27017:27017 -d mongo --auth 29 | ``` 30 | 31 | Create user on mongo 32 | --------------- 33 | ```sh 34 | # shell of mongo on docker 35 | docker exec -it mongo-example mongo admin 36 | 37 | # create superuser 38 | db.createUser({ user: 'admin', pwd: '4dm1nP4ssw0rd', roles: [{ role: 'userAdminAnyDatabase', db: 'admin' }] }); 39 | 40 | # auth connect 41 | db.auth('admin', '4dm1nP4ssw0rd') 42 | 43 | # connect on new database 44 | use example 45 | 46 | # create user with role of read and write 47 | db.createUser({ user: 'userexample', pwd: 'us3rP4ssw0rd', roles: [{ role: 'readWrite', db: 'example' }] }); 48 | ``` 49 | 50 | Docker Support 51 | --------------- 52 | ```sh 53 | 54 | # Build your docker 55 | docker build -t es6/api-service . 56 | # ^ ^ ^ 57 | # tag tag name Dockerfile location 58 | 59 | # run your docker 60 | docker run -p 4000:4000 es6/api-service 61 | # ^ ^ 62 | # bind the port container tag 63 | # to your host 64 | # machine port 65 | ``` 66 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "express-es6-jwt-mongoose", 3 | "version": "0.0.1", 4 | "description": "A basic project for an ES6 RESTful Express server with JWT, Passport and Mongoose", 5 | "main": "dist", 6 | "scripts": { 7 | "test": "jest", 8 | "test:watch": "npm test -- --watch", 9 | "test:coverage": "jest --coverage", 10 | "dev": "nodemon -w src --exec \"babel-node src --presets es2015,stage-0\"", 11 | "build": "babel src -s -D -d dist --presets es2015,stage-0", 12 | "start": "node dist", 13 | "prestart": "npm run -s build", 14 | "lint": "eslint src" 15 | }, 16 | "eslintConfig": { 17 | "extends": "eslint:recommended", 18 | "parserOptions": { 19 | "ecmaVersion": 7, 20 | "sourceType": "module" 21 | }, 22 | "env": { 23 | "node": true 24 | }, 25 | "rules": { 26 | "no-console": 0, 27 | "no-unused-vars": 1 28 | } 29 | }, 30 | "repository": { 31 | "type": "git", 32 | "url": "git+https://github.com/emersonlaurentino/express-es6-jwt-mongoose.git" 33 | }, 34 | "author": "Emerson Laurentino ", 35 | "license": "MIT", 36 | "dependencies": { 37 | "bcrypt": "^1.0.2", 38 | "bluebird": "^3.5.0", 39 | "body-parser": "^1.13.3", 40 | "compression": "^1.5.2", 41 | "cors": "^2.7.1", 42 | "express": "^4.13.3", 43 | "jsonwebtoken": "^7.4.3", 44 | "jwt-simple": "^0.5.1", 45 | "lodash": "^4.17.4", 46 | "mongoose": "^4.11.7", 47 | "morgan": "^1.8.0", 48 | "passport": "^0.4.0", 49 | "passport-jwt": "^3.0.0", 50 | "resource-router-middleware": "^0.6.0" 51 | }, 52 | "devDependencies": { 53 | "babel-cli": "^6.9.0", 54 | "babel-core": "^6.9.0", 55 | "babel-preset-es2015": "^6.9.0", 56 | "babel-preset-stage-0": "^6.5.0", 57 | "coveralls": "^2.13.1", 58 | "eslint": "^3.1.1", 59 | "jest": "^21.0.2", 60 | "nodemon": "^1.9.2", 61 | "winston": "^2.3.1" 62 | }, 63 | "bugs": { 64 | "url": "https://github.com/emersonlaurentino/express-es6-jwt-mongoose/issues" 65 | }, 66 | "homepage": "https://github.com/emersonlaurentino/express-es6-jwt-mongoose#readme" 67 | } 68 | -------------------------------------------------------------------------------- /src/api/auth.js: -------------------------------------------------------------------------------- 1 | import { isEmpty } from 'lodash/fp'; 2 | import resource from 'resource-router-middleware'; 3 | import jwt from 'jsonwebtoken'; 4 | import UserModel from '../models/user'; 5 | import config from '../config'; 6 | 7 | const authApi = resource({ 8 | create({ body: { email, password } }, res) { 9 | UserModel.findOne({ email }).select("+password") 10 | .then(result => { 11 | if (isEmpty(result)) { 12 | return res.status(401).send({ 13 | success: false, 14 | message: 'Authentication failed. User not found.' 15 | }) 16 | } 17 | 18 | result.comparePassword(password, (err, isMatch) => { 19 | if (isMatch && !err) { 20 | var token = jwt.sign({ sub: result._id }, config.jwtSecret, { 21 | expiresIn: "2 days" 22 | }); 23 | 24 | return res.json({ 25 | success: true, 26 | message: 'Authentication successfull', 27 | token 28 | }); 29 | } 30 | 31 | res.status(401).send({ 32 | success: false, 33 | message: 'Authentication failed. Passwords did not match.' 34 | }); 35 | }); 36 | }) 37 | .catch(err => res.send(err.toString())) 38 | }, 39 | }); 40 | 41 | export default authApi; 42 | -------------------------------------------------------------------------------- /src/api/index.js: -------------------------------------------------------------------------------- 1 | import { Router } from 'express'; 2 | import { version } from '../../package.json'; 3 | import requireAuth from '../middleware/require-auth'; 4 | import authApi from './auth'; 5 | import userApi from './user'; 6 | import registerApi from './register'; 7 | 8 | const api = Router(); 9 | 10 | api.use('/auth', authApi); 11 | api.use('/user', requireAuth, userApi); 12 | api.use('/register', registerApi); 13 | 14 | api.get('/', (req, res) => { 15 | res.json({ version }); 16 | }); 17 | 18 | export default api; 19 | -------------------------------------------------------------------------------- /src/api/register.js: -------------------------------------------------------------------------------- 1 | import resource from 'resource-router-middleware'; 2 | import { merge, get } from 'lodash/fp'; 3 | import resMessage from '../lib/res-message'; 4 | import UserModel from '../models/user'; 5 | 6 | const addFullNameToBody = body => merge({ 7 | name: { 8 | full: `${get('name.first', body)} ${get('name.last', body)}` 9 | }, 10 | }, body); 11 | 12 | const userApi = resource({ 13 | create({ body }, res) { 14 | let user = new UserModel(addFullNameToBody(body)); 15 | 16 | user.save() 17 | .then(({ _id }) => UserModel.findById(_id).then(result => res.send(result))) 18 | .catch(error => res.status(400).send(resMessage(error.message))) 19 | }, 20 | }); 21 | 22 | export default userApi; 23 | -------------------------------------------------------------------------------- /src/api/user.js: -------------------------------------------------------------------------------- 1 | import resource from 'resource-router-middleware'; 2 | import { merge, get, isEmpty } from 'lodash/fp'; 3 | import resMessage from '../lib/res-message'; 4 | import UserModel from '../models/user'; 5 | 6 | const addFullNameToBody = body => { 7 | if (isEmpty(get('name', body))) { 8 | return body; 9 | } 10 | 11 | return merge({ 12 | name: { 13 | full: `${get('name.first', body)} ${get('name.last', body)}` 14 | }, 15 | }, body); 16 | }; 17 | 18 | const userApi = resource({ 19 | id: 'userId', 20 | 21 | index({ params }, res) { 22 | UserModel.find() 23 | .then(result => res.send(result)) 24 | .catch(error => res.status(400).send(error)) 25 | }, 26 | 27 | read({ params: { userId } }, res) { 28 | UserModel.findById(userId) 29 | .then(result => res.send(result)) 30 | .catch(() => res.status(404).send(resMessage('User not found.'))) 31 | }, 32 | 33 | update({ params: { userId }, body }, res) { 34 | UserModel.findByIdAndUpdate(userId, addFullNameToBody(body)) 35 | .then(() => UserModel.findById(userId).then(result => res.send(result))) 36 | .catch(() => res.status(404).send(resMessage('User not found.'))) 37 | }, 38 | 39 | delete({ params: { userId } }, res) { 40 | UserModel.findByIdAndRemove(userId) 41 | .then(() => res.send(resMessage('User successfully deleted!'))) 42 | .catch(() => res.status(404).send(resMessage('User not found.'))) 43 | } 44 | }); 45 | 46 | export default userApi; 47 | -------------------------------------------------------------------------------- /src/config.js: -------------------------------------------------------------------------------- 1 | export default { 2 | host: 'mongodb://userexample:us3rP4ssw0rd@localhost:27017/example', 3 | jwtSecret: 'MyS3cr3tK3Y', 4 | port: 4000, 5 | bodyLimit: '100kb', 6 | corsHeaders: ['Link'] 7 | }; 8 | -------------------------------------------------------------------------------- /src/db.js: -------------------------------------------------------------------------------- 1 | import mongoose from 'mongoose'; 2 | import Promise from 'bluebird'; 3 | import { logger } from './lib/util'; 4 | import config from './config'; 5 | 6 | const env = process.env.NODE_ENV || 'development'; 7 | 8 | const options = { 9 | useMongoClient: true 10 | }; 11 | 12 | export default callback => { 13 | mongoose.Promise = Promise; 14 | 15 | if (env === 'development') mongoose.set('debug', true); 16 | 17 | mongoose.connect(config.host, options) 18 | .then(() => { 19 | logger.info('Mongo connected!'); 20 | 21 | callback(mongoose); 22 | }) 23 | .catch(err => logger.error(err.toString())); 24 | } 25 | -------------------------------------------------------------------------------- /src/index.js: -------------------------------------------------------------------------------- 1 | import bodyParser from 'body-parser'; 2 | import cors from 'cors'; 3 | import express from 'express'; 4 | import http from 'http'; 5 | import morgan from 'morgan'; 6 | import passport from 'passport'; 7 | import { logger } from './lib/util'; 8 | import api from './api'; 9 | import config from './config'; 10 | import initializeDb from './db'; 11 | import passportMiddleware from './middleware/passport'; 12 | 13 | const app = express(); 14 | 15 | app.server = http.createServer(app); 16 | 17 | app.use(morgan('dev')); 18 | app.use(cors({ exposedHeaders: config.corsHeaders })); 19 | app.use(bodyParser.json({ limit : config.bodyLimit })); 20 | 21 | initializeDb(() => { 22 | app.use(passport.initialize()); 23 | 24 | passportMiddleware(passport); 25 | 26 | app.use('/api', api); 27 | app.server.listen(process.env.PORT || config.port, () => { 28 | logger.info(`Started on port ${app.server.address().port}`); 29 | }); 30 | }); 31 | 32 | export default app; 33 | -------------------------------------------------------------------------------- /src/lib/res-message.js: -------------------------------------------------------------------------------- 1 | const resMessage = message => ({ 2 | message: message, 3 | }); 4 | 5 | export default resMessage; 6 | -------------------------------------------------------------------------------- /src/lib/util.js: -------------------------------------------------------------------------------- 1 | import winston from 'winston'; 2 | 3 | const { NODE_ENV, LOG_LEVEL } = process.env; 4 | const DEV = NODE_ENV !== 'production'; 5 | const TEST = NODE_ENV === 'test'; 6 | const level = LOG_LEVEL || (TEST ? 'test' : 'info'); 7 | 8 | export const logger = new (winston.Logger)({ 9 | transports: [ 10 | new (winston.transports.Console)({ 11 | level, 12 | colorize: DEV 13 | }) 14 | ] 15 | }); 16 | -------------------------------------------------------------------------------- /src/middleware/passport.js: -------------------------------------------------------------------------------- 1 | import { Strategy, ExtractJwt } from 'passport-jwt'; 2 | import User from '../models/user'; 3 | import config from '../config'; 4 | 5 | const opts = { 6 | jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(), 7 | secretOrKey: config.jwtSecret 8 | }; 9 | 10 | export default passport => passport.use(new Strategy(opts, (payload, done) => { 11 | User.findById(payload.sub) 12 | .then(user => { 13 | if (user) { 14 | return done(null, user); 15 | } 16 | 17 | return done(new Error("User not found."), null); 18 | }) 19 | .catch(err => done(err, false)) 20 | })); 21 | -------------------------------------------------------------------------------- /src/middleware/require-auth.js: -------------------------------------------------------------------------------- 1 | import passport from 'passport'; 2 | 3 | export default passport.authenticate('jwt', { session: false }); 4 | 5 | -------------------------------------------------------------------------------- /src/models/user.js: -------------------------------------------------------------------------------- 1 | import mongoose from 'mongoose'; 2 | import bcrypt from 'bcrypt'; 3 | 4 | const userSchema = new mongoose.Schema({ 5 | name: { 6 | first: { type: String, required: true }, 7 | last: { type: String, required: true }, 8 | full: { type: String, required: true } 9 | }, 10 | email: { type: String, required: true, unique: true, lowercase: true }, 11 | password: { type: String, required: true, select: false }, 12 | created_at: { type: Date, default: new Date() }, 13 | }); 14 | 15 | userSchema.pre('save', function(next) { 16 | var user = this; 17 | if (this.isModified('password') || this.isNew) { 18 | bcrypt.genSalt(10, function(err, salt) { 19 | if (err) { 20 | return next(err); 21 | } 22 | bcrypt.hash(user.password, salt, function(err, hash) { 23 | if (err) { 24 | return next(err); 25 | } 26 | user.password = hash; 27 | next(); 28 | }); 29 | }); 30 | } else { 31 | return next(); 32 | } 33 | }); 34 | 35 | userSchema.methods.comparePassword = function(pw, cb) { 36 | bcrypt.compare(pw, this.password, function(err, isMatch) { 37 | if (err) { 38 | return cb(err); 39 | } 40 | 41 | return cb(null, isMatch); 42 | }); 43 | }; 44 | 45 | const userModel = mongoose.model('User', userSchema); 46 | 47 | export default userModel; --------------------------------------------------------------------------------