Skip to content

Commit

Permalink
chore: update the codebase with newer JS features
Browse files Browse the repository at this point in the history
  • Loading branch information
maciek134 committed Dec 30, 2018
1 parent 55d1430 commit d2b8c59
Show file tree
Hide file tree
Showing 18 changed files with 1,503 additions and 1,744 deletions.
47 changes: 22 additions & 25 deletions controllers/auth.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ const oauth = require('../lib/OAuth')
const RSA = require('../lib/RSA')
const Staticman = require('../lib/Staticman')

module.exports = (req, res) => {
module.exports = async (req, res) => {
const staticman = new Staticman(req.params)
staticman.setConfigPath()

Expand All @@ -31,34 +31,31 @@ module.exports = (req, res) => {
)
}

return staticman.getSiteConfig()
.then(requestAccessToken)
.then((accessToken) => {
const git = gitFactory.create(req.params.service, {
oauthToken: accessToken
})
try {
const siteConfig = await staticman.getSiteConfig()
const accessToken = await requestAccessToken(siteConfig)
const git = gitFactory.create(req.params.service, {
oauthToken: accessToken
})

// TODO: Simplify this when v2 support is dropped.
const getUser = req.params.version === '2' && req.params.service === 'github'
? git.api.users.get({}).then(({data}) => data)
: git.getCurrentUser()
// TODO: Simplify this when v2 support is dropped.
const getUser = req.params.version === '2' && req.params.service === 'github'
? git.api.users.get({}).then(({data}) => data)
: git.getCurrentUser()

return getUser
.then((user) => {
res.send({
accessToken: RSA.encrypt(accessToken),
user
})
})
const user = await getUser
res.send({
accessToken: RSA.encrypt(accessToken),
user
})
.catch((err) => {
console.log('ERR:', err)
} catch (err) {
console.log('ERR:', err)

const statusCode = err.statusCode || 401
const statusCode = err.statusCode || 401

res.status(statusCode).send({
statusCode,
message: err.message
})
res.status(statusCode).send({
statusCode,
message: err.message
})
}
}
23 changes: 12 additions & 11 deletions controllers/connect.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ const path = require('path')
const config = require(path.join(__dirname, '/../config'))
const GitHub = require(path.join(__dirname, '/../lib/GitHub'))

module.exports = (req, res) => {
module.exports = async (req, res) => {
const ua = config.get('analytics.uaTrackingId')
? require('universal-analytics')(config.get('analytics.uaTrackingId'))
: null
Expand All @@ -16,7 +16,9 @@ module.exports = (req, res) => {
token: config.get('githubToken')
})

return github.api.users.getRepoInvites({}).then(({data}) => {
try {
const { data } = await github.api.users.getRepoInvites({})

let invitationId = null

const invitation = data.some(invitation => {
Expand All @@ -28,23 +30,22 @@ module.exports = (req, res) => {
})

if (invitation) {
return github.api.users.acceptRepoInvite({
await github.api.users.acceptRepoInvite({
invitation_id: invitationId
})
res.send('OK!')

if (ua) {
ua.event('Repositories', 'Connect').send()
}
} else {
res.status(404).send('Invitation not found')
}
}).then(response => {
res.send('OK!')

if (ua) {
ua.event('Repositories', 'Connect').send()
}
}).catch(err => { // eslint-disable-line handle-callback-err
} catch (err) {
res.status(500).send('Error')

if (ua) {
ua.event('Repositories', 'Connect error').send()
}
})
}
}
3 changes: 1 addition & 2 deletions controllers/encrypt.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
'use strict'

const path = require('path')
const RSA = require(path.join(__dirname, '/../lib/RSA'))
const RSA = require('../lib/RSA')

module.exports = (req, res) => {
const encryptedText = RSA.encrypt(req.params.text)
Expand Down
29 changes: 13 additions & 16 deletions controllers/handlePR.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ const config = require('../config')
const GitHub = require('../lib/GitHub')
const Staticman = require('../lib/Staticman')

module.exports = (repo, data) => {
module.exports = async (repo, data) => {
const ua = config.get('analytics.uaTrackingId')
? require('universal-analytics')(config.get('analytics.uaTrackingId'))
: null
Expand All @@ -19,7 +19,9 @@ module.exports = (repo, data) => {
token: config.get('githubToken')
})

return github.getReview(data.number).then((review) => {
try {
const review = await github.getReview(data.number)

if (review.sourceBranch.indexOf('staticman_')) {
return null
}
Expand All @@ -32,33 +34,28 @@ module.exports = (repo, data) => {
const bodyMatch = review.body.match(/(?:.*?)<!--staticman_notification:(.+?)-->(?:.*?)/i)

if (bodyMatch && (bodyMatch.length === 2)) {
try {
const parsedBody = JSON.parse(bodyMatch[1])
const staticman = new Staticman(parsedBody.parameters)
const parsedBody = JSON.parse(bodyMatch[1])
const staticman = new Staticman(parsedBody.parameters)

staticman.setConfigPath(parsedBody.configPath)
staticman.processMerge(parsedBody.fields, parsedBody.options)
.catch(err => Promise.reject(err))
} catch (err) {
return Promise.reject(err)
}
staticman.setConfigPath(parsedBody.configPath)
await staticman.processMerge(parsedBody.fields, parsedBody.options)
}
}

return github.deleteBranch(review.sourceBranch)
}).then(response => {
const response = github.deleteBranch(review.sourceBranch)

if (ua) {
ua.event('Hooks', 'Delete branch').send()
}

return response
}).catch(err => {
} catch (err) {
console.log(err.stack || err)

if (ua) {
ua.event('Hooks', 'Delete branch error').send()
}

return Promise.reject(err)
})
throw err
}
}
106 changes: 51 additions & 55 deletions controllers/process.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,77 +7,70 @@ const reCaptcha = require('express-recaptcha')
const Staticman = require('../lib/Staticman')
const universalAnalytics = require('universal-analytics')

function checkRecaptcha (staticman, req) {
return new Promise((resolve, reject) => {
staticman.getSiteConfig().then(siteConfig => {
if (!siteConfig.get('reCaptcha.enabled')) {
return resolve(false)
}
async function checkRecaptcha (staticman, req) {
const siteConfig = await staticman.getSiteConfig()

const reCaptchaOptions = req.body.options && req.body.options.reCaptcha
if (!siteConfig.get('reCaptcha.enabled')) {
return false
}

if (!reCaptchaOptions || !reCaptchaOptions.siteKey || !reCaptchaOptions.secret) {
return reject(errorHandler('RECAPTCHA_MISSING_CREDENTIALS'))
}
const reCaptchaOptions = req.body.options && req.body.options.reCaptcha

let decryptedSecret
if (!reCaptchaOptions || !reCaptchaOptions.siteKey || !reCaptchaOptions.secret) {
throw errorHandler('RECAPTCHA_MISSING_CREDENTIALS')
}

try {
decryptedSecret = staticman.decrypt(reCaptchaOptions.secret)
} catch (err) {
return reject(errorHandler('RECAPTCHA_CONFIG_MISMATCH'))
}
let decryptedSecret

if (
reCaptchaOptions.siteKey !== siteConfig.get('reCaptcha.siteKey') ||
decryptedSecret !== siteConfig.get('reCaptcha.secret')
) {
return reject(errorHandler('RECAPTCHA_CONFIG_MISMATCH'))
}
try {
decryptedSecret = staticman.decrypt(reCaptchaOptions.secret)
} catch (err) {
throw errorHandler('RECAPTCHA_CONFIG_MISMATCH')
}

if (
reCaptchaOptions.siteKey !== siteConfig.get('reCaptcha.siteKey') ||
decryptedSecret !== siteConfig.get('reCaptcha.secret')
) {
throw errorHandler('RECAPTCHA_CONFIG_MISMATCH')
}

reCaptcha.init(reCaptchaOptions.siteKey, decryptedSecret)
reCaptcha.verify(req, err => {
if (err) {
return reject(errorHandler(err))
}
reCaptcha.init(reCaptchaOptions.siteKey, decryptedSecret)

return new Promise((resolve, reject) => {
reCaptcha.verify(req, err => {
if (err) {
return reject(errorHandler(err))
}

return resolve(true)
})
}).catch(err => reject(err))
return resolve(true)
})
})
}

function createConfigObject (apiVersion, property) {
let remoteConfig = {}

if (apiVersion === '1') {
remoteConfig.file = '_config.yml'
remoteConfig.path = 'staticman'
} else {
remoteConfig.file = 'staticman.yml'
remoteConfig.path = property || ''
}

return remoteConfig
return apiVersion === '1'
? { file: '_config.yml', path: 'staticman' }
: { file: 'staticman.yml', path: property || '' }
}

function process (staticman, req, res) {
async function process (staticman, req, res) {
const ua = config.get('analytics.uaTrackingId')
? universalAnalytics(config.get('analytics.uaTrackingId'))
: null
const fields = req.query.fields || req.body.fields
const options = req.query.options || req.body.options || {}

return staticman.processEntry(fields, options).then(data => {
sendResponse(res, {
redirect: data.redirect,
fields: data.fields
})
const data = await staticman.processEntry(fields, options)

if (ua) {
ua.event('Entries', 'New entry').send()
}
sendResponse(res, {
redirect: data.redirect,
fields: data.fields
})

if (ua) {
ua.event('Entries', 'New entry').send()
}
}

function sendResponse (res, data) {
Expand Down Expand Up @@ -120,20 +113,23 @@ function sendResponse (res, data) {
res.status(statusCode).send(payload)
}

module.exports = (req, res, next) => {
module.exports = async (req, res, next) => {
const staticman = new Staticman(req.params)

staticman.setConfigPath()
staticman.setIp(req.headers['x-forwarded-for'] || req.connection.remoteAddress)
staticman.setUserAgent(req.headers['user-agent'])

return checkRecaptcha(staticman, req)
.then(usedRecaptcha => process(staticman, req, res))
.catch(err => sendResponse(res, {
try {
await checkRecaptcha(staticman, req)
await process(staticman, req, res)
} catch (err) {
sendResponse(res, {
err,
redirect: req.body.options && req.body.options.redirect,
redirectError: req.body.options && req.body.options.redirectError
}))
})
}
}

module.exports.checkRecaptcha = checkRecaptcha
Expand Down
Loading

0 comments on commit d2b8c59

Please sign in to comment.