/
nodeko.coffee
430 lines (376 loc) · 12.4 KB
/
nodeko.coffee
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
# this entire application is pretty gross, by our own judgement. we'd love to
# clean it up, but we'd probably just rewrite the whole thing anyway. you have
# been warned.
sys = require 'sys'
connect = require 'connect'
express = require 'express'
models = require './models/models'
[Team, Person, Vote] = [models.Team, models.Person, models.Vote]
pub = __dirname + '/public'
app = express.createServer(
connect.compiler({ src: pub, enable: ['sass', 'coffee'] }),
connect.staticProvider(pub)
)
app.use connect.logger()
app.use connect.bodyDecoder()
app.use connect.methodOverride()
app.use connect.cookieDecoder()
Hoptoad = require('./lib/hoptoad-notifier/lib/hoptoad-notifier').Hoptoad
Hoptoad.key = 'b76b10945d476da44a0eac6bfe1aeabd'
process.on 'uncaughtException', (e) ->
Hoptoad.notify e
request = (type) ->
(path, fn) ->
app[type] path, (req, res, next) ->
Person.firstByAuthKey req.cookies.authkey, (error, person) =>
ctx = {
sys: sys
req: req
res: res
next: next
redirect: __bind(res.redirect, res),
cookie: (key, value, options) ->
value ||= ''
options ||= {}
options.path ||= '/'
cookie = "#{key}=#{value}"
for k, v of options
cookie += "; #{k}=#{v}"
res.header('Set-Cookie', cookie)
render: (file, opts, fn) ->
opts ||= {}
opts.locals ||= {}
opts.locals.view = file.replace(/\..*$/,'').replace(/\//,'-')
opts.locals.ctx = ctx
res.render file, opts, fn
currentPerson: person
isAdmin: person? && person.admin()
setCurrentPerson: (person, options) ->
@cookie 'authKey', person?.authKey(), options
redirectToTeam: (person, alternate) ->
Team.first { 'members._id': person._id }, (error, team) =>
if team?
@redirect '/teams/' + team.toParam()
else if alternate
alternate()
else
@redirect '/'
redirectToLogin: ->
@redirect "/login?return_to=#{@req.url}"
logout: (fn) ->
if @currentPerson?
@currentPerson.logout (error, resp) =>
@setCurrentPerson null
fn()
else fn()
canEditTeam: (team) ->
req.cookies.teamauthkey is team.authKey() or
team.hasMember(@currentPerson) or @isAdmin
ensurePermitted: (other, fn) ->
permitted = (@isAdmin or
other.hasMember? and @canEditTeam(other) or
!other.hasMember? and @currentPerson? and other.id() is @currentPerson.id())
if permitted then fn()
else
unless @currentPerson?
@redirectToLogin()
else
# TODO flash "Oops! You don't have permissions to see that. Try logging in as somebody else."
@redirectToLogin()}
try
__bind(fn, ctx)()
catch e
e.action = e.url = req.url
Hoptoad.notify e
next e
get = request 'get'
post = request 'post'
put = request 'put'
del = request 'del'
get /.*/, ->
[host, path] = [@req.header('host'), @req.url]
if host == 'www.nodeknockout.com' or host == 'nodeknockout.heroku.com'
@redirect "http://nodeknockout.com#{path}", 301
else
@next()
get '/', ->
@render 'index.html.haml'
get '/me', ->
if @currentPerson?
@redirect "/people/#{@currentPerson.toParam()}/edit"
else
@redirectToLogin()
get '/team', ->
if @currentPerson?
@redirectToTeam @currentPerson, __bind(@redirectToLogin, this)
else
@redirectToLogin()
get '/register', ->
if @currentPerson?
@redirectToTeam @currentPerson
else
@redirect "/login?return_to=#{@req.url}"
get '/error', ->
throw new Error('Foo')
# list teams
get '/teams', ->
Team.all (error, teams) =>
[@teams, @unverifiedTeams] = [[], []]
for team in _.shuffle(teams)
if team.members.length == team.invited.length
@unverifiedTeams.push team
else
@teams.push team
@yourTeams = if @currentPerson?
_.select teams, (team) =>
# TODO this is gross
_ids = _.pluck(team.members, '_id')
_.include _.pluck(_ids, 'id'), @currentPerson._id.id
else []
@render 'teams/index.html.haml'
# new team
get '/teams/new', ->
return @redirect '/' unless @isAdmin
@team = new Team {}, =>
@render 'teams/new.html.haml'
# create team
post '/teams', ->
return @redirect '/' unless @isAdmin
@team = new Team @req.body, =>
@team.save (errors, res) =>
if errors?
@errors = errors
@render 'teams/new.html.haml'
else
@cookie 'teamAuthKey', @team.authKey()
@redirect '/teams/' + @team.toParam()
# show team
get '/teams/:id', ->
Team.fromParam @req.param('id'), (error, team) =>
if team?
@team = team
@title = @team.name
@editAllowed = @canEditTeam team
people = team.members or []
@members = _.select people, (person) -> person.name
@invites = _.without people, @members...
renderVotes = =>
Vote.all { 'team._id': team._id }, { 'sort': [['createdAt', -1]], limit: 50 }, (error, votes) =>
@votes = votes
@render 'teams/show.html.haml'
if @currentPerson
Vote.firstByTeamAndPerson team, @currentPerson, (error, vote) =>
@vote = vote or new Vote(null, @req)
@vote.person = @currentPerson
@vote.email = @vote.person.email
renderVotes()
else
@vote = new Vote(null, @req)
renderVotes()
else
# TODO make this a 404
@redirect '/'
# edit team
get '/teams/:id/edit', ->
Team.fromParam @req.param('id'), (error, team) =>
@ensurePermitted team, =>
@team = team
@render 'teams/edit.html.haml'
# update team
put '/teams/:id', ->
Team.fromParam @req.param('id'), (error, team) =>
@ensurePermitted team, =>
team.update @req.body
save = =>
team.save (errors, result) =>
if errors?
@errors = errors
@team = team
if @req.xhr
@res.send 'ERROR', 500
else
@render 'teams/edit.html.haml'
else
if @req.xhr
@res.send 'OK', 200
else
@redirect '/teams/' + team.toParam()
# TODO shouldn't need this
if @req.body.emails
team.setMembers @req.body.emails, save
else save()
# delete team
del '/teams/:id', ->
Team.fromParam @req.param('id'), (error, team) =>
@ensurePermitted team, =>
team.remove (error, result) =>
@redirect '/'
# resend invitation
get '/teams/:teamId/invite/:personId', ->
Team.fromParam @req.param('teamId'), (error, team) =>
@ensurePermitted team, =>
Person.fromParam @req.param('personId'), (error, person) =>
person.inviteTo team, =>
if @req.xhr
@res.send 'OK', 200
else
# TODO flash "Sent a new invitation to $@person.email"
@redirect '/teams/' + team.toParam()
# new vote
get '/teams/:teamId/votes/new', ->
return @redirect '/teams/' + @req.param('teamId') unless @isAdmin
Team.fromParam @req.param('teamId'), (error, team) =>
# TODO: handle error
@team = team
@vote = new Vote
@email = @currentPerson?.email
@render 'votes/new.html.jade', { layout: 'layout.haml' }
# create vote
post '/teams/:teamId/votes', ->
return @redirect '/teams/' + @req.param('teamId') unless @isAdmin
Team.fromParam @req.param('teamId'), (error, team) =>
# TODO: handle error
@vote = new Vote @req.body, @req
@vote.team = @team = team
@vote.person = @currentPerson
@vote.save (errors, res) =>
if errors?
if errors[0] is 'Unauthorized'
# TODO flash "You must login to vote as #{@vote.email}."
@res.send 'Unauthorized', 403
else
@res.send JSON.stringify(errors), 400
else
# TODO flash "You are now logged into Node Knockout as #{@vote.email}."
@setCurrentPerson @vote.person if @vote.person? and !@currentPerson?
@noHeader = true
@votes = [@vote]
@render 'partials/votes/index.html.jade', { layout: false }
# list votes
get '/teams/:teamId/votes', ->
@redirect '/teams/' + @req.param('teamId')
get '/teams/:teamId/votes.js', ->
skip = 50 * ((@req.query['page'] || 1)-1)
Team.fromParam @req.param('teamId'), (error, team) =>
# TODO: handle error
Vote.all { 'team._id': team._id }, { 'sort': [['createdAt', -1]], skip: skip, limit: 50 }, (error, votes) =>
@votes = votes
@render 'partials/votes/index.html.jade', { layout: false }
# sign in
get '/login', ->
@person = new Person()
@render 'login.html.haml'
post '/login', ->
Person.login @req.body, (error, person) =>
if person?
if @req.param 'remember'
d = new Date()
d.setTime(d.getTime() + 1000 * 60 * 60 * 24 * 180)
options = { expires: d }
@setCurrentPerson person, options
if person.name
if returnTo = @req.param('return_to')
@redirect returnTo
else @redirectToTeam person
else
@redirect '/people/' + person.toParam() + '/edit'
else
@errors = error
@person = new Person(@req.body)
@render 'login.html.haml'
get '/logout', ->
@logout => @redirect(@req.param('return_to') || @req.headers.referer || '/')
# reset password
post '/reset_password', ->
Person.first { email: @req.param('email') }, (error, person) =>
# TODO assumes xhr
unless person?
@res.send 'Email not found', 404
else
person.resetPassword =>
@res.send 'OK', 200
# new judge
get '/judges/new', ->
@person = new Person({ type: 'Judge' })
@ensurePermitted @person, =>
@render 'judges/new.html.haml'
get '/judges|/judging', ->
Person.all { type: 'Judge' }, (error, judges) =>
@judges = _.shuffle judges
@render 'judges/index.html.jade', { layout: 'layout.haml' }
# create person
post '/people', ->
@person = new Person @req.body
@ensurePermitted @person, =>
@person.save (error, res) =>
# TODO send confirmation email
@redirect '/people/' + @person.toParam() + '/edit'
# edit person
get '/people/:id/edit', ->
Person.fromParam @req.param('id'), (error, person) =>
@ensurePermitted person, =>
@person = person
@render 'people/edit.html.haml'
# update person
put '/people/:id', ->
Person.fromParam @req.param('id'), (error, person) =>
@ensurePermitted person, =>
attributes = @req.body
# TODO this shouldn't be necessary
person.setPassword attributes.password if attributes.password
delete attributes.password
attributes.link = '' unless /^https?:\/\/.+\./.test attributes.link
if attributes.email? && attributes.email != person.email
person.confirmed = attributes.confimed = false
person.github ||= ''
person.update attributes
person.save (error, resp) =>
@redirectToTeam person
post '/deploys', ->
# user: 'visnupx@gmail.com'
# head: '87eaeb6'
# app: 'visnup-nko'
# url: 'http://visnup-nko.heroku.com'
# git_log: ''
# prev_head: ''
# head_long: '87eaeb69d726593de6a47a5f38ff6126fd3920fa'
# TODO don't let anyone post here
sys.log sys.inspect(@req)
query = {}
deployedTo = if /\.no\.de$/.test(@req.param('url')) then 'joyent' else 'heroku'
query[deployedTo + 'Slug'] = @req.param('app')
Team.first query, (error, team) =>
if team
team.url = @req.param('url')
team.lastDeployedTo = deployedTo
team.lastDeployedAt = new Date()
team.save(->)
@render 'deploys/ok.html.haml', { layout: false }
get '/prizes', ->
@render 'prizes.html.jade', { layout: 'layout.haml' }
get '/*', ->
try
@render "#{@req.params[0]}.html.haml"
catch e
throw e if e.errno != 2
@next()
app.helpers {
pluralize: (n, str) ->
if n == 1
n + ' ' + str
else
n + ' ' + str + 's'
escapeURL: require('querystring').escape
markdown: require('markdown').toHTML
gravatar: (p, s) ->
"<img src=\"http://www.gravatar.com/avatar/#{p.emailHash}?s=#{s || 40}&d=monsterid\" />"
}
_.shuffle = (a) ->
r = _.clone a
for i in [r.length-1 .. 0]
j = parseInt(Math.random() * i)
[r[i], r[j]] = [r[j], r[i]]
r
# has to be last
app.use '/', express.errorHandler({ dumpExceptions: true, showStack: true })
server = app.listen parseInt(process.env.PORT || 8000), null