Skip to content
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

Adding FirstLegoLeague's eslint standard #9

Merged
merged 2 commits into from
May 22, 2019
Merged
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
80 changes: 40 additions & 40 deletions .eslintrc.yml
Original file line number Diff line number Diff line change
@@ -1,40 +1,40 @@
extends: standard
parserOptions:
sourceType: script
rules:
arrow-parens:
- warn
- as-needed
- requireForBlockBody: false
no-shadow: warn
no-var: warn
object-curly-spacing: [ warn, always ]
prefer-arrow-callback: warn
prefer-const: warn
strict: [ warn, global ]
import/newline-after-import: warn
import/no-absolute-path: warn
import/no-dynamic-require: warn
import/no-extraneous-dependencies: warn
import/no-mutable-exports: warn
import/order:
- warn
- groups:
- [ builtin, external ]
- [ sibling, index ]
- parent
newlines-between: always-and-inside-groups
node/exports-style:
- warn
- exports
node/no-unsupported-features: warn
node/shebang: warn
promise/catch-or-return: warn
promise/no-callback-in-promise: warn
promise/no-native: warn
promise/no-return-wrap: warn
extends: "@first-lego-league"

parserOptions:
sourceType: script

#rules:
# arrow-parens:
# - warn
# - as-needed
# - requireForBlockBody: false
# no-shadow: warn
# no-var: warn
# object-curly-spacing: [ warn, always ]
# prefer-arrow-callback: warn
# prefer-const: warn
# strict: [ warn, global ]
#
# import/newline-after-import: warn
# import/no-absolute-path: warn
# import/no-dynamic-require: warn
# import/no-extraneous-dependencies: warn
# import/no-mutable-exports: warn
# import/order:
# - warn
# - groups:
# - [ builtin, external ]
# - [ sibling, index ]
# - parent
# newlines-between: always-and-inside-groups
#
# node/exports-style:
# - warn
# - exports
# node/no-unsupported-features: warn
# node/shebang: warn
#
# promise/catch-or-return: warn
# promise/no-callback-in-promise: warn
# promise/no-native: warn
# promise/no-return-wrap: warn
18 changes: 11 additions & 7 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,9 @@
"description": "Identity Provider using jwt-redirection",
"main": "server.js",
"scripts": {
"start": "set DEV=true&& start mhub-server&& node server.js"
"start": "set DEV=true&& start mhub-server&& node server.js",
"lint": "eslint \"*.js\"",
"lint:fix": "eslint --fix \"*.js\""
},
"repository": "git+https://github.com/FirstLegoLeagueIL/IdP.git",
"author": "Idan Stark <[email protected]>",
Expand All @@ -28,11 +30,13 @@
"template-file": "^3.0.1"
},
"devDependencies": {
"eslint": "^4.19.1",
"eslint-config-standard": "^11.0.0",
"eslint-plugin-import": "^2.10.0",
"eslint-plugin-node": "^6.0.1",
"eslint-plugin-promise": "^3.7.0",
"eslint-plugin-standard": "^3.0.1"
"@first-lego-league/eslint-config": "^1.0.0",
"eslint": "^5.16.0",
"eslint-config-standard": "^12.0.0",
"eslint-plugin-chai-friendly": "^0.4.1",
"eslint-plugin-import": "^2.17.2",
"eslint-plugin-node": "^9.0.1",
"eslint-plugin-promise": "^4.1.1",
"eslint-plugin-standard": "^4.0.0"
}
}
229 changes: 112 additions & 117 deletions server.js
Original file line number Diff line number Diff line change
@@ -1,117 +1,112 @@
'use strict'
/* eslint node/no-deprecated-api: 0 */
/* eslint node/no-unsupported-features: 0 */

const DEFAULT_PORT = 9000
const DEFAULT_SECRET = '321LEGO'
const TOKEN_EXPIRATION = 24 * 60 * 60 * 1000 // day
const TOKEN_KEY = 'auth-token' // Following the FIRST LEGO League System module standard v1.0

const express = require('express')
const path = require('path')
const cookieParser = require('cookie-parser')
const bodyParser = require('body-parser')
const templates = require('template-file')
const jwt = require('jsonwebtoken')

const { correlationMiddleware } = require('@first-lego-league/ms-correlation')
const { Logger, loggerMiddleware } = require('@first-lego-league/ms-logger')

const Users = require('./users')

const port = process.env.PORT || DEFAULT_PORT
const secret = process.env.SECRET || DEFAULT_SECRET
const tokenExpiration = TOKEN_EXPIRATION // TODO token expiration

const app = express()
const logger = new Logger()

app.use(correlationMiddleware)
app.use(loggerMiddleware)

app.use(cookieParser())
app.use(bodyParser.urlencoded({ extended: true }))
app.use(bodyParser.json())
app.use('/webfonts', express.static(path.resolve(__dirname, 'client/node_modules/@first-lego-league/user-interface/current/assets/fonts')))
app.use(express.static(path.resolve(__dirname, 'client')))

app.use((req, res, next) => {
req.callbackUrl = req.query['callbackUrl'] || req.params['callbackUrl'] || req.body['callbackUrl']

res.redirectToCallbackUrl = function (token) {
if (!req.callbackUrl.match(/^http(s)?:\/\//)) {
req.callbackUrl = `http://${req.callbackUrl}`
}
req.logger.debug(`Redirecting to callback URL ${req.callbackUrl} with token ${token}`)
res.redirect(`${req.callbackUrl}?token=${token}`)
}

res.renderLoginPage = function (options) {
templates.renderTemplateFile(path.resolve(__dirname, 'login.html'), options)
.then(content => {
req.logger.debug(`Rending login page with options ${Object.entries(options).filter(([key, value]) => value).map(([key, value]) => `${key}:${value}`).join(',')}`)
res.send(content)
})
.catch(err => {
req.logger.error(`Error while rendering login page: ${err}`)
res.send(err)
})
}

if (req.callbackUrl || req.path === '/login') {
next()
} else {
res.redirect('/login?error=No callback url specified')
}
})

app.post('/login', (req, res) => {
Users.get(req.body['username'], req)
.then(user => Users.authenticate(user, req.body['password']))
.then(user => {
const token = jwt.sign({ username: user.username }, secret)
res.cookie(TOKEN_KEY, token, { maxAge: tokenExpiration })
res.redirectToCallbackUrl(token)
})
.catch(error => res.redirect(`/login?error=${error}&callbackUrl=${req.callbackUrl}`))
})

app.get('/login', (req, res) => {
const existingAuthToken = req.get(TOKEN_KEY) || req.cookies[TOKEN_KEY]
if (existingAuthToken) {
try {
jwt.verify(existingAuthToken, secret)
res.redirectToCallbackUrl(existingAuthToken)
return
} catch (err) {
logger.warn(`Someone tried bypassing the system with a wrongly encoded web token: ${existingAuthToken}`)
res.renderLoginPage({ 'callbackUrl': req.callbackUrl, error: req.query.error })
}
} else {
res.renderLoginPage({ 'callbackUrl': req.callbackUrl, error: req.query.error })
}
})

app.get('/logout', (req, res) => {
res.clearCookie(TOKEN_KEY)
res.redirect(`/login?callbackUrl=${req.callbackUrl}`)
})

app.listen(port, () => {
logger.info(`Identity provider listening on port ${port}`)
})

process.on('SIGINT', () => {
logger.info('Process received SIGINT: shutting down')
process.exit(130)
})

process.on('uncaughtException', err => {
logger.fatal(err.message)
process.exit(1)
})

process.on('unhandledRejection', err => {
logger.fatal(err.message)
process.exit(1)
})
const DEFAULT_PORT = 9000
const DEFAULT_SECRET = '321LEGO'
const TOKEN_EXPIRATION = 24 * 60 * 60 * 1000 // day
const TOKEN_KEY = 'auth-token' // Following the FIRST LEGO League System module standard v1.0

const express = require('express')
const path = require('path')
const cookieParser = require('cookie-parser')
const bodyParser = require('body-parser')
const templates = require('template-file')
const jwt = require('jsonwebtoken')

const { correlationMiddleware } = require('@first-lego-league/ms-correlation')
const { Logger, loggerMiddleware } = require('@first-lego-league/ms-logger')

const Users = require('./users')

const port = process.env.PORT || DEFAULT_PORT
const secret = process.env.SECRET || DEFAULT_SECRET
const tokenExpiration = TOKEN_EXPIRATION // TODO token expiration

const app = express()
const logger = new Logger()

app.use(correlationMiddleware)
app.use(loggerMiddleware)

app.use(cookieParser())
app.use(bodyParser.urlencoded({ extended: true }))
app.use(bodyParser.json())
app.use('/webfonts', express.static(path.resolve(__dirname, 'client/node_modules/@first-lego-league/user-interface/current/assets/fonts')))
app.use(express.static(path.resolve(__dirname, 'client')))

app.use((req, res, next) => {
req.callbackUrl = req.query['callbackUrl'] || req.params['callbackUrl'] || req.body['callbackUrl']

res.redirectToCallbackUrl = function (token) {
if (!req.callbackUrl.match(/^http(s)?:\/\//)) {
req.callbackUrl = `http://${req.callbackUrl}`
}
req.logger.debug(`Redirecting to callback URL ${req.callbackUrl} with token ${token}`)
res.redirect(`${req.callbackUrl}?token=${token}`)
}

res.renderLoginPage = function (options) {
templates.renderTemplateFile(path.resolve(__dirname, 'login.html'), options)
.then(content => {
req.logger.debug(`Rending login page with options ${Object.entries(options).filter(([key, value]) => value).map(([key, value]) => `${key}:${value}`).join(',')}`)
res.send(content)
})
.catch(err => {
req.logger.error(`Error while rendering login page: ${err}`)
res.send(err)
})
}

if (req.callbackUrl || req.path === '/login') {
next()
} else {
res.redirect('/login?error=No callback url specified')
}
})

app.post('/login', (req, res) => {
Users.get(req.body['username'], req)
.then(user => Users.authenticate(user, req.body['password']))
.then(user => {
const token = jwt.sign({ username: user.username }, secret)
res.cookie(TOKEN_KEY, token, { maxAge: tokenExpiration })
res.redirectToCallbackUrl(token)
})
.catch(error => res.redirect(`/login?error=${error}&callbackUrl=${req.callbackUrl}`))
})

app.get('/login', (req, res) => {
const existingAuthToken = req.get(TOKEN_KEY) || req.cookies[TOKEN_KEY]
if (existingAuthToken) {
try {
jwt.verify(existingAuthToken, secret)
res.redirectToCallbackUrl(existingAuthToken)
} catch (err) {
logger.warn(`Someone tried bypassing the system with a wrongly encoded web token: ${existingAuthToken}`)
res.renderLoginPage({ 'callbackUrl': req.callbackUrl, error: req.query.error })
}
} else {
res.renderLoginPage({ 'callbackUrl': req.callbackUrl, error: req.query.error })
}
})

app.get('/logout', (req, res) => {
res.clearCookie(TOKEN_KEY)
res.redirect(`/login?callbackUrl=${req.callbackUrl}`)
})

app.listen(port, () => {
logger.info(`Identity provider listening on port ${port}`)
})

process.on('SIGINT', () => {
logger.info('Process received SIGINT: shutting down')
process.exit(130)
})

process.on('uncaughtException', err => {
logger.fatal(err.message)
process.exit(1)
})

process.on('unhandledRejection', err => {
logger.fatal(err.message)
process.exit(1)
})
Loading