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
4 changes: 4 additions & 0 deletions google-oauth-backend-starter-code/.babelrc
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
{
"presets": ["es2015"],
"plugins": ["transform-object-rest-spread"]
}
149 changes: 149 additions & 0 deletions google-oauth-backend-starter-code/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,149 @@
*.env
.*.env
db

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

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

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


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

### Redis ###
# Ignore redis binary dump (dump.rdb) files

*.rdb

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

### Windows ###
# Windows thumbnail cache files
Thumbs.db
ehthumbs.db
ehthumbs_vista.db

# Folder config file
Desktop.ini

# Recycle Bin used on file shares
$RECYCLE.BIN/

# Windows Installer files
*.cab
*.msi
*.msm
*.msp

# Windows shortcuts
*.lnk

# End of https://www.gitignore.io/api/osx,vim,node,redis,linux,windows
17 changes: 17 additions & 0 deletions google-oauth-backend-starter-code/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
# slugchat

## configuration
configure a .env file to include the following

``` bash
PORT=3000
NODE_ENV='dev'
SECRET='shark in the dark'
API_URL='http://localhost:3000'
CLIENT_URL='http://localhost:8080'
CORS_ORIGINS='http://localhost:8080'
MONGODB_URI='mongodb://localhost/slugchat-dev'
GOOGLE_CLIENT_SECRET='<put google client secret here>'
GOOGLE_CLIENT_ID='<put your google cleint id here>'
```

8 changes: 8 additions & 0 deletions google-oauth-backend-starter-code/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
'use strict'
// load env
require('dotenv').config()
// assert env
require('./src/lib/assert-env.js')
// start server
require('babel-register')
require('./src/main.js')
38 changes: 38 additions & 0 deletions google-oauth-backend-starter-code/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
{
"name": "slugchat",
"version": "1.0.0",
"main": "index.js",
"license": "MIT",
"scripts": {
"lint": "eslint .",
"start": "node index.js",
"watch": "nodemon index.js",
"test": "jest --runInBand",
"test-watch": "jest --watch --runInBand",
"mongo-on": "mkdir -p ./db && mongod --dbpath ./db",
"mongo-off": "killall mongod"
},
"dependencies": {
"babel-plugin-transform-object-rest-spread": "^6.23.0",
"babel-preset-es2015": "^6.24.1",
"babel-register": "^6.24.1",
"bcrypt": "^1.0.2",
"body-parser": "^1.17.2",
"cors": "^2.8.4",
"dotenv": "^4.0.0",
"express": "^4.15.3",
"faker": "^4.1.0",
"http-errors": "^1.6.2",
"jsonwebtoken": "^7.4.2",
"lodash": "^4.17.4",
"mongoose": "^4.11.5",
"morgan": "^1.8.2",
"socket.io": "^2.0.3",
"superagent": "^3.5.2"
},
"devDependencies": {
"faker": "^4.1.0",
"jest": "^20.0.4",
"nodemon": "^1.11.0"
}
}
23 changes: 23 additions & 0 deletions google-oauth-backend-starter-code/src/lib/assert-env.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
let required = [
'PORT',
'SECRET',
'API_URL',
'NODE_ENV',
'CLIENT_URL',
'MONGODB_URI',
'CORS_ORIGINS',
'GOOGLE_CLIENT_ID',
'GOOGLE_CLIENT_SECRET',
]

try {
required.forEach(key => {
if(!process.env[key])
throw new Error(`ENVIRONMNET ERROR: slugchat requires process.env.${key} to be set`)
})
} catch (e) {
console.error(e.message)
process.exit(1)
}


35 changes: 35 additions & 0 deletions google-oauth-backend-starter-code/src/lib/mongo.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
'use strict'

// DEPENDENCIES
const mongoose = require('mongoose')
mongoose.Promise = Promise

// STATE
const state = {
isOn: false,
config: {
useMongoClient: true,
promiseLibrary: Promise,
},
}

// INTERFACE
export const start = () => {
if(state.isOn)
return Promise.reject(new Error('USER ERROR: db is connected'))
return mongoose.connect(process.env.MONGODB_URI, state.config)
.then(() => {
console.log('__MONGO_CONNECTED__', process.env.MONGODB_URI)
state.isOn = true
})
}

export const stop = () => {
if(!state.isOn)
return Promise.reject(new Error('USER ERROR: db is disconnected'))
return mongoose.disconnect()
.then(() => {
state.isOn = false
console.log('__MONGO_DISCONNECTED__')
})
}
9 changes: 9 additions & 0 deletions google-oauth-backend-starter-code/src/lib/promisify.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
export default (fn) => (...args) => {
return new Promise((resolve, reject) => {
fn(...args, (err, data) => {
if(err)
return reject(err)
resolve(data)
})
})
}
67 changes: 67 additions & 0 deletions google-oauth-backend-starter-code/src/lib/server.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
'use strict'

// DEPENDENCIES
import cors from 'cors'
import morgan from 'morgan'
import express from 'express'
import * as mongo from './mongo.js'

import authRouter from '../router/auth.js'
import fourOhFour from '../middleware/four-oh-four.js'
import errorHandler from '../middleware/error-middleware.js'

// STATE
const app = express()

// global middleware
app.use(morgan('dev'))
app.use(cors({
origin: process.env.CORS_ORIGINS.split(' '),
credentials: true,
}))

// routers
app.use(authRouter)

// handle errors
app.use(fourOhFour)
app.use(errorHandler)

const state = {
isOn: false,
http: null,
}

// INTERFACE
export const start = () => {
return new Promise((resolve, reject) => {
if (state.isOn)
return reject(new Error('USAGE ERROR: the state is on'))
state.isOn = true
mongo.start()
.then(() => {
state.http = app.listen(process.env.PORT, () => {
console.log('__SERVER_UP__', process.env.PORT)
resolve()
})
})
.catch(reject)
})
}

export const stop = () => {
return new Promise((resolve, reject) => {
if(!state.isOn)
return reject(new Error('USAGE ERROR: the state is off'))
return mongo.stop()
.then(() => {
state.http.close(() => {
console.log('__SERVER_DOWN__')
state.isOn = false
state.http = null
resolve()
})
})
.catch(reject)
})
}
3 changes: 3 additions & 0 deletions google-oauth-backend-starter-code/src/main.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
import * as server from './lib/server.js'

server.start()
29 changes: 29 additions & 0 deletions google-oauth-backend-starter-code/src/middleware/basic-auth.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
import User from '../model/user.js'
import createError from 'http-errors'

export default (req, res, next) => {
let {authorization} = req.headers
if(!authorization)
return next(createError(400, 'AUTH ERROR: no authorization header'))

let encoded = authorization.split('Basic ')[1]
if(!encoded)
return next(createError(400, 'AUTH ERROR: not basic auth'))

let decoded = new Buffer(encoded, 'base64').toString()
let [username, password] = decoded.split(':')
if(!username || !password)
return next(createError(401, 'AUTH ERROR: username or password missing'))

User.findOne({username})
.then(user => {
if(!user)
throw createError(401, 'AUTH ERROR: user not found')
return user.passwordCompare(password)
})
.then(user => {
req.user = user
next()
})
.catch(next)
}
Loading