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

async-auth #10

Closed
wants to merge 2 commits into from
Closed
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
38 changes: 19 additions & 19 deletions app.js
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ var app = express()

// session cookies
app.use(cookieSession({
name: 'mangrove-retreat-session',
name: 'mangrove-retreat-session',
keys: _.filter([process.env.SECRET_KEY, 'M@ngR0ve']),
maxAge: 30 * 24 * 3600 * 1000 // 30 days
}))
Expand Down Expand Up @@ -54,17 +54,17 @@ app.use(bodyParser.urlencoded({ extended: false }))
app.use(cookieParser())

app.use('/stylesheets', sassMiddleware({
src: __dirname + '/public/sass',
dest: __dirname + '/public/stylesheets',
debug: true,
outputStyle: 'expanded'
src: __dirname + '/public/sass',
dest: __dirname + '/public/stylesheets',
debug: true,
outputStyle: 'expanded'
}))

app.use('/stylesheets', postcssMiddleware({
src: function(req) {
return path.join(__dirname, 'public', 'stylesheets', req.path)
},
plugins: [autoprefixer()]
src: function(req) {
return path.join(__dirname, 'public', 'stylesheets', req.path)
},
plugins: [autoprefixer()]
}))

app.use(express.static(path.join(__dirname, 'public')))
Expand All @@ -73,25 +73,25 @@ app.use('/', index)

// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found')
err.status = 404
next(err)
var err = new Error('Not Found')
err.status = 404
next(err)
})

// error handler
app.use(function(err, req, res, next) {
// set locals, only providing error in development
const isDev = req.app.get('env') === 'development'
// set locals, only providing error in development
const isDev = req.app.get('env') === 'development'

// render the error page
res.status(err.status || 500)
res.render('error', {error: isDev ? err : null})
// render the error page
res.status(err.status || 500)
res.render('error', {error: isDev ? err : null})
})

// proper logging of UnhandledPromiseRejection
process.on('unhandledRejection', function(reason, p) {
console.log("Possibly Unhandled Rejection at: Promise ",
p, " reason: ", reason, reason ? reason.message : null)
console.log("Possibly Unhandled Rejection at: Promise ",
p, " reason: ", reason, reason ? reason.message : null)
})

module.exports = app
8 changes: 4 additions & 4 deletions helpers/airtable.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,8 @@ var Airtable = require('airtable')
var base = new Airtable({apiKey: process.env.AIRTABLE_API_KEY}).base(process.env.AIRTABLE_BASE_KEY)

module.exports = {
retreat: base('Retreats'),
participants: base('Retreat Participants'),
faq: base('Retreat FAQ'),
members: base('Members')
retreat: base('Retreats'),
participants: base('Retreat Participants'),
faq: base('Retreat FAQ'),
members: base('Members')
}
50 changes: 25 additions & 25 deletions helpers/bedsCounter.js
Original file line number Diff line number Diff line change
@@ -1,35 +1,35 @@
function haveDaysInCommon(days1, days2) {
for (var i = 0; i < days1.length; i++) {
var day1 = days1[i]
for (var j = 0; j < days2.length; j++) {
var day2 = days2[j]
if (day1.id === day2.id) {
return true
}
}
}
return false
for (var i = 0; i < days1.length; i++) {
var day1 = days1[i]
for (var j = 0; j < days2.length; j++) {
var day2 = days2[j]
if (day1.id === day2.id) {
return true
}
}
}
return false
}

function addBedsCountPerWeek(retreat, participants) {
for (var i = 0; i < retreat.weeks.length; i++) {
var bedsAvailable = retreat.house.beds
var week = retreat.weeks[i]
for (var i = 0; i < retreat.weeks.length; i++) {
var bedsAvailable = retreat.house.beds
var week = retreat.weeks[i]

// Remove a bed each time a participant is found in the week
for (var j = 0; j < participants.length; j++) {
var participant = participants[j]
if (haveDaysInCommon(week.days, participant.days)) {
bedsAvailable -= 1
}
}
// Remove a bed each time a participant is found in the week
for (var j = 0; j < participants.length; j++) {
var participant = participants[j]
if (haveDaysInCommon(week.days, participant.days)) {
bedsAvailable -= 1
}
}

// Add beds count to week
retreat.weeks[i].beds = bedsAvailable
}
return retreat
// Add beds count to week
retreat.weeks[i].beds = bedsAvailable
}
return retreat
}

module.exports = {
addBedsCountPerWeek: addBedsCountPerWeek
addBedsCountPerWeek: addBedsCountPerWeek
}
76 changes: 38 additions & 38 deletions helpers/dateFormatter.js
Original file line number Diff line number Diff line change
@@ -1,51 +1,51 @@
function formatDay(date) {
const weekDays = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat']
const months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Nov', 'Dec']
return {
id: months[date.getMonth()] + date.getDate(),
name: weekDays[date.getDay()],
number: date.getDate(),
month: months[date.getMonth()],
date: date
}
const weekDays = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat']
const months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Nov', 'Dec']
return {
id: months[date.getMonth()] + date.getDate(),
name: weekDays[date.getDay()],
number: date.getDate(),
month: months[date.getMonth()],
date: date
}
}

function formatWeeks(beginDate, endDate) {
var days = []
var day = new Date(beginDate)

while(day.getTime() < new Date(endDate).getTime()) {
days.push(formatDay(day))
day = new Date(day.getTime() + 24 * 60 * 60 * 1000)
}
days.push(formatDay(new Date(endDate)))

var weeks = []
for (var i = 0; i < days.length; i++) {
if (i % 7 == 0) {
weeks.push({days: []})
}
var weekIndex = parseInt(i / 7)
weeks[weekIndex].days.push(days[i])
}

return weeks
var days = []
var day = new Date(beginDate)

while(day.getTime() < new Date(endDate).getTime()) {
days.push(formatDay(day))
day = new Date(day.getTime() + 24 * 60 * 60 * 1000)
}
days.push(formatDay(new Date(endDate)))

var weeks = []
for (var i = 0; i < days.length; i++) {
if (i % 7 == 0) {
weeks.push({days: []})
}
var weekIndex = parseInt(i / 7)
weeks[weekIndex].days.push(days[i])
}

return weeks
}

function formatDays(beginDate, endDate) {
var days = []
var day = new Date(beginDate)
var days = []
var day = new Date(beginDate)

while(day.getTime() < new Date(endDate).getTime()) {
days.push(formatDay(day))
day = new Date(day.getTime() + 24 * 60 * 60 * 1000)
}
days.push(formatDay(new Date(endDate)))
while(day.getTime() < new Date(endDate).getTime()) {
days.push(formatDay(day))
day = new Date(day.getTime() + 24 * 60 * 60 * 1000)
}
days.push(formatDay(new Date(endDate)))

return days
return days
}

module.exports = {
formatDays: formatDays,
formatWeeks: formatWeeks
formatDays: formatDays,
formatWeeks: formatWeeks
}
Binary file removed mangrove_retreat.textClipping
Binary file not shown.
70 changes: 35 additions & 35 deletions middleware/auth.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,54 +6,54 @@ const airtable = require('../helpers/airtable.js')


function checkCode(code) {
return new Promise(function (resolve, reject) {
request.get('https://slack.com/api/oauth.access?code=' + code + '&client_id=' + clientId
+ '&client_secret=' + clientSecret + '&redirect_uri=' + slackRedirectUri,
function (error, response, body) {
if (!error && response.statusCode == 200) {
body = JSON.parse(body)
if (body.error) return reject(body.error)
return new Promise(function (resolve, reject) {
request.get('https://slack.com/api/oauth.access?code=' + code + '&client_id=' + clientId
+ '&client_secret=' + clientSecret + '&redirect_uri=' + slackRedirectUri,
function (error, response, body) {
if (!error && response.statusCode == 200) {
body = JSON.parse(body)
if (body.error) return reject(body.error)
// resolve with user AccessToken and Slack ID
resolve({
slackId: body.user_id,
accessToken: body.access_token,
})
} else { reject(error) }
})
})
} else { reject(error) }
})
})
}

// retrieves details about a Member from Airtable based on their Slack ID
function getMemberBySlackId(slackId) {
return new Promise(function (resolve, reject) {
airtable.members.select({
return new Promise(function (resolve, reject) {
airtable.members.select({
maxRecords: 10,
filterByFormula: `{Slack ID} = '${slackId}'`,
}).firstPage(function(err, records) {
if (err) { reject(err); return }
if (typeof records[0] !== 'undefined') {
resolve(formatMember(records[0]))
} else {
reject('No members found matching username : ' + username)
}
})
})
filterByFormula: `{Slack ID} = '${slackId}'`,
}).firstPage(function(err, records) {
if (err) { reject(err); return }
if (typeof records[0] !== 'undefined') {
resolve(formatMember(records[0]))
} else {
reject('No members found matching username : ' + username)
}
})
})

function formatMember(currentUser) {
const tw = currentUser.get('Twitter') && currentUser.get('Twitter').length ? currentUser.get('Twitter') : null
const img = tw ? 'https://twitter.com/' + tw + '/profile_image?size=original' : null
function formatMember(currentUser) {
const tw = currentUser.get('Twitter') && currentUser.get('Twitter').length ? currentUser.get('Twitter') : null
const img = tw ? 'https://twitter.com/' + tw + '/profile_image?size=original' : null

return {
id: currentUser.id,
name: currentUser.get('Name'),
return {
id: currentUser.id,
name: currentUser.get('Name'),
slackId: currentUser.get('Slack ID'),
color: 'black',
avatar_url: img
}
}
color: 'black',
avatar_url: img
}
}
}

module.exports = {
checkCode: checkCode,
getMemberBySlackId: getMemberBySlackId
}
checkCode: checkCode,
getMemberBySlackId: getMemberBySlackId
}
58 changes: 29 additions & 29 deletions middleware/charge.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,36 +5,36 @@ const price = require('./price.js')
const participants = require('./participants.js')

function charge(memberAirtableId, params) {
return new Promise(function (resolve, reject) {
price.compute(params)
.then(function (result) {
if (result.canBook) {
participants.getParticipantByMemberId(memberAirtableId).then(function (participant) {
stripe.customers.create({
email: params.email,
source: params.tokenId,
description: (`Member ID: ${memberAirtableId}`),
}).then(function (customer) {
const amountInCents = result.price * 100
stripe.charges.create({
amount: amountInCents,
description: result.description,
currency: "eur",
customer: customer.id
}).then(function (charge) {
participants.add(participant.id, params.retreatId, params.firstNight, params.lastNight).then(function () {
resolve()
})
})
})
}, function (error) { reject(error) })
} else {
reject('You cannot book this retreat for the desired dates. Week is either full or you chose custom dates.')
}
}, function (error) { reject(error) })
})
return new Promise(function (resolve, reject) {
price.compute(params)
.then(function (result) {
if (result.canBook) {
participants.getParticipantByMemberId(memberAirtableId).then(function (participant) {
stripe.customers.create({
email: params.email,
source: params.tokenId,
description: (`Member ID: ${memberAirtableId}`),
}).then(function (customer) {
const amountInCents = result.price * 100
stripe.charges.create({
amount: amountInCents,
description: result.description,
currency: "eur",
customer: customer.id
}).then(function (charge) {
participants.add(participant.id, params.retreatId, params.firstNight, params.lastNight).then(function () {
resolve()
})
})
})
}, function (error) { reject(error) })
} else {
reject('You cannot book this retreat for the desired dates. Week is either full or you chose custom dates.')
}
}, function (error) { reject(error) })
})
}

module.exports = {
charge: charge
charge: charge
}
Loading